Last active
July 23, 2020 14:26
-
-
Save av01d/8698aef1ffa6d60ed16900c92ccb25a0 to your computer and use it in GitHub Desktop.
Super simple jQuery plugin for making DOM elements draggable. Touch compatible.
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
// Plugin: jQuery.draggable | |
// Author: Arjan Haverkamp - webgear.nl | |
// Version: 1.0 | |
// Date: 2019-01-30 | |
(function($) { | |
$.fn.draggable = function(options) { | |
var $document = $(document), settings = $.extend({ | |
// These are the defaults. | |
handle: null, | |
dragstart: null, | |
dragmove: null, | |
dragend: null, | |
containment: null //$('body') | |
}, options); | |
return this.each(function() { | |
var $this = $(this), dragging = false, startX, startY, containerRect; | |
if (settings.containment) { | |
var $ctr = (true === settings.containment) ? $this.parent() : $(settings.containment); | |
containerRect = $ctr[0].getBoundingClientRect(); | |
} | |
function move(e) { | |
if (!dragging) { return; } | |
e = e.changedTouches ? e.changedTouches[0] : e; | |
var x = e.pageX - startX, y = e.pageY - startY; | |
if (settings.containment) { | |
var rect = $this[0].getBoundingClientRect(); | |
if (x < containerRect.x) { x = containerRect.x; } | |
if (y < containerRect.y) { y = containerRect.y; } | |
if (x > containerRect.width - rect.width + containerRect.x) { x = containerRect.width - rect.width + containerRect.x; } | |
if (y > containerRect.height - rect.height + containerRect.y) { y = containerRect.height - rect.height + containerRect.y; } | |
} | |
$this.offset({left:x, top:y}); | |
settings.dragmove && settings.dragmove(e); | |
} | |
function end(e) { | |
if (!dragging) { return; } | |
e = e.changedTouches ? e.changedTouches[0] : e; | |
dragging = false; | |
$document | |
.off('mousemove touchmove', move) | |
.off('mouseup touchend', end); | |
settings.dragend && settings.dragend(e); | |
} | |
$this.on('mousedown touchstart', function(e) { | |
if (settings.handle && !$(e.target).is(settings.handle)) {return;} | |
if ($(e.target).closest('[data-nodrag').length > 0) { return } | |
e.preventDefault(); | |
e = e.changedTouches ? e.changedTouches[0] : e; | |
dragging = true; | |
var offset = $this.offset(); | |
startX = e.pageX - offset.left; | |
startY = e.pageY - offset.top; | |
$document | |
.on('mousemove touchmove', move) | |
.on('mouseup touchend', end); | |
settings.dragstart && settings.dragstart(e); | |
}); | |
}); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Serving suggestion: