I'm building a fluid website in which an image must scale to a maximum size depending on the viewport of the browser (minus some margins). I don't want the image to crop or lose its original proportions, so depending on the width or height it should resize to the maximum size possible without cropping.
I wrote some javascript code, but since I'm not a hardcore coder I was wondering how to fix this in the right way. The script works, but has a bug when resizing. It seems that it only processes one if statement when resizing the browser window.
function setSizes() {
    var margin_top = 100;
    var margin_right = 85;
    var margin_bottom = 10;
    var margin_left = 85;
    // get image width and height
    var img_w = $('.gallery_img').width();
    var img_h = $('.gallery_img').height();
    // calculate viewport width and height
    var vp_w = $(window).width() - margin_right - margin_left;
    var vp_h = $(window).height() - margin_top - margin_bottom;
    //
    if (vp_w <= img_w || vp_w > img_w) {
        // new width
        var img_w_new=vp_w;
        // calculate new height
        var img_h_new=Math.round((img_h*img_w_new) / img_w);
    }
    //
    if (vp_h <= img_h || vp_h > img_h) {
        // new height
        var img_h_new=vp_h;
        // calculate new width
        var img_w_new=Math.round((img_w*img_h_new) / img_h);
    }
    // change image width and height to new width and new height
    $('.gallery_img').width(img_w_new);
    $('.gallery_img').height(img_h_new);
}
// onload
$(window).load(function(){ setSizes(); });
// on resize
$(window).bind("resize", function() { setSizes(); });
I searched for a solution for quite some time, but most scripts I found only check and change the width.
Does somebody know how to fix this?
Thanx!