I have the following JavaScript to make a slideshow:
window.addEventListener('load', main, false);
var number = 1;
var interval;
function main() {
interval = setInterval(changeDia, 3000);
}
function changeDia() {
var img = document.getElementById("dia");
var currentDia = img.getAttribute("src");
if(currentDia == "style/slideshow/6.jpg") {
number = 1;
} else {
number = number + 1;
}
img.setAttribute("src", "style/slideshow/" + number + ".jpg");
}
This code works fine, but the transitions are very rude. I would like to have the current image to fade out and the next one to fade in so there's a smooth transition. What is the easiest way? Javascript and jQuery are both good for me.
Thanks in advance,
Cedric
You can do it easily using jQuery without plugins:
var i = 0, //initial index
duration = 1000, //animation duration
interval = 3000; //interval
function switchImg() {
$("<img>") //create new <img>
.attr("src", "style/slideshow/" + (i<6?++i:(i=1,i)) + ".jpg") //set attr.
.css("opacity", 0) //hide it
.prependTo("#wrap") //add it to DOM
.animate({ //fade in
opacity: 1
}, {
duration: duration
})
.next() //select current img
.animate({ //fade out
opacity: 0
}, {
duration: duration
})
.promise()
.done(function () { //remove old img
$(this).remove(); // when done
setTimeout(switchImg, interval); //repeat
});
}
switchImg(); //start up
http://jsfiddle.net/DerekL/vzhHZ/
Don't forget to set the position
porperty of the images to absolute
or else it won't work.