Brandon Steward
Brandon Steward

Reputation: 21

JS custom resize function using wrong image sizes only in certain browers

I'm having a bizarre issue. I wrote a small function to resize images on a site I'm working on, and it works for every image on the site except two that are in a dynamically-sized container. In IE10 and Firefox, both inconsistently use the wrong width/height for the image and instead spit out a bizarre number and the formula then messes up the resizing of the image.

The general picture of what I'm trying to do is this: I have one section of the site that is supposed to be the entire height of the screen, minus 60px to account for the fixed nav menu. The two images are inside this section and should be half its height and width (there are four even-sized squares in this section, two of which contain the images in question). Since the height of the section is dynamically calculated on pageload (100% of browser height minus 60px), I'm assuming that sometimes this function runs before the height of the container is properly calculated, so the images get scaled weirdly.

Here's what I believe is all the relevant code:

function onResize() {

    var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)

    $("#FourSquareSectionContainer").css("height", h - 60 );

    ResizeItem($("#SecondSquareBGImage"), (w / 2), ((h - 60)  / 2));
    ResizeItem($("#ThirdSquareBGImage"), (w / 2), ((h - 60)  / 2));

}

function ResizeItem(item, w, h) {

    var aspect = item.width() / item.height();
    var SlideWidth = aspect * h;
    var SlideHeight = w / aspect;

    if (SlideWidth < w) SlideWidth = SlideHeight * aspect;
    if (SlideHeight < h) SlideHeight = SlideWidth / aspect;

    item.width(SlideWidth);
    item.height(SlideHeight);
    item.css('top', Math.ceil((h - SlideHeight) / 2));
    item.css('left', Math.ceil((w - SlideWidth) / 2));

}

My assumption is that, since the height of the FourSquareSectionContainer is dynamic (it's supposed to always be 60px less than the full height of the page), and since the height of the SecondSquareBGImage and ThirdSquareBGImage are dependent on this height (they should both be half the height of FourSquareSectionContainer and half its width), some sort of race condition is happening where occasionally the wrong size is used for the images and they get too stretched.

It's probably relevant to note this issue only happens (again, inconsistently) in IE10 and Firefox. Chrome and Safari never have this issue.

This issue has been plaguing me for a while, and I'm not really sure of what the proper solution would be. As I said, this issue is jarringly inconsistent and only happens in IE10 and rarely Firefox. Any help would be appreciated! Thanks in advance!

Upvotes: 1

Views: 75

Answers (0)

Related Questions