Page 1 of 1

Resize function timing problem

Posted: Mon Jan 25, 2010 1:54 am
by Phix
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:

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

Re: Resize function timing problem

Posted: Mon Jan 25, 2010 7:31 am
by daedalus__
if you are pulling the image out of a db anyway then re-size it using the GD library.

Re: Resize function timing problem

Posted: Mon Jan 25, 2010 1:58 pm
by Phix
I thought I may have worded it wrong. The path is being pulled, not the actual image data.

Re: Resize function timing problem

Posted: Mon Jan 25, 2010 2:08 pm
by pickle
I've seen in Firefox that if you set the width of an image to a percentage, the height resizes according to the ratio. You can try setting the width of the image to 100% & see if other browsers display the height properly.

Re: Resize function timing problem

Posted: Mon Jan 25, 2010 2:51 pm
by daedalus__
it should work like that in most browsers if you resize one dimension and leave the other unspecified.

phix you are missing the point of what i said. you are already doing work on the image through the back-end. just do a little more. it will work almost every time and not be as fussy as other methods. you'll also be cutting a little off the file size which is always a good thing.

Re: Resize function timing problem

Posted: Mon Jan 25, 2010 4:59 pm
by Phix
phix you are missing the point of what i said. you are already doing work on the image through the back-end. just do a little more.
My mistake... I suppose I could look into that, I was just hoping to get it done with js. But you're right, the file size decrease is probably worth it.

Thanks for the input fellas.