Érik Desjardins
Érik Desjardins

Reputation: 993

jQuery event after div background-image is rendered

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.

Upvotes: 1

Views: 4359

Answers (2)

thefreeman
thefreeman

Reputation: 1035

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/

Upvotes: 0

Bruno
Bruno

Reputation: 5822

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

Upvotes: 2

Related Questions