Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140131

how to make an infinite loop? (slider javascript)

$
0
0

My slider contains X slides (4 in the example). I want show 3 slides in same time and go back to the beginning when you get to the end.
For example:

  • 1 2 3
  • 2 3 4
  • 3 4 1
  • 4 1 2
  • 1 2 3

Could someone help me loop the slider properly?
I tried with if this.slide[this.nbrClick +2] != undefined, but that's a lot of conditions.

class Slider {
  constructor() {
    this.slide = document.getElementsByClassName("slide");
    this.next = document.getElementById("next");
    this.nbr = this.slide.length;
    this.nbrClick = 0;
  }
  click() {
    this.next.addEventListener("click", () => {
      this.nbrClick++;
      if (this.nbrClick > this.nbr) {
        this.nbrClick = 1;
      }
      for (let i = 0; i < this.nbr; i++) {
        this.slide[i].classList = "slide hidden";
      }
      this.slide[this.nbrClick].classList = "slide left";
      this.slide[this.nbrClick + 1].classList = "slide center";
      this.slide[this.nbrClick + 2].classList = "slide right";
    })
  }
}
let slider = new Slider();
slider.click();
#slider {
  position: relative;
  height: 200px;
  display: flex;
}

.slide {
  height: 200px;
  width: 200px;
  position: absolute;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.left {
  transform: translateX(0px);
}

.center {
  transform: translateX(200px);
}

.right {
  transform: translateX(400px);
}

.hidden {
  display: none;
}
<div id="slider" style="display: flex"><div class="slide left">1</div><div class="slide center">2</div><div class="slide right">3</div><div class="slide hidden">4</div></div><button id="next">Next</button>

Viewing all articles
Browse latest Browse all 140131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>