Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Images (as background) every 10 seconds

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!

like image 586
MikaldL Avatar asked Jan 17 '26 20:01

MikaldL


1 Answers

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;}
like image 116
Daniel Dimitrov Avatar answered Jan 20 '26 09:01

Daniel Dimitrov