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) {
var tis = this;
this.el = el;
this.cbs = callbacks;
this.points = [0, 0];
//perform binding
this.el.addEventListener('touchstart', function (evt) {
tis.start(evt);
});
this.el.addEventListener('touchmove', function (evt) {
evt.preventDefault();
tis.move(evt);
});
};
Swiper.prototype.start = function (evt) {
if (evt.targetTouches && evt.targetTouches.length === 1) {
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.diff = function () {
return this.points[1] - this.points[0];
};
Swiper.prototype.move = function (evt) {
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());
this.points[0] = this.points[1];
}
};
$.fn.swiper = function (callbacks) {
if (typeof callbacks.swiping !== 'function') {
throw '"swiping" callback must be defined.';
}
this.each(function () {
var tis = $(this),
swiper = tis.data('swiper');
if (!swiper) { //i.e. plugin not invoked on the element yet
...