JSFiddle - React, Tailwind, and code Playground

by 76484

HTML

<div class="pagination">
  <a href="#" class="prev">&larr;</a>
  <div class="numbers">
    <span class="current current--active">1</span>
    <span class="current">2</span>
    <span class="current">3</span> / <span class="total">3</span>
  </div>
  <a href="#" class="next">&rarr;</a>
</div>

<ul class="slides">
  <li class="slide slide--active"></li>
  <li class="slide"></li>
  <li class="slide"></li>
</ul>

CSS

.pagination {
  display: flex;
}

.numbers {
  padding: 0 1em;
}

.slides {
  list-style: none;
  display: flex;
}

.slide {
  width: 4em;
  height: 4em;
  background: blue;
}

.slide--active {
  background: red;
}

.current {
  display: none;
}

.current.current--active {
  display: inline;
}

JavaScript

const state = {
	index: $('.slide--active').index(),
  timer: null,
  timerDurationMilliseconds: 2000,
  numSlides: $('.slide').length
};

const decrementIndex = () => {
	let newIndex = state.index - 1;
  
  if (newIndex < 0) {
  	newIndex = state.numSlides - 1;
  }
  
  state.index = newIndex;
};

const incrementIndex = () => {
	let newIndex = state.index + 1;
  
  if (newIndex >= state.numSlides) {
  	newIndex = 0;
  }
  
  state.index = newIndex;
};

const render = () => {
	$('.current').each(function () {
  	const $this = $(this);
    $this.toggleClass('current--active', $this.index() === state.index);
  });
  
	$('.slide').each(function () {
  	const $this = $(this);
  	$this.toggleClass('slide--active', $this.index() === state.index);
  });
  
  if (state.timer) {
    clearTimeout(state.timer);
  }
  
  state.timer = setTimeout(() => {
    incrementIndex();
    render();
  }, state.timerDurationMilliseconds);
};

$('.next').on('click', function () {
	incrementIndex();
  render();
});

$('.prev').on('click', function () {
	decrementIndex();
  render();
});

render();