JSFiddle - React, Tailwind, and code Playground
HTML
<div class="slider">
<div class="slider-set">
<img class="slider-item" src="http://paper.bl.ee/images/sliderImages/layer1.png">
<img class="slider-item" src="http://paper.bl.ee/images/sliderImages/layer2.png">
<img class="slider-item" src="http://paper.bl.ee/images/sliderImages/layer3.jpg">
<img class="slider-item" src="http://paper.bl.ee/images/sliderImages/layer4.jpg">
</div>
<div class="slider-controls">
<div class="slider-prev"></div>
<div class="slider-next"></div>
</div>
</div>
CSS
* {
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* slider.open */
.slider,
.slider-set,
.slider-controls {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
/* slider-set.open */
.slider-set {
overflow: hidden;
}
.slider-item {
display: none;
vertical-align: middle;
}
.slider-item.active {
display: block;
}
/* slider-set.close */
/* slider-controls.open */
.slider-prev,
.slider-next {
position: absolute;
top: 50%;
width: 40px;
height: 40px;
margin-top: -20px;
cursor: pointer;
}
.slider-prev {
left: 10px;
background: url(http://paper.bl.ee/images/left.png) -10px center no-repeat;
}
.slider-next {
right: 10px;
background: url(http://paper.bl.ee/images/right.png) 10px center no-repeat;
}
/* slider-controls.close */
/* slider.close */
JavaScript
var AutoScroller = (function() {
"use strict";
var AutoScroller = function(container, image) {
this.container = container;
this.image = image;
this.init();
};
AutoScroller.prototype.init = function() {
window.addEventListener("load", function() {
this.update();
this.startInterval();
}.bind(this));
window.addEventListener("resize", function() {
this.updateImageSize();
}.bind(this));
};
AutoScroller.prototype.changeImage = function(image) {
this.image = image;
this.container.scrollTop = 0;
this.container.scrollLeft = 0;
this.update();
};
AutoScroller.prototype.startInterval = function() {
this.stopInterval();
this.timer = setInterval(function() {
if (Math.abs(this.containerRatio - this.imageRatio) < 0.1) return;
this.updateSecondaryDirection();
var method;
switch (this.primaryDirection) {
case "horizontal":
method = "scrollTop";
break;
case "vertical":
method = "scrollLeft";
break;
}
switch (this.secondaryDirection) {
case "positive":
this.container[method] += 1;
break;
case "negative":
this.container[method] -= 1;
break;
}
}.bind(this), 20);
};
AutoScroller.prototype.stopInterval = function() {
clearInterval(this.timer);
delete this.timer;
};
AutoScroller.prototype.update = function() {
this.updatePrimaryDirection();
this.updateSecondaryDirection();
this.updateImageSize();
};
AutoScroller.prototype.updatePrimaryDirection = function() {
this.containerRatio = this.container.offsetWidth / this.container.offsetHeight;
this.imageRatio = this.image.naturalWidth / this.image.naturalHeight;
if (this.containerRatio > this.imageRatio) {
this.primaryDirection = "horizontal";
} else {
this.primaryDirection = "vertical";
}
};
...