简体   繁体   中英

Javascript not applying first, only by refreshing page

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.

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.

Use:

$(document).ready(init);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM