Skip to content

Instantly share code, notes, and snippets.

@SergeyNarozhny
Last active August 29, 2015 14:25
Show Gist options
  • Save SergeyNarozhny/ace14bdcccbb0dd8a8b2 to your computer and use it in GitHub Desktop.
Save SergeyNarozhny/ace14bdcccbb0dd8a8b2 to your computer and use it in GitHub Desktop.
Native js Touch simple Slider class for mobile
function NativeTouchSlide(selector, minMoveX) {
this.domSelector = document.querySelector(selector) || selector;
this.sCh = this.domSelector.children;
this.checkSelector = !!this.domSelector && this.sCh && this.sCh.length>1;
this.minMoveX = minMoveX || 30;
if (this.checkSelector) {
this.domSelector.addEventListener('touchstart', this.onTouchStart.bind(this));
this.addClass(this.sCh[0], "current");
}
else throw new Error("Place initialization code inside the DOMContentLoaded event or similar\n
and fill in the container width enough elements!");
}
NativeTouchSlide.prototype = {
cancelTouch : function() {
this.domSelector.removeEventListener('touchmove', this.onTouchMove);
this.startX = null;
this.isMoving = false;
},
onTouchStart : function(e) {
if (!this.checkSelector || e.touches.length != 1) return;
this.startX = e.touches[0].pageX; //clientX
this.isMoving = true;
this.domSelector.addEventListener('touchmove', this.onTouchMove.bind(this), false);
},
onTouchMove : function(e) {
if (!this.checkSelector || !this.isMoving) return;
var x = e.touches[0].pageX, //clientX
dx = this.startX - x;
if (Math.abs(dx) >= this.minMoveX) {
this.cancelTouch();
if (dx > 0) {
//left swipe
this.nextSlide("left");
}
else {
//right swipe
this.nextSlide("right");
}
}
},
addClass : function(el, cl) {
if (el.className.indexOf(cl) == -1)
el.className += (el.className ? ' ' : '') + cl;
},
removeClass : function(el, cl) {
if (el.className.indexOf(cl) == -1) return;
var classList = el.className.split(" "),
newClass = '';
for (var i=0; i < classList.length; i++) {
if classList[i] && classList[i] != cl)
newClass += classList[i] + " ";
}
el.className = newClass;
},
nextSlide : function(flag) {
var current = this.domSelector.querySelector(".current");
if (!current) return;
var check1 = (flag == "left"
? current.nextElementSibling
: current.previousElementSibling),
check2 = (flag == "left"
? !current.nextElementSibling
: !current.previousElementSibling);
if (check1) {
this.addClass((flag == "left"
? current.nextElementSibling
: current.previousElementSibling),
"current");
}
else if (check2) {
this.addClass((flag == "left"
? this.sCh[0]
: this.sCh[this.sCh.length-1]),
"current");
}
this.removeClass(current, "current");
}
}
//implementation
document.addEventListener("DOMContentLoaded", function(){
var mySlider = new NativeTouchSlide("#my-carousel");
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment