Resize function timing problem
Posted: Mon Jan 25, 2010 1:54 am
Hello all 
On my front page I have a "featured" image thats being pulled out of a DB and displayed. Problem is, it's either too tall or too wide for the div it's in, so I wrote a function that resizes it to keep it in check. Code as follows:
It works, but sometimes I have to refresh to get the image to appear.
I have a feeling it's due to the timing of the DOM and the image being available, but I'm still wrapping my head around all this client side stuff. Right now the js files these classes/functions reside in are right before the </body> tag, as I've read it's best to put these sorts of things there so the document is loaded in time.
Thanks
On my front page I have a "featured" image thats being pulled out of a DB and displayed. Problem is, it's either too tall or too wide for the div it's in, so I wrote a function that resizes it to keep it in check. Code as follows:
Code: Select all
$.prototype.Images = {
changeSize : function(id, maxWidth, maxHeight){
var im = document.getElementById(id);
var ratio = im.width < im.height ? im.height/im.width : im.width/im.height;
if(im.width > im.height){
//horiz
im.width = maxWidth;
im.height = maxWidth / ratio;
}else{
//vert
im.height = maxHeight;
im.width = maxHeight / ratio;
}
}
}
//useage
$.Images.changeSize("featuredImg", 480, 400);
I have a feeling it's due to the timing of the DOM and the image being available, but I'm still wrapping my head around all this client side stuff. Right now the js files these classes/functions reside in are right before the </body> tag, as I've read it's best to put these sorts of things there so the document is loaded in time.
Thanks