1

Thanks for taking some of your time.

I was wondering if there was a possible way using jQuery to trigger a function right after a div background image is finished downloading and rendered.

Let's say you have this div

<div id="img1" class="img1"> </div>

where img1 style is

.img1 {
    background-image: some_big_image.png;
    background-position:center;
    background-repeat:no-repeat;
    background-size:cover;  
    display: none;
}

concidering this javascript function

function showDiv() {
  $("#img1").fadeIn(1000);
}

Is there a way to call the previous function right after the image is rendered? By rendered I mean resized to fit nicely within its div and ready to be shown.

I found a lot of infos about triggering a function after page load or after downloading image but nothing about post-render.

You guys are the bests. Thank you in advance.

Érik Desjardins
  • 993
  • 1
  • 11
  • 24
  • http://stackoverflow.com/questions/910727/jquery-event-for-images-loaded – xyz Nov 28 '12 at 13:17
  • What is your goal here? It seems like fading it in as soon as the page is loaded would work fine. Why are you trying to perform it after the image is rendered? – thefreeman Nov 28 '12 at 13:18
  • @davidcroda If I do so, the images are downloaded but not yet rendered. The images must be resized and repositioned according to the div's position and size. The fadeIn starts before the image is rendered. – Érik Desjardins Nov 28 '12 at 13:23

2 Answers2

2

Try

var img = new Image();
img.src = "/some_big_image.png";
img.onload = function( ) {
    $("#img1").css("background-image", "url('" + img.src + "')" ).fadeIn(1000);
}

Fiddle here

Bruno
  • 5,504
  • 1
  • 22
  • 39
0

I know you already accepted an answer above, but this can be simplified grealy to just use the jquery magic function

$(function() {
    $("#img1").fadeIn(1000);
}

You replied above that the onload event wasn't working for you. The $(function() { //code here } ); fires when the dom is completely ready (not sure if all browsers do this by default for the onload event), so perhaps that is why you were having issues. It is also handy because you can call it multiple places on your page and they will be combined (rather then directly setting onload, which will be overriden if its set somewhere else)

Fiddle here: http://jsfiddle.net/5cR4G/8/

thefreeman
  • 996
  • 10
  • 13
  • Doesn't work. You are correct in that "ready" fires when the DOM is ready, but this specifically does _not_ include all images loaded. "load" fires in that case. Ie, "ready" fires when the DOM is ready to be fiddled with. "load" fires when all the resources are loaded. – Ch'marr Aug 07 '13 at 20:08