Last active
November 27, 2017 09:13
-
-
Save arielsalminen/fdcec0ee23a64a51b5c3 to your computer and use it in GitHub Desktop.
Drag and scroll in plain JS
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
var element, | |
isPushed = false, | |
scrollTop = 0, | |
scrollLeft = 0, | |
lastClientX = 0, | |
lastClientY = 0; | |
var DragScroll = { | |
onMouseDown : function(e) { | |
element = e.target; | |
isPushed = true; | |
element.addEventListener("mousemove", this.onMouseMove); | |
element.addEventListener("mouseup", this.onMouseUp); | |
element.addEventListener("mouseleave", this.onMouseUp); | |
lastClientX = e.clientX; | |
lastClientY = e.clientY; | |
e.preventDefault(); | |
e.stopPropagation(); | |
}, | |
onMouseUp : function() { | |
if (isPushed) { | |
element.removeEventListener("mousemove", this.onMouseMove); | |
element.removeEventListener("mouseup", this.onMouseUp); | |
element.removeEventListener("mouseleave", this.onMouseUp); | |
isPushed = false; | |
} | |
}, | |
onMouseMove : function(e) { | |
if (isPushed) { | |
element.scrollLeft -= (e.clientX - lastClientX); | |
element.scrollTop -= (e.clientY - lastClientY); | |
lastClientX = e.clientX; | |
lastClientY = e.clientY; | |
} | |
} | |
}; | |
// INIT | |
document.querySelector(".draggable").addEventListener("mousedown", DragScroll.onMouseDown, false); |
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
.draggable { | |
cursor: move; | |
cursor: -webkit-grab; | |
&:active { | |
cursor: -webkit-grabbing; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment