Skip to content

Instantly share code, notes, and snippets.

@wiledal
Created June 10, 2015 19:05
Show Gist options
  • Select an option

  • Save wiledal/9593c302347fba1a046d to your computer and use it in GitHub Desktop.

Select an option

Save wiledal/9593c302347fba1a046d to your computer and use it in GitHub Desktop.
tinyslider wip
function TinySlider(element) {
this.element = element;
this.currentSlide = 0;
this.slides = element.querySelectorAll(".slide");
this.slidesContainer = document.createElement("div");
this.applyStyles(this.slidesContainer, {
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
whiteSpace: "nowrap"
});
this.element.appendChild(this.slidesContainer);
for (var i = 0; i < this.slides.length; i++) {
this.applyStyles(this.slides[i], {
display: "inline-block",
width: "100%",
height: "100%",
whiteSpace: "normal"
});
this.slidesContainer.appendChild(this.slides[i]);
}
this.touching = false;
this.touchPosition = null;
this.slidePosition = 0;
var _this = this;
this.element.addEventListener("mousedown", function(event) {
_this.ontouchstart(event);
});
this.element.addEventListener("mousemove", function(event) {
_this.ontouchmove(event);
});
window.addEventListener("mouseup", function(event) {
_this.ontouchend(event);
});
}
TinySlider.prototype.applyStyles = function(el, styles) {
for (var key in styles) {
el.style[key] = styles[key];
}
}
TinySlider.prototype.toggleClass = function(el, theclass, addFlag) {
var classes = el.className.split(" ");
var classIndex = classes.indexOf(theclass);
if (classIndex == -1 && addFlag) {
classes.push(theclass);
} else if (classIndex > -1 && !addFlag) {
classes = classes.slice(classIndex, 1);
}
el.className = classes.join(" ");
}
TinySlider.prototype.ontouchstart = function (event) {
event.preventDefault();
this.touching = true;
this.touchPosition = event.clientX;
this.applyStyles(this.slidesContainer, {
transition: "none"
});
};
TinySlider.prototype.ontouchmove = function (event) {
if (this.touching) {
var diffX = event.clientX - this.touchPosition;
this.slidePosition += diffX;
this.applyStyles(this.slidesContainer, {
transform: "translateX("+this.slidePosition+"px)"
});
this.touchPosition = event.clientX;
}
};
TinySlider.prototype.ontouchend = function (event) {
this.touching = false;
this.applyStyles(this.slidesContainer, {
transition: "all .2s ease-out"
});
};
var ts = new TinySlider(document.querySelector(".section--learn-more__slider"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment