2

The following, I believe, waits until the image has fully loaded:

$('.some-img').load(function(){
    $('.img-container').show();
});

What I want however is to wait until the image has begun to load and adjust the height of the image's container based on the height of the image.

The container's height is responsive height: auto and the images have varying heights, so the container starts off with no height (just 20px padding) and then quickly adjusts its height based on the height of the image inside it, which is kind of grating each time it loads.

Is there any way to check if the image has started to load so that I can adjust the height of the image's container, then do $('.imagemodal-container').show(), as waiting for the entire image to load is not good UX.

frosty
  • 2,779
  • 6
  • 34
  • 63
  • I don't believe you can get the height of the image until it is done loading, so not sure your strategy will work. Normally to reserve the space the image should be rendered with height / width values, and the browser will reserve the space, no js needed. – random_user_name Mar 20 '16 at 15:56
  • Can you start with [this](http://stackoverflow.com/questions/6575159/get-image-dimensions-with-javascript-before-image-has-fully-loaded) and modify it to fit your need? If you have issues update it in your question. – sabithpocker Mar 20 '16 at 16:03
  • Thanks! I adjusted it and it worked. I'll post my answer. – frosty Mar 20 '16 at 16:29

1 Answers1

0

Using the getImageSize function from this answer:

function getImageSize(img, callback) {
      var $img = $(img);

      var wait = setInterval(function() {
          var w = $img[0].naturalWidth,
              h = $img[0].naturalHeight;
          if (w && h) {
              clearInterval(wait);
              callback.apply(this, [w, h]);
          }
      }, 30);
}

Since images that are greater than the img wrapper's width (600px) get scaled down to fit, I had to adjust the height based on the ratio, and also take into account the constant padding of 20px + 20px top and bottom:

getImageSize($('.showcase-img'), function(width, height) {
    width > 600 ? calculatedHeight = 600/width * height + 40 : calculatedHeight = height + 40;
    $('.showcase-img-wrapper').css("height", calculatedHeight+"px");
    $('.imagemodal-container').show();
});
Community
  • 1
  • 1
frosty
  • 2,779
  • 6
  • 34
  • 63