Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger an event after lazy load has loaded an image?

I have images that need to be absolutely positioned so that the center of the image is in the center of its parent div. I already have code that does this.

I recently added the Lazy Load plugin and it works as expected. But I need a way of triggering my image centering code after lazy load has loaded and faded-in the image.

My current code is basically this:

jQuery(document).ready( function($) {

// Make all lazy images ready to load themselves and listen for a custom event
$("img.lazy").lazyload({ event:"delayed-lazy-load-event", effect : "fadeIn"});

});


// Wait for the iframes and other important junk to finish loading
jQuery( window ).load( function($){

// trigger lazy loading of thumbnails.
$("img.lazy").trigger("delayed-lazy-load-event")
}

I can't find any info about any feature of Lazy Load that lets me set a callback function to run after it runs the fadeIn effect.

like image 563
thinsoldier Avatar asked Oct 16 '14 03:10

thinsoldier


People also ask

What would be the effect of adding loading lazy to the IMG tag?

Using browser-level lazy-loading # This attribute can be added to <img> elements, and also to <iframe> elements. A value of lazy tells the browser to load the image immediately if it is in the viewport, and to fetch other images when the user scrolls near them.

How do you test for lazy loading images?

If you want to test the execution of lazy loading, I can recommend that you clear your browser's cache and try reloading. In Chrome's Developer Console (F12), you can tweak the speeds and simulate modem speeds. Hit F12 -> Network tab -> Change the "No throttling" dropdown . Choose a slower speed to experiment.

Can you lazy load background images?

IMG tags can leverage native browser lazy loading, which doesn't require any JavaScript. You can still lazy load background images if they're in HTML as an inline style. Plugins like FlyingPress automatically detect and lazy load them.

How do I know if lazy loading is working?

If you're not sure if lazy loading is working correctly, you can open the Chrome DevTools and check that the images are not loaded until the scroll.


2 Answers

found this to work:

$('img.lazy').on('appear',function(){
  console.log(this)//fires this function when it appears
});
like image 54
Entrabiter Avatar answered Oct 09 '22 17:10

Entrabiter


Entrabiter's answer is actually for triggering a function when the image appears on screen, not after it has loaded. To run some code after an image has loaded (i.e. faded in), you need the 'load' argument:

$('img.lazy').on('load',function(){
  console.log(this)//fires this function when it appears
});
like image 40
Nathan Hornby Avatar answered Oct 09 '22 18:10

Nathan Hornby