JSFiddle - React, Tailwind, and code Playground
by mori57
HTML
<div style="width: 330px; height: 200px;">
<div id="target" class="frame">
<div class="pictures">
<div class="pic">
<img alt="" src="http://placehold.it/50/f00" />
</div>
<div class="pic">
<img alt="" src="http://placehold.it/50/0f0" />
</div>
<div class="pic">
<img alt="" src="http://placehold.it/50/00f" />
</div>
<div class="pic">
<img alt="" src="http://placehold.it/50/999" />
</div>
</div>
</div>
</div>
CSS
img {
/*100% width to scale the height proportionately*/
width: 100%;
margin: 0;
}
.frame {
width: 100%;
height: 100%;
border: 1px solid #ccc;
overflow: hidden;
position: relative;
}
.pictures {
position: absolute;
width: 400%;
/*change accordingly*/
left: 0%;
}
.pictures:after {
content:"\0020";
display: none;
height: 0;
}
.pictures .pic {
width: 25%;
/*change with respect to .pictures*/
float: left;
}
JavaScript
(function ($) {
'use strict';
var Swiper = function (el, callbacks, options) {
var tis = this;
this.el = el;
this.cbs = callbacks;
this.points = [0, 0];
this.opts = options;
this.swipeDone = false;
//perform binding
this.el.addEventListener('touchend', function (evt) {
tis.stop(evt);
});
this.el.addEventListener('touchstart', function (evt) {
tis.start(evt);
});
this.el.addEventListener('touchmove', function (evt) {
evt.preventDefault();
tis.move(evt);
});
};
Swiper.LEFT = -1;
Swiper.RIGHT = 1;
Swiper.prototype.diff = function () {
return this.points[1] - this.points[0];
};
Swiper.prototype.getDirection = function () {
var direction = this.diff();
if (direction < 0) {
return Swiper.LEFT;
}
if (direction > 0) {
return Swiper.RIGHT;
}
};
Swiper.prototype.move = function (evt) {
if (Math.abs(this.diff()) >= this.opts.tolerance) {
this.swipeDone = true;
} else {
this.swipeDone = false;
}
if (evt.targetTouches && evt.targetTouches.length === 1) {
if (evt.targetTouches[0].offsetX) {
this.points[1] = evt.targetTouches[0].offsetX;
} else if (evt.targetTouches[0].layerX) {
this.points[1] = evt.targetTouches[0].layerX;
} else {
this.points[1] = evt.targetTouches[0].pageX;
}
this.cbs.swiping(this.diff());
}
};
Swiper.prototype.start = function (evt) {
if (evt.targetTouches && evt.targetTouches.length === 1) {
this.swipeDone = false;
if (evt.targetTouches[0].offsetX) {
this.points[0] = evt.targetTouches[0].offsetX;
} else if (evt.targetTouches[0].layerX) {
this.points[0] = evt.targetTouches[0].layerX;
} else {
this.points[0] = evt.targetTouches[0].pageX;
}
//make initial contact with 0 difference
this.points[1] = this.points[0];
}
};
Swiper.prototype.stop = function () {
...