Reputation: 159
HTML
<div id="background">
<img src="#" alt="Background Image" class="first"/>
<img src="#" alt="Background Image" class="second"/>
</div>
I dont have a SRC added because it'll reduce the loading time of my page. (demo)
JQuery
var current = "first";
window.setInterval(function() {
if(current == "first") {
$("#background .second").prop("src", getMessage());
setTimeout(function(){
$("#background .second").animate({
opacity: 1
}, 1000);
$("#background .first").animate({
opacity: 0
}, 1000);
},1000);
current = "second";
} else if (current == "second") {
$("#background .first").prop("src", getMessage());
setTimeout(function(){
$("#background .first").animate({
opacity: 1
}, 1000);
$("#background .second").animate({
opacity: 0
}, 1000);
},1000);
current = "first";
}
getMessage()
}, 5000);
so I have an array with src links to my images, which are randomly chosen by function getMessage()
and while a picture is shown, the other IMG tag will change SRC and wait a second or two to get that image loaded and after that it will show with a animate.
But the problem is now: He doesn't show the second picture when the first picture got opacity 0 and the second picture got opacity 1.. Edit: The problem is the black fade between picture's.
Thanks in advance!
Upvotes: 3
Views: 2860
Reputation: 3560
I would really recommend using CSS for the transition. I made a JSfiddle - http://jsfiddle.net/9GEAn/1/ and it's far more efficient than the way you wrote it (I would recommend preloading the images, even though I didn't in the demo).
window.setInterval(function () {
current++;
if (current>=backgrounds.length) { current=0;}
if ($bg1.css("opacity")==1) {
$bg2.css({
"background-image":"url("+backgrounds[current]+")",
"opacity":"1"});
$bg1.css("opacity","0");
}
else {
$bg1.css({
"background-image":"url("+backgrounds[current]+")",
"opacity":"1"});
$bg2.css("opacity","0");
}
}, 5000);
Upvotes: 0
Reputation: 3965
Try to use attr() function instead of prop() Or try another one:
$("#background .first").animate({
opacity: 1
}, 1000, function(){
// after finished first animation
$("#background .second").animate({
opacity: 0
}, 1000);
});
Upvotes: 0
Reputation: 2018
Don't use setTimeout to add a buffer. You don't need this. What happens when the user is on a really slow connection? Your 1000ms won't do it. The correct thing to do here would be to create a new elemenent of type img. And listen to the onloadimage event. When it has fired, you can show the image.
Here is an example of this: Load Image from javascript
In addition to this you'll need some CSS:
#background > img {position:absolute; top:0; left:0;}
Upvotes: 7
Reputation: 58432
You need to add the following styles and it should fix your problem:
#background > img {position:absolute; top:0; left:0;}
Upvotes: 1