How do I add transition/animation to slider of images?

Viewed 1973

How to add a transition effect when the image changes?

When the array loops through images, how do I add a transition so that its more smooth.

var i = 0;
var images = [];
var time = 3000;


images[0] =  'test.jpg';
images[1] =  'test1.jpg';
images[2] =  'test2.jpg';


function changeImg() {
    document.slide.src = images[i];

    if(i < images.length - 1) {
        i++
    } else {
        i = 0;

    }



    setTimeout("changeImg()", time);
}

window.onload = changeImg;
3 Answers

My easiest way to do it is putting all the images into 1 wrapper. Then use loop to set active image by element index. Something like this

<style>
  .wrapper { position: relative; }
  .wrapper img {
    opacity: 0;
    visibility: hidden;
    transition: 0.5s opacity;
    position: absolute;
  }
  .wrapper img.active {
    opacity: 1;
    visibility: visible;
    position: relative;
  }
</style>
<div class="wrapper">
  <img src={images[0]} />
  <img src={images[1]} />
  <img src={images[2]} />
  <img src={images[3]} />
</div>

One of the easiest ways I found is using w3.css.

In your html code add these lines.

<html>
  <head>
    <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  </head>
  <body>    
    <img  class="w3-animate-fading" name="slide" src="" width="800" />
  </body>
</html>

The class parameter in your image tag will call the predefined css animations deom w3.css file. There are many more options such as slide right, slide left etc. You can view them all here

Codepen Demo

Related