I am attempting to create a horizontal slider that can be dragged left or right, updating its transform translate position accordingly. My goal is to accomplish this using pure JavaScript without any external libraries.
Currently, my progress works upon initial load and allows for dragging to the desired position. However, it fails to update again after that.
var object = document.querySelector('.js-slider-container'),
initX, firstX;
object.addEventListener('mousedown', function(e) {
e.preventDefault();
initX = this.style.transform;
firstX = e.pageX;
this.addEventListener('mousemove', dragIt, false);
console.log(initX);
window.addEventListener('mouseup', function() {
object.removeEventListener('mousemove', dragIt, false);
}, false);
}, false);
object.addEventListener('touchstart', function(e) {
e.preventDefault();
initX = this.style.transform;
var touch = e.touches;
firstX = touch[0].pageX;
this.addEventListener('touchmove', swipeIt, false);
window.addEventListener('touchend', function(e) {
e.preventDefault();
object.removeEventListener('touchmove', swipeIt, false);
}, false);
}, false);
function dragIt(e) {
this.style.transform = `translate3d(${initX+e.pageX-firstX}px,0,0)`;
}
function swipeIt(e) {
var contact = e.touches;
this.style.transform = `translate3d(${initX+contact[0].pageX-firstX}px,0,0)`;
}
Check out this jsfiddle demonstration. It initially works, but then fails to update its position consistently. I'm also struggling with setting boundaries to prevent over-scrolling. Any insights would be greatly appreciated. Thank you!