PDA

View Full Version : Dynamically resizing images with onLoad


kyozoku
09-22-2005, 02:11 AM
Hello,
I am having a problem getting this script to work. What I want to do is resize each image having the name "Resizeable" once the page has loaded. THe images need to be 250px wide but they are of varying dimensions so the height has to be determined by finding the change in width. The page is at www.itailers.com/auction-template.html , I know there are style issues happening but I can fix those later.
The script I am using is
<script type="text/javascript">
function imgResize()
{
var Children = document.getElementsByName("Resizeable");
var Endpoint = Children.Length;

//Go through all images and resize them accordingly.
for (var i = 0; i < Endpoint; ++i)
{
var currWidth = Children[i].style.width;
document.write("currWidth");
var currHeight = Children[i].style.height;
var Width = 250;
var Factor = currWidth/Width;

Children[i].style.width = currWidth * Factor;
Children[i].style.height = currHeight * Factor;
}

}
</script>
I am calling the function like this
<body onLoad="imgResize()">

Any idea why this won't work in either IE or Fx?

a_leon
09-22-2005, 03:07 AM
I've never had good luck with "getElementsByName". Everytime I've used it...it would only error.

I would try giving them a class of "resizeable" and looping through the images and grabbing them by class.

kyozoku
09-22-2005, 05:00 AM
Alright, I got it.

<script type="text/javascript">
function imgResize()
{
var TD = document.getElementById("ImageRow");
var Children = TD.getElementsByTagName("img");
var Endpoint = Children.length;

//Go through all images and resize them accordingly.
for (var i = 0; i < Endpoint; ++i)
{
var WorkElement = Children[i];
var currWidth = WorkElement.width;

var currHeight = WorkElement.height;
var Width = 250;
var Factor = eval(currWidth/Width);

WorkElement.width = 250;
WorkElement.height = (currHeight * (250/currWidth));
}
}
</script>

glenngv
09-22-2005, 07:39 AM
You don't need to manually calculate the ratio of the width and height. Let CSS do it. No scripting required.
<style type="text/css">
.Resizeable{
width:250px;
height:auto;
}
</style>
...
<img class="Resizeable" src="http://www.itailers.com/current/double1.jpg" alt="" />
<img class="Resizeable" src="http://www.itailers.com/current/double2.jpg" alt="" />
<img class="Resizeable" src="http://www.itailers.com/current/double3.jpg" alt="" />
<img class="Resizeable" src="http://www.itailers.com/current/double4.jpg" alt="" />