Ansis Spruģevics
Ansis Spruģevics

Reputation: 388

Adding a transition/animation to this JavaScript slideshow?

I'm trying to make a simple JavaScript slideshow, following the W3Schools tutorial. How would I go about adding animations to the slide class? Idea is - you press the next/previous button and the 2 slides crossfade or, best case scenario, move to the left/right accordingly.

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("slide");
  if (n > x.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = x.length
  };
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex - 1].style.display = "block";
}
#sl1 {
  background-color: #F00;
}

#sl2 {
  background-color: #0F0;
}

.slide {
  width: 600px;
  height: 200px;
}

#next{
  background-color: #000;
  color: #FFF;
  width: 65px;
  height: 20px;
  position: absolute;
  top: 50%;
  right: 0;
}

#prev {
  background-color: #000;
  color: #FFF;
  width: 75px;
  height: 20px;
  position: absolute;
  top: 50%;
  left: 0;
}
<div id="prev" onclick="plusDivs(-1);fade();">Previous</div>
<div id="next" onclick="plusDivs(+1)">Next</div>
<div class="slide" id="sl1"></div>
<div class="slide" id="sl2"></div>

Upvotes: 0

Views: 139

Answers (1)

Temani Afif
Temani Afif

Reputation: 272590

You may do changes on the opacity instead of the display and add CSS tansition. You have also to adjust the CSS like this :

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("slide");
  if (n > x.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = x.length
  };
  for (i = 0; i < x.length; i++) {
    x[i].style.opacity = 0;
  }
  x[slideIndex - 1].style.opacity = 1;
}
.container {
position:relative;
margin:20px;
height:200px;
}

#sl1 {
  background-color: #F00;
  position:absolute;
}

#sl2 {
  background-color: #0F0;
  position:absolute;
}

.slide {
  width: 100%;
  height: 200px;
  transition:1s;
}

#next{
  background-color: #000;
  color: #FFF;
  width: 65px;
  height: 20px;
  position: absolute;
  top: 50%;
  right: 0;
  z-index:9;
}

#prev {
  background-color: #000;
  color: #FFF;
  width: 75px;
  height: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  z-index:9;
}
<div class="container">
<div id="prev" onclick="plusDivs(-1);">Previous</div>
<div id="next" onclick="plusDivs(+1)">Next</div>
<div class="slide" id="sl1" style="opacity:1"></div>
<div class="slide" id="sl2"></div>
</div>

Upvotes: 2

Related Questions