Punitha Balan 0 Newbie Poster

An approach would be to create the divs on load of the page and make them hidden with CSS. Then onclick of button just make all of them visible and on clicking on each div make that hidden again.
Creating and removing elements dynamically in JS is slow and errorprone(if the removal is not properly handled) process compared to just controlling the display with CSS

Posting a modified version of your code for reference. Improvise it as per your needs

<html>
<head>
<script type="text/javascript">

//detecting the browser version
var bname = navigator.appName;
var isIE = false;
if (bname == "Microsoft Internet Explorer"){
	isIE = true;
}
else{
	isIE = false;
}


function create_div_dynamic(){

	for(i=0; i<3; i++) {
		dv = document.createElement('div'); // create dynamically div tag
		dv.setAttribute('id',"lyr"+i); //give id to it
		dv.className="top"; // set the style classname
		//set the inner styling of the div tag
		dv.style.position="absolute";
		dv.style.pixelLeft=20;
		dv.style.top=100*(i+1); //since the position is absolute multiplying with i+1 to able to view all the divs
		dv.style.pixelWidth=10;
		dv.style.pixelHeight=20;
		dv.style.backgroundColor="red";

		//Make the divs hidden
		dv.style.visibility="hidden";
		dv.style.display="none";

		//set the html content inside the div tag
		dv.innerHTML='<br> hiiiiiiiiii '+i+'<br>';

		// attach event onmouseclick to the created div tag
		if(isIE){
			dv.onclick = new Function("element_event_onmouseclick('lyr"+i+"')");
		}
		else{
			dv.setAttribute("onclick", "element_event_onmouseclick('lyr"+i+"')");
		}

		//finally add the div id to ur form
		document.forms[0].appendChild(dv);
	}
}

function element_event_onmouseclick(lyr) //its called for onmouseclick
{
	dv = document.getElementById(lyr);
	dv.style.visibility="hidden";
	dv.style.display="none";

}

function show_div_dynamic() //to show all the div
{
	for(i=0; i<3; i++) {
		dv = document.getElementById('lyr'+i);
		dv.style.visibility="visible";
		dv.style.display="block";
	}
}


//Create the div elements on load
window.onload=create_div_dynamic;


</script>
</head>

<body>
<form name = form1>
<input type="button" value="Show DIV" onclick = show_div_dynamic()>
</form>

</body>
</html>

Hi,

I'm trying to set Height and Width to a div in Javascript.
I'm using PixelWidth and PixelHeight property.
Its working fine in IE but not in Firefox.
Can anyone help me?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.