Reputation: 735
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.
Upvotes: 1
Views: 1207
Reputation: 191729
.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();
}
Upvotes: 3