1

I'm trying to show a div background with fadein() effect when it completes loading.

I've been searching and the closer I got was this topic (wich works great on a <img> tag).

I want to do exactly the same with the css background property of a div. Here is the code I'm tryin' to work:

HTML

<div id="some_target"></div>

CSS

#some_target {
  position: absolute;
  width: 100%; height: 100% ;      
}

jQuery

$(document).ready(function() {
var newImage = "url(http://vanusasousa.com.br/sicom/img/background2.jpg)"; //Image name

  $("#some_target").hide() //Hide it
    .one('load', function() { //Set something to run when it finishes loading
      $(this).fadeIn(); //Fade it in when loaded
    })
    .css('background', newImage) //Set the background image
    .each(function() {
      //Cache fix for browsers that don't trigger .load()
      if(this.complete) $(this).trigger('load');
    });   
});

It looks fine to me, except that doesn't work. Here is the jsFiddle I'm working at.

Does anyone know what am I doing wrong?

Thanks everyone.

Community
  • 1
  • 1

1 Answers1

3

.load and .complete do not apply to divs. Just create an <img> and use its triggers to properly update the div.

var newImage = "http://vanusasousa.com.br/sicom/img/background2.jpg";
$("#some_target").hide().css('background', 'url(' + newImage + ')');
var $img = $("<img>").attr('src', newImage).one('load', function () {
    $("#some_target").fadeIn();
});
if ($img.get(0).complete) {
    $("#some_target").fadeIn();
}   

http://jsfiddle.net/DfFhp/2/

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • This is exactly what I was looking for. Could you please just tell if in that case, once the `background` is loaded that way If I use it in another page on my system if it will be loaded again? Or the browser caches it? Thank you very much! – A. Cristian Nogueira May 03 '13 at 22:31
  • 1
    @Christian browser will probably cache it; depends on the browser of course – Explosion Pills May 03 '13 at 22:41