Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Fade Effect in Slideshow (Javascript)

I have created a JavaScript Slideshow, but I don't know how to add the fade effect. Please tell me how to do it, and please tell in JavaScript only, no jQuery!

Code:

var imgArray = [
    'img/slider1.jpg',
    'img/slider2.jpg',
    'img/slider3.jpg'],
    curIndex = 0;
    imgDuration = 3000;

function slideShow() {
    document.getElementById('slider').src = imgArray[curIndex];
    curIndex++;
    if (curIndex == imgArray.length) { curIndex = 0; }
    setTimeout("slideShow()", imgDuration);
}
slideShow();
like image 494
Abhinv Bhagwat Avatar asked Dec 03 '22 19:12

Abhinv Bhagwat


1 Answers

Much shorter than Ninja's solution and with hardware accelerated CSS3 animation. http://jsfiddle.net/pdb4kb1a/2/ Just make sure that the transition time (1s) is the same as the first timeout function (1000(ms)).

Plain JS

var imgArray = [
    'http://placehold.it/300x200',
    'http://placehold.it/200x100',
    'http://placehold.it/400x300'],
    curIndex = 0;
    imgDuration = 3000;

function slideShow() {
    document.getElementById('slider').className += "fadeOut";
    setTimeout(function() {
        document.getElementById('slider').src = imgArray[curIndex];
        document.getElementById('slider').className = "";
    },1000);
    curIndex++;
    if (curIndex == imgArray.length) { curIndex = 0; }
    setTimeout(slideShow, imgDuration);
}
slideShow();

CSS

#slider {
    opacity:1;
    transition: opacity 1s; 
}

#slider.fadeOut {
    opacity:0;
}
like image 114
Bram Vanroy Avatar answered Dec 11 '22 16:12

Bram Vanroy