You cannot detect the load on background images. You cannot translate / animate background images.
What you and other answers are trying to do is fade / animate the whole div after loading the img element. It does not work flawlessly every time. Because this IMO is destructive, because either the entire div (along with its contents) must be hidden when loading the image, or you hide the div , and then try to fade it. This will give you a flicker, as the div will be hidden before fading.
I would suggest that you use a dummy img element, as you already do, but set it to absolute (with respect to the div ) with the same size and negative z-index . Thus, the div and its contents can be visible during image loading. After loading, you lose the dummy img in (behind the div ), then assign the background-image , and then delete the dummy img .
Demo: http://jsfiddle.net/abhitalks/q7cvn2nd/
See this snippet:
var $img = $("<img />"); $img.load(function() { $(this).fadeIn("slow", function() { $('.feature').css('background-image', 'url(http://lorempixel.com/240/240)'); $(this).remove(); }); }); $img.addClass("dummy"); $img.attr('src', 'http://lorempixel.com/240/240'); $(".feature").append($img);
* { box-sizing: border-box; } .feature { position: relative; width: 240px; height: 240px; border: 1px solid gray; padding: 8px; color: #f00; background-color: transparent; background-repeat: no-repeat; background-size: 100% 100%; } img.dummy { top: 0; left: 0; bottom: 0; right: 0; width: 100%; height: 100%; position: absolute; z-index: -1; display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="feature"><h1>This is some text.</h1></div>
It is important . Remember to delete the dummy image.
source share