Last active
January 2, 2024 07:22
-
-
Save Arifursdev/9c3d36a9d27b48f5788d48a3d34bbcc5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HorizontalScrollDragger { | |
constructor(element) { | |
this.slider = typeof element === "string" ? document.querySelector(element) : element instanceof Element ? element : null; | |
if (this.slider === null) return console.error("HorizontalScrollDragger: Element not found"); | |
this.isDown = false; | |
this.preventClick = false; | |
this.startX; | |
this.scrollLeft; | |
this.init() | |
} | |
init() { | |
this.slider.addEventListener("mousedown", e => this.handleMouseDown(e)); | |
this.slider.addEventListener("mouseleave", () => this.handleMouseLeave()); | |
this.slider.addEventListener("mouseup", () => this.handleMouseUp()); | |
this.slider.addEventListener("mousemove", e => this.handleMouseMove(e)); | |
this.slider.addEventListener("click", e => this.handleClick(e)) | |
Array.from(this.slider.querySelectorAll('img,a,button') ).forEach(child => { | |
child.addEventListener('dragstart', e => e.preventDefault()); | |
}); | |
} | |
handleMouseDown(e) { | |
this.isDown = true; | |
this.slider.classList.add("adev-dragging"); | |
this.startX = e.pageX - this.slider.offsetLeft; | |
this.scrollLeft = this.slider.scrollLeft; | |
this.preventClick = false | |
} | |
handleMouseLeave() { | |
this.isDown = false; | |
this.slider.classList.remove("adev-dragging") | |
} | |
handleMouseUp() { | |
this.isDown = false; | |
this.slider.classList.remove("adev-dragging") | |
} | |
handleMouseMove(e) { | |
if (!this.isDown) return; | |
e.preventDefault(); | |
const x = e.pageX - this.slider.offsetLeft; | |
const walk = (x - this.startX) * 3; | |
this.slider.scrollLeft = this.scrollLeft - walk; | |
this.preventClick = true | |
} | |
handleClick(e) { | |
if (this.preventClick) { | |
e.stopPropagation(); | |
e.preventDefault() | |
} | |
} | |
} | |
document.addEventListener('init:adev:horizontal:scrollable', function () { | |
document.querySelectorAll('[data-adev-horizontal-scrollable]:not(.adev-initialized)').forEach(function (element) { | |
element.classList.add('adev-initialized'); | |
new HorizontalScrollDragger(element); | |
}); | |
}); | |
document.dispatchEvent(new CustomEvent('init:adev:horizontal:scrollable')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment