Add Fade Effect to Slideshow (Javascript)

I've created a JavaScript slideshow, but I don't know how to add a fade effect. Please tell me how to do this, and please tell me 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();

      

+3


source to share


4 answers


Considerably shorter than Ninja's solution and CSS3 hardware accelerated animation. http://jsfiddle.net/pdb4kb1a/2/ Just make sure the transition time (1s) matches 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;
}

      

+6


source


As an alternative. If you are trying to make a slider.

The usual approach is to animate the frame and animate the frame.

This is what slide effect and fade effect do. Your example fades out. This is good, but it might not be what you really want once you see it working.

If you really want to animate images in ... OUT, you need something more sophisticated.

To animate images inside and out, you have to use an image element for each, then flip one out and flip it over. Images should be stacked on top of each other in case of fading, if you want to slide you put them next to each other.

The slideshow function then works magic, but before you can do that, you need to add all these images to your array in the dom, this is called dynamic dom injection, which is really cool.



Make sure you check out the script for a complete working demo and the code linked below.

Html

<div id="slider">
// ...we will dynamically add your images here, we need element for each image
</div>

      

Js

var curIndex = 0,
    imgDuration = 3000,
    slider = document.getElementById("slider"),
    slides = slider.childNodes; //get a hook on all child elements, this is live so anything we add will get listed
    imgArray = [
        'http://placehold.it/300x200',
        'http://placehold.it/200x100',
        'http://placehold.it/400x300'];


//
// Dynamically add each image frame into the dom;
//
function buildSlideShow(arr) {
    for (i = 0; i < arr.length; i++) {
        var img = document.createElement('img');
        img.src = arr[i];
        slider.appendChild(img);
    }
    // note the slides reference will now contain the images so we can access them
}

//
// Our slideshow function, we can call this and it flips the image instantly, once it is called it will roll
// our images at given interval [imgDuration];
//
function slideShow() {

    function fadeIn(e) {
        e.className = "fadeIn";
    };

    function fadeOut(e) {
        e.className = "";
    };


        // first we start the existing image fading out;

        fadeOut(slides[curIndex]);

        // then we start the next image fading in, making sure if we are at the end we restart!
        curIndex++;
        if (curIndex == slides.length) {
            curIndex = 0;
        }

        fadeIn(slides[curIndex]);

        // now we are done we recall this function with a timer, simple.

        setTimeout(function () {
            slideShow();
        }, imgDuration);
    };


    // first build the slider, then start it rolling!

    buildSlideShow(imgArray);
    slideShow();

      

Fiddle: http://jsfiddle.net/f8d1js04/2/

+2


source


you can use this code

var fadeEffect=function(){

    return{

        init:function(id, flag, target){

            this.elem = document.getElementById(id);

            clearInterval(this.elem.si);

            this.target = target ? target : flag ? 100 : 0;

            this.flag = flag || -1;

            this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;

            this.elem.si = setInterval(function(){fadeEffect.tween()}, 20);

        },

        tween:function(){

            if(this.alpha == this.target){

                clearInterval(this.elem.si);

            }else{

                var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);

                this.elem.style.opacity = value / 100;

                this.elem.style.filter = 'alpha(opacity=' + value + ')';

                this.alpha = value

            }

        }

    }

}();

      

here's how to use it

fadeEffect.init('fade', 1, 50) // fade in the "fade" element to 50% transparency

fadeEffect.init('fade', 1) // fade out the "fade" element

      

+1


source


A new version

Dynamic javascript slideshow generator with css transition effect and pause / resume function.

Without jQuery, only plain javascript and some es2015 functionality are available.

Html

<div class="foreground-img"></div>
<div class="background-img"></div>

<button class="start">Start</button>
<button class="pause">Pause</button>

      

CSS

div {
  width: 100px;
  height: 100px;
  position: absolute;
  top: 40px;
  transition: opacity 1s ease-in-out;
}

.Hide {
  opacity: 0 !important;
}

      

Js

const $foreground = document.querySelector('.foreground-img');
const $background = document.querySelector('.background-img');
const $start = document.querySelector('.start');
const $pause = document.querySelector('.pause');

const images = [
  'https://dummyimage.com/100x100/e62020/fff&text=IMG1',
  'https://dummyimage.com/100x100/20e679/fff&text=IMG2',
  'https://dummyimage.com/100x100/4120e6/fff&text=IMG3'
];

// initialize a new slideshow
const slideshow = new Slideshow($foreground, $background, images);

// start slideshow on load
// can be use with or without the callback
// `imgIndex` refer to variable `i` in `Slideshow`
slideshow.start((imgIndex) => {
  console.log('The current image is:', images[imgIndex]);
});

$pause.addEventListener('click', () => {
  slideshow.pause();
});
$start.addEventListener('click', () => {
  slideshow.start();
});

/* ================
slideshow generator
=================== */

function Slideshow($foreground, $background, images) {
  // slideshow duration in milliseconds
  const duration = 2000;

  const length = images.length - 1;

  // setInterval id used to stop the slideshow if needed
  let id;

  // used to iterate through images
  let i = 0;

  // initialize slideshow
  // show foreground
  $foreground.style.backgroundImage = `url("${images[0]}")`;
  // hide background
  $background.classList.add('Hide');

  // start/resume slideshow
  this.start = (callback) => {
    id = setInterval(() => {
      // everytime function is called `i` increase by 1
      // when reach last img `i` is set to 0
      // first call start at second img: `i == 1`
      i = (i === length) ? 0 : i + 1;
      // set image url
      // show/hide image
      changeImage($foreground);
      changeImage($background);
      // return the current image index in a callback
      if (typeof callback === 'function') {
        callback(i);
      }
    }, duration);
  }

  // pause slideshow
  this.pause = () => clearInterval(id);

  function changeImage($img) {
    if ($img.classList.contains('Hide')) {
      $img.style.backgroundImage = `url("${images[i]}")`;
      $img.classList.remove('Hide');
    } else {
      $img.classList.add('Hide');
    }
  }
}

      

https://jsfiddle.net/qqpobuoy/6/

Old answer

https://jsfiddle.net/hLg9pct6/6/

0


source







All Articles