jurchiks
jurchiks

Reputation: 1433

Weird issues with image resizing in JavaScript (problems only in Firefox)

Code:

function resizeImage()
{
    // this just dynamically changes the width of the wrapper depending on the popup width
    // to properly calculate what size should the image be fit into
    var largeWidth = gallery.offsetWidth - 300;
    setStyle(div, "width: " + largeWidth + "px");
    maxWidth = div.offsetWidth;
    if (maxWidth < 300) // can only happen if CSS max-width is not supported
    {
        maxWidth = 300;
    }
    maxHeight = div.offsetHeight - 60;
    if (maxHeight < 240)
    {
        maxHeight = 240;
    }
    var style = "width: " + ((origWidth > maxWidth) ? maxWidth : origWidth) + "px;";
    setStyle(img, style); // at this point the image is fit into the wrapper by width, still need to check the height
    if (img.height >= maxHeight) // the height is out of bounds
    {
        style = "height: " + maxHeight + "px;";
    }
    else // height is not enough, pad it by half (hack for vertical-align: middle...)
    {
        style += 'padding-top: ' + Math.floor((maxHeight - img.height) / 2) + "px";
    }
    setStyle(img, style);
}

The problem:
Every browser I tested (IE 7,8,9 document modes (padding and margin: auto doesn't work in Quirks Mode so no centering there), Safari 5.1.2, Opera 11.61, Chrome 17.0.963.66) does this job reasonably well, padding is always correct no matter how fast I switch the images (there are thumbnails to the right of the big image and images can be switched using arrow keys aswell). BUT Firefox 10.0(.2) has a weird problem: when you switch images, more often than not the padding/height is broken (sometimes padding is >3x more than it should be or it isn't there at all, or height doesn't switch etc.). Is there a problem in the way Firefox resizes images or something? Because I can't figure out why only Firefox does this (even the damn IE works perfectly compared to FF).

If there is need for additional info, ask away. I could, of course, just add a link to the actual page, but I'm not sure if it is allowed so I'll refrain from doing that for now.

Edit: ok, I've managed to get a little closer to the problem (I think). When I change the source of the image (img.src) and console.log the img.width and img.height, the source changes but the width and height DO NOT!! And it happens only in Firefox! WTF is that?

Upvotes: 0

Views: 486

Answers (1)

Boris Zbarsky
Boris Zbarsky

Reputation: 35064

When you change .src the spec says the new image is loaded async. This is true even if it's been "preloaded". What that means is that the width/height, which depend on the image that's currently loaded, change async as well.

So if you set .src and immediately read the width/height you should get the old image dimensions, per spec. Use an onload handler to wait for the image to actually load?

Upvotes: 1

Related Questions