JS Carousel

by ajinkyax

HTML

<div class="wrapper" id="carousel">
    <ul>
      <li><img src="http://placekitten.com/300/300" alt="Kitten" /></li>
      <li><img src="http://placekitten.com/300/300" alt="Kitten" /></li>
      <li><img src="http://placekitten.com/300/300" alt="Kitten" /></li>
      <li><img src="http://placekitten.com/300/300" alt="Kitten" /></li>
      <li><img src="http://placekitten.com/300/300" alt="Kitten" /></li>
    </ul>
    <div class="controls">
      <a href="#" class="left">Left</a>
      <a href="#" class="right">Right</a>
      <span></span>
    </div>
  </div>

CSS

.wrapper {
  width: 300px;
  overflow: hidden;
}

.wrapper ul {
      display: block;
  height: 300px;
  list-style: none;
  padding: 0;
    }

.wrapper ul li {
  width: 300px;
  height: 300px;
  float: left;
}

Babel + JSX

class Carousel {
  constructor() {
    console.log('Carousel module');

    this.carousel = $('#carousel');
    this.ul = this.carousel.find('ul');
    this.li = this.ul.find('li');
    this.slidesCount = this.li.length;
    this.slideWidth = 300;
    this.currentImage = 0;
    this.controls = this.carousel.find('.controls');
    this.controlsSpan = this.controls.find('span');
    this.controlsLeft = this.controls.find('a.left');
    this.controlsRight = this.controls.find('a.right');

    //init
    this.setUlWidth();
    this.displayCount();
    this.registerEvents();
    this.timer();
  }

  timer() {
    this.slideInterval = window.setInterval(() => {
      this.slideLeft();
    }, 2000);
  }

  displayCount(){
    this.controlsSpan.text("Current: " + (this.slideRemainder() + 1));
  }

  setUlWidth(){
    this.ul.css('width', this.slidesCount * this.slideWidth);
  }
  
  slideRemainder() {
  	return this.currentImage % this.slidesCount;
  }

  slideLeft(){
    window.clearTimeout(this.slideInterval);
    //it its last img slide to first
    if(this.slideRemainder() === this.slidesCount - 1) {
      this.ul.animate({
        "margin-left": 0
      }, () => {
        this.currentImage = 0;
        this.displayCount();
      });
    } else {
      this.ul.animate({
        "margin-left": (this.slideRemainder() + 1) * -300
      }, () => {
        this.currentImage++;
        this.displayCount();
      });
    }

    this.timer();
  }
  
  
  slideRight(){
    window.clearTimeout(this.slideInterval);
    //it its first img slide to last
    if(this.slideRemainder() === 0) {
      this.ul.animate({
        "margin-left": (this.slidesCount - 1) * -300
      }, () => {
        this.currentImage = (this.slidesCount - 1);
        this.displayCount();
      });
    } else {
    	this.ul.animate({
        "margin-left": (this.slideRemainder() - 1) * -300
      }, () => {
        this.currentImage = (this.slideRemainder() - 1);
        this.displayCount();
      });
   ...