Using lazy load adding classes when img is in viewport

I am trying to add classes to img elements once they are lazy loaded and in the viewport.
Using the jq lazyload library, it works just as expected, but I want to add a callback to the lazyload function, which does not seem to work.
The documentation on github is rather poor, or I am rather blind, I could not see a callback option, the source code is not entirely understood yet either.

So I have extended the jquery prototype with the inView fn, and I check if the img is in the viewpoert before adding the css classes.

This works good on the first, sometimes the second picture, but the classes are all added to the remaining pictures before they are in the viewport, all that is happening is the fadeIn effect from the lazyload library, see this pen:

I have tried to target the event.target, did not work, tried to set a callback fn to the lazyload fn etc, to no avail.

Of course, if I check the this property on this function, it points to window.

$(window).on('scroll',function(){
if( $('img').inView() ) {
   
  $( 'img').addClass('magictime vanishIn');
};

});

So yeah, the goal is to only add the css animation classes to the lazyloaded images once they are in the viewport. Obviously, a callback fn to the lazyload fn would be the easiest, as that “this” points to the current img node.

Thank you for any help, this has cost me couple hrs:grin:

I haven’t really dug into it, but just by looking at it you’re basically saying:

if (any image is in view) {
    Give "magictime vanishIn" to ALL images
}

Better might be something like:

var $imgs = $('img'); // cache all the images, otherwise the searches the entire DOM everytime you scroll!

$(window).on('scroll', function () {
    $imgs.each(function(){
        var $this = $(this);
        $this.inView() && $this.addClass('magictime vanishIn');
    }) ;
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.