6

I am trying to download an image then apply a fade using css background-image.
I can accomplish this when it is a regular <img src=''/> like so:

#mainImg {display:none}

var c = $('#mainImg');
$(new Image()).load(function(){
    c.fadeIn(300);
}).attr('src', c.attr('src'));

But how can i detect it when it is a css background?
Here's css using jQuery, but i cant seem to get it like the code above and detect when the download is finished

$('<img/>').attr('src', 'image.png').load(function() {
     $('#mainImg').css('background-image', 'url(image.png)');
});

edit this helped out! How can I check if a background image is loaded? thank you @colin

Community
  • 1
  • 1
t q
  • 4,593
  • 8
  • 56
  • 91
  • 1
    http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript/ – NickD Nov 04 '12 at 19:14
  • possible duplicate of [How can I check if a background image is loaded?](http://stackoverflow.com/questions/5057990/how-can-i-check-if-a-background-image-is-loaded) – hitautodestruct Sep 07 '14 at 11:00

1 Answers1

2

I've done this before by temporarily appending a hidden child image to the div, then setting its parent's backround image and fading in, when the child image's load event has fired. Best to delete the child image afterwards, to keep things tidy! You could just append the image anywhere, but this was a mapping application and I had to keep the images associated with their parent divs!

evilunix
  • 960
  • 6
  • 11