JSFiddle - React, Tailwind, and code Playground
by ajinkyax
HTML
<div class="slider" id="slider">
<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
.slider {
width: 300px;
overflow: hidden;
}
.slider ul {
display: block;
height: 300px;
list-style: none;
padding: 0;
}
.slider ul li {
width: 300px;
height: 300px;
float: left;
}
Babel + JSX
class Slider {
constructor(id) {
console.log('Slider module');
this.$slider = $('#' + id);
this.ul = this.$slider.find('ul');
this.li = this.ul.find('li');
this.controls = this.$slider.find('.controls');
this.controlsLeft = this.controls.find('a.left');
this.controlsRight = this.controls.find('a.right');
this.controlsSpan = this.controls.find('span');
this.basewidth = 300;
//var
this.slideCount = this.li.length;
this.currentSlide = 0;
//init
this.registerEvents();
this.setULWidth();
this.displayText();
this.timer();
}
registerEvents() {
this.controlsLeft.on('click', (event) => {
event.preventDefault()
this.slideLeft();
});
this.controlsRight.on('click', (event) => {
event.preventDefault()
this.slideRight();
});
}
timer() {
this.slideInterval = window.setInterval(() => this.slideLeft(), 2000);
}
displayText() {
let num = (this.currentSlide % this.slideCount ) + 1;
this.controlsSpan.html('Current Slide: ' + num);
}
setULWidth() {
this.ul.css({
width: this.basewidth * this.slideCount
});
}
remainder() {
return this.currentSlide % this.slideCount;
}
slideLeft() {
window.clearInterval(this.slideInterval);
//if last img slide to first
if(this.remainder() === this.slideCount - 1){
this.ul.animate({
'margin-left': 0
}, () => {
this.currentSlide = 0;
});
} else {
this.ul.animate({
'margin-left': (this.remainder() + 1 ) * (- this.basewidth)
}, () => {
this.currentSlide += 1;
});
}
this.displayText();
this.timer();
}
slideRight() {
//if first img slide to last
window.clearInterval(this.slideInterval);
if(this.remainder() === 0){
this.ul.animate({
'margin-left': (this.slideCount - 1) * (-this.basewidth)
}, () => {
this.currentSlide = this.slideCount - 1;
});
} else {
this.ul.animate({
'margin-left':...