Skip to content

Instantly share code, notes, and snippets.

@abdasis
Last active March 4, 2023 02:37
Show Gist options
  • Save abdasis/eba558ccd3d6020e3f73a47ef23c14c9 to your computer and use it in GitHub Desktop.
Save abdasis/eba558ccd3d6020e3f73a47ef23c14c9 to your computer and use it in GitHub Desktop.
Snippet Javascript untuk membuat horizontal scroll menggunakan drag dari Mouse
let curXPos = 0,
curDown = false,
scrollLeft = 0;
const dragable = document.querySelector('.table');
dragable.addEventListener('mousemove', function(e) {
if (curDown === true) {
const walk = (curXPos - e.pageX);
scrollLeft = scrollLeft + walk;
document.querySelector('.table-responsive').scrollLeft = scrollLeft;
curXPos = e.pageX;
}
});
dragable.addEventListener('mousedown', function(e) {
curDown = true;
curXPos = e.pageX;
dragable.style.cursor = 'grabbing';
});
dragable.addEventListener('mouseup', function(e) {
curDown = false;
dragable.style.cursor = '';
});
dragable.addEventListener('mouseleave', function(e) {
curDown = false;
dragable.style.cursor = '';
});
function smoothScroll() {
scrollLeft += (scrollTarget - scrollLeft) * 0.1;
document.querySelector('.table-responsive').scrollLeft = scrollLeft;
if (Math.abs(scrollLeft - scrollTarget) > 1) {
requestAnimationFrame(smoothScroll);
} else {
document.querySelector('.table-responsive').scrollLeft = scrollTarget;
}
}
let scrollTarget = 0;
document.querySelector('.table-responsive').addEventListener('wheel', function(e) {
e.preventDefault();
const delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
scrollTarget = scrollTarget + (delta * 30);
if (!scrolling) {
requestAnimationFrame(smoothScroll);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment