Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger event on background image load

Tags:

jquery

Is there a way, using jQuery, to trigger an event on load of a CSS background image?

like image 267
Squirkle Avatar asked Jul 19 '10 13:07

Squirkle


People also ask

How to add lazy load on background image?

By default Lazy will use <img /> tags to load the src attribute. But there is also a way now to use Lazy with other html tags and load the image by background-image CSS attribute. Just use Lazy the way you would do on normal image tags. $(function() { $('.

What is img lazy loading?

What is Image Lazy Loading? Lazy Loading Images is a set of techniques in web and application development that defer the loading of images on a page to a later point in time - when those images are actually needed, instead of loading them up front.


2 Answers

you could do it like this,

demo

$('<img>').load(function(){
    // make sure to bind the load event BEFORE setting the "src"
    alert('image loaded');
}).attr('src',function(){
    var imgUrl = $('body').css('background-image');
    imgUrl = imgUrl .substring(4, imgUrl .length-1);
    return imgUrl;
}).each(function() {
    // fail-safe for cached images which sometimes don't trigger "load" events
    if(this.complete) $(this).load();
});
like image 139
Reigel Avatar answered Oct 09 '22 04:10

Reigel


$('<img>').attr('src',function(){
    var imgUrl = $('#body').css('background-image');
    imgUrl = imgUrl .substring(5, imgUrl .length-2);
    return imgUrl;
}).load(function(){
    //Do Something
});

Could not help but notice that the above code does not work in fiddle. Looks like its because it returns "url('/img-path.jpg')" instead of just "/img-path.jpg".

However this method still fails in IE. Anyone have an ie fix?

like image 31
Fresheyeball Avatar answered Oct 09 '22 04:10

Fresheyeball