View Full Version : Change Width & Height Dynamically of Div

07-15-2009, 08:18 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">

<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;



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


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



07-16-2009, 06:51 AM
You are using percentages because you don't know the height and width of the next image? Whether you use some proportional aspect, or fit the border right to the image, I believe all modern browsers include "width" and "height" properties for "img" elements. Just give it an "id" attribute so you can find it. And you should be able to read height/width and adjust your border as you wish.

07-16-2009, 03:20 PM
Thank you, that's very helpful advice