0

I've got a bit of javascript that is just not working in IE.

function resize($img) {
    var max_size_w = 200;
    var max_size_h = 200;
    var h = $img.height();
    var w = $img.width();
    if (h > max_size_h) {
        h = max_size_h;
        w = Math.ceil($img.width() / $img.height() * max_size_h);
    }
    if (w > max_size_w) {
        h = Math.ceil($img.height() / $img.width() * max_size_w);
        w = max_size_w;
    }
    $img.css({ height: h, width: w });
}

$(window).load(function() {
    // Size the images correctly
    $(".personPictureImage").each(function() {
        var $img = $(this).find("img");
        $img.load(function() { resize($(this)); });
        if($img.height())
            resize($img);
    });
});

In every other browser it resizes an image to fit in a 200x200 box. In IE I get a size of 30px by =28px. In chrome I get 200px by 142px.

I know IE has issues and is generally a horrible browser but I'm trying to support it anyway. How can I fix my code to work in IE?

Justin808
  • 20,859
  • 46
  • 160
  • 265

1 Answers1

0

Try to replace

var max_size_w = 200;
var max_size_h = 200;
var h = $img.height();
var w = $img.width();
if (h > max_size_h) {
    h = max_size_h;
    w = Math.ceil($img.width() / $img.height() * max_size_h);
}
if (w > max_size_w) {
    h = Math.ceil($img.height() / $img.width() * max_size_w);
    w = max_size_w;
}

with this calculation

var MAX=200,wi=$img.width(),he=$img.height(),
r=MAX/Math.max(wi,he),
w=Math.round(wi*r),
h=Math.round(he*r);

..

var MAX=200,
r=MAX/Math.max(this.width,this.height),
w=Math.round(this.width*r),
h=Math.round(this.height*r);

taken from here.

https://stackoverflow.com/a/17502568/2450730

ps.: r is the RATIO & i would also use pure javascript as everything you do is supported by all browsers.

Community
  • 1
  • 1
cocco
  • 16,442
  • 7
  • 62
  • 77