0

I've got a .content element on my website which contains the main content. I want to be able to resize the images when the browser gets resized. So I've made a jQuery function.

First the setImgData() function is called. This loops all the images and sets the original size as a data-w and data-h attribute.

After that the resizeImg() is called. Based on the original width and height the image will be resized to maximal the content width (keeping the aspect ratio).

The problem is that the data-* attribute doesn't get set. Probably because the $(this) inside the load function doesn't point to the content image.

Any ideas how I can fix this?

function setImgData(callback) {
    $(".content img").each( function() {
        var img = $(this);
        var pic_real_width, pic_real_height;
        $("<img/>")
            .attr("src", $(img).attr("src"))
            .load(function() {
                pic_real_width = this.width;
                pic_real_height = this.height;
                $(this).data("w", pic_real_width);
                $(this).data("h", pic_real_height);
            });
    });
    callback();
}
function resizeImg() {
    var cWidth = $('.content').innerWidth();
    var cPaddL = $('.content').css('padding-left').replace("px", "");
    var cPaddR = $('.content').css('padding-right').replace("px", "");
    var contentWidth = cWidth - cPaddL - cPaddR;

    $(".content img").each( function() {
        var imgW = $(this).data('w');
        if( imgW > contentWidth ) {
            var imgH = $(this).data('h');
            var newH = Math.round( ( imgH * contentWidth ) / imgW );
            $(this).width( contentWidth ).height( newH );
        }
    });
};
$(function() {
    setImgData(function () {
        resizeImg();
    });
});
$(window).resize( function(){
    resizeImg();
});
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59

0 Answers0