0

I have a problem with my js script to set height of images on my page.

It looks like this:

var $bigImages = $('.js-big-image'),
    $quotes = $('.js-quote'),
    $quoteImages = $('.js-quote-image');

        if (window.innerWidth >= 460) {
            $bigImages.each(function (index) {
                var imgHeight = $(this).height() / 2;
                $($quotes[index]).height(imgHeight);
                $($quoteImages[index]).height($quoteImages[index] / 2);
            });
        }

When I go to page first time, images gets height:0px;, but when I reload page images gets height calculated from script.

It's happening when user come first time. When I use chrome incognito window, the problem exist, so it's happening only first time, after reload everything is fine.

Many thanks for solutions.

Robson
  • 1,207
  • 3
  • 21
  • 43
  • Are you running this code within $(document).ready() ? – AGB Aug 02 '17 at 09:31
  • 2
    images load asynchronously, so when you check their sizes, them are not loaded yet and size is 0x0. You need to use 'load' event of each image to have actual size in it's callback, or define exactly width and height inside of your CSS – MysterX Aug 02 '17 at 09:32
  • @AlanBuchanan Yes, my whole scripts.js is wrapped by $(document).ready(function(){ //scripts are here }); – Robson Aug 02 '17 at 09:42
  • @Robson What MysterX said then is probably the issue here, which explains why it works on subsequent page loads as the browser will have cached the image. You could try using the load event but it isn't 100% reliable. See the docs for more info: https://api.jquery.com/load-event/ – AGB Aug 02 '17 at 09:57
  • Refering to @MysterX: Possible duplicate of [jquery callback after all images in dom are loaded?](https://stackoverflow.com/questions/4857896/jquery-callback-after-all-images-in-dom-are-loaded) – Herr Derb Aug 02 '17 at 09:59

1 Answers1

2

Make sure the page is completely loaded, before executing the script

do this by warping your code into the ready function

$(document).ready(function () {
    var $bigImages = $('.js-big-image'),
    $quotes = $('.js-quote'),
    $quoteImages = $('.js-quote-image');

    if (window.innerWidth >= 460) {
        $bigImages.each(function (index) {
            var imgHeight = $(this).height() / 2;
            $($quotes[index]).height(imgHeight);
            $($quoteImages[index]).height($quoteImages[index] / 2);
        });
    }
});
Herr Derb
  • 4,977
  • 5
  • 34
  • 62