Skip to content

Instantly share code, notes, and snippets.

@hannesl
Created October 23, 2012 20:38
Show Gist options
  • Select an option

  • Save hannesl/3941382 to your computer and use it in GitHub Desktop.

Select an option

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.
$(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