Skip to content

Instantly share code, notes, and snippets.

@balkhaev
Last active March 7, 2020 02:05
Show Gist options
  • Save balkhaev/81e1ec83f609b110accad3ed1e835cb5 to your computer and use it in GitHub Desktop.
Save balkhaev/81e1ec83f609b110accad3ed1e835cb5 to your computer and use it in GitHub Desktop.
Vanilla js drag handlers
let dragStartX = null;
let dragStarted = false;
let currentPositionX = 0;
function dragStart(e) {
// Клик правой кнопкой
if (e.button === 2) {
return;
}
var isMouseEvent = e instanceof MouseEvent;
if (isMouseEvent) {
e.preventDefault();
}
dragStartPosX = isMouseEvent ? e.clientX : e.touches[0].clientX;
}
function drag(e) {
if (dragStartPosX === null) {
return;
}
dragStarted = true;
var isMouseEvent = e instanceof MouseEvent;
var clientX = isMouseEvent ? e.clientX : e.touches[0].clientX;
var shiftX = dragStartPosX - clientX;
currentPositionX = dragStartPosX + shiftX;
element.style.transform = `translateX(${currentPositionX})`;
}
function dragEnd() {
if (!dragStarted) {
return;
}
dragStarted = false;
dragStartX = null;
if (currentPositionX < 0) {
currentPositionX = 0;
} else if (currentPositionX > maxRightPositionX) {
currentPositionX = maxRightPositionX;
}
element.style.transform = `translateX(${currentPositionX})`;
}
wrapper.addEventListener('mousedown', dragStart);
wrapper.addEventListener('mousemove', drag);
window.addEventListener('mouseup', dragEnd);
wrapper.addEventListener('touchstart', dragStart);
wrapper.addEventListener('touchmove', drag);
window.addEventListener('touchend', dragEnd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment