0

Right now I have some code which executes once the page is loaded like this:

$(window).load(function() {

    $('.featuredimage').each(function(){
        var img_width = $(this).width();
        var img_height = $(this).height();

        if (img_height >= img_width){
            $(this).addClass("artistthirdtall");

        };

        if (img_height < img_width){
            $(this).addClass("artistthirdwide");      
        };

    });


});

However, there are some big images on the page and there can be a "flicker" as the images get manipulated by Javascript.

Ideally I'd like to run this function on each image as it loads (rather than wait for them all to load).

I looked at this jQuery load event page: https://api.jquery.com/load-event/ and it looks like there are some serious issues with using it for checking if images are loaded? But the example given is essentially exactly what I'm trying to do.

So is it safe to use the example code given or not?

Thanks

PS - I'm a self-taught developer and don't know that much so please forgive me if I've said something stupid.

tomcritchlow
  • 785
  • 2
  • 11
  • 28
  • Well, there‘s plugins out there that promise to do a better job than jQuery’s `.load`, like f.e. https://github.com/desandro/imagesloaded Feel free to do some further research on your own … http://stackoverflow.com/search?q=cross+browser+image+load+event, https://www.google.com/search?q=cross+browser+javascript+image+load+event – CBroe Jun 22 '15 at 22:20

1 Answers1

0

I would add a class to your images to hide them until they are ready. Then fade them in. Scratched $.ready for load based on the following: Official way to ask jQuery wait for all images to load before executing something

<img src="foo" class="featuredimage ui-hidden-accessible"

    $(window).load(function() {
        $('.featuredimage').each(function() {
        var img_width = $(this).width();
        var img_height = $(this).height();

        if (img_height >= img_width){
            $(this).addClass("artistthirdtall").fadeIn(); /* added fadeIn() */
        };

        if (img_height < img_width){
            $(this).addClass("artistthirdwide").fadeIn(); /* added fadeIn() */     
        };
    });
});
Community
  • 1
  • 1
Joe Johnston
  • 2,794
  • 2
  • 31
  • 54