PDA

View Full Version : Change Width & Height Dynamically of Div



theflyingminstrel
07-15-2009, 07:59 PM
Hi. This script changes the image, I wanted to know if there is a way to automatically resize the div's height and width based on the actual image proportions.

Thank you


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Switch Picture</title>

<script type="text/javascript">
function changeIt(imageName,objName)
{
var obj = document.getElementById(objName);
var imgTag = "<img src='"+imageName+"' width='100%' height='100%' border='0' />";
obj.innerHTML = imgTag;
return;
}
</script>

</head>

<body>

<div id="change" style="width:200px; height:200px;">
<img src="cat.jpg" width="100%" height="100%" border="0" />
</div>

<br/>

<a href="#" onclick="changeIt('dog.jpg','change');">Switch to Dog Pic</a>

</body>

</html>

Jesdisciple
07-17-2009, 01:32 AM
image.clientWidth and image.clientHeight are what you want:
https://developer.mozilla.org/en/DOM/element.clientWidth
https://developer.mozilla.org/en/DOM/element.clientHeight
http://msdn.microsoft.com/en-us/library/ms533563(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms533566(VS.85).aspx

vwphillips
07-17-2009, 11:42 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Switch Picture</title>

<script type="text/javascript">
function changeIt(id,src,sec){
var obj = document.getElementById(id);
if (!obj.oop) obj.oop=new changeItLoad(obj,sec);
obj.oop.srt=new Date();
obj.oop.newimg=new Image();
obj.oop.newimg.src=src+'?'+obj.oop.srt.getTime();
clearTimeout(obj.oop.to);
obj.oop.load();
return;
}

function changeItLoad(obj,sec){
this.obj=obj;
this.to=null;
this.sec=sec||10;
}

changeItLoad.prototype.load=function(){
if (this.newimg.complete){
this.obj.style.width=this.newimg.width+'px';
this.obj.style.height=this.newimg.height+'px';
this.obj.getElementsByTagName('IMG')[0].src=this.newimg.src;
}
else if ((new Date()-this.srt)/1000<this.sec){
var oop=this;
this.to=setTimeout(function(){ oop.load(); },100);
}
}
</script>

</head>

<body>

<div id="change" style="width:200px; height:200px;border:solid black 1px;">
<img src="http://www.vicsjavascripts.org.uk/StdImages/One.gif" width="100%" height="100%" border="0" />
</div>

<br/>

<a href="#" onclick="changeIt('change','http://www.vicsjavascripts.org.uk/StdImages/Three.gif',10);">Switch to Three</a>
<a href="#" onclick="changeIt('change','http://www.vicsjavascripts.org.uk/StdImages/Four.gif',10);">Switch to Four</a>

</body>

</html>