Created
October 23, 2012 20:38
-
-
Save hannesl/3941382 to your computer and use it in GitHub Desktop.
A simple JS/jQuery pattern for making an object draggable on touch and desktop devices.
This file contains hidden or 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
| $(document).ready(function() { | |
| var $handle = $("#handle"), | |
| dragging = false; | |
| // Make the slider handle draggable. | |
| var dragStart = function(e) { | |
| dragging = true; | |
| $handle.addClass("dragging"); | |
| // Prevent text select while dragging. | |
| $(document.body).css("user-select", "none"); | |
| }; | |
| var dragMove = function(e) { | |
| if (dragging) { | |
| // Move the handle horizontally with the cursor. | |
| $handle.offset({ | |
| left: e.pageX | |
| }); | |
| } | |
| } | |
| var dragEnd = function(e) { | |
| if (dragging) { | |
| // -- DO YOUR DIRT --- | |
| $(document.body).removeAttr("style"); | |
| $handle.removeClass("dragging"); | |
| dragging = false; | |
| } | |
| }; | |
| // Mouse events for the slider. | |
| $handle.mousedown(dragStart); | |
| $(document.body).mousemove(dragMove); | |
| $(document.body).mouseup(dragEnd); | |
| // Touch events for the slider. | |
| document.addEventListener("touchstart", function(e) { | |
| if (e.srcElement.id && e.srcElement.id == "handle") { | |
| dragStart(e); | |
| } | |
| }, true); | |
| document.addEventListener("touchmove", function(e) { | |
| if (dragging) { | |
| e.preventDefault(); // Prevent page scrolling. | |
| dragMove(e); | |
| } | |
| }, true); | |
| document.addEventListener("touchend", dragEnd, true); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment