Skip to content

Instantly share code, notes, and snippets.

@av01d
Last active July 23, 2020 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save av01d/8698aef1ffa6d60ed16900c92ccb25a0 to your computer and use it in GitHub Desktop.
Save av01d/8698aef1ffa6d60ed16900c92ccb25a0 to your computer and use it in GitHub Desktop.
Super simple jQuery plugin for making DOM elements draggable. Touch compatible.
// 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);
@av01d
Copy link
Author

av01d commented Jul 23, 2020

Serving suggestion:

var maxZindex = 1, $ctr = $('#container');

$ctr
.draggable({
   handle: '.header',
   containment: true,
   dragstart: function(e) { $ctr.css('zIndex', maxZindex++); }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment