0

I have made an image gallery, in which i have portrait as well as landscape pictures. I use Javascript to determine which mode the picture is, to apply css based on the pictures orientation. This is the Code:

     $(document).onload(function() {   
$('.gallery').find('img').each(function(i,elem){
var $this = $(this),
    ratio = $this.width() / $this.height();

$this.addClass((ratio < 1) ? 'portrait' : 'landscape');
});
});

It does not work, when visiting the webiste first, altough it works flawlessly as soon as I refresh the page once. Open the website in new tab and its again not working.

PS. Tried to change document.onload to document.ready, didnt change anything.

1
  • If you think the issue might have to do with the function running in the first place, have you checked to see if the function is indeed running on the first page load? Apr 15, 2018 at 0:07

2 Answers 2

0

Listen to the window loaded event this way (it would fire after images are loaded):

$(window).on('load', function(e) {
    $('.gallery').find('img').each(function(i,elem){
        var $this = $(this),
        ratio = $this.width() / $this.height();
        $this.addClass((ratio < 1) ? 'portrait' : 'landscape');
    });
});

Only after images were loaded you can check their ratio.

0

Use:

$(document).ready(init);

function init(){
// Enter your code here
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.