Skip to content

Instantly share code, notes, and snippets.

@crccheck
Forked from Arty2/jquery.draggable.js
Created October 6, 2017 16:39
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 crccheck/e50a0f4eedce804eede145085d70e770 to your computer and use it in GitHub Desktop.
Save crccheck/e50a0f4eedce804eede145085d70e770 to your computer and use it in GitHub Desktop.
jQuery plugin to make elements draggable without jQuery UI. Usage: view source on http://jqueryui.com/draggable/
/*--------------------------------------------------------------
Draggable
alternative to jQuery UI’s draggable
based on comments from: http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
usage example: $('.post-thumbnail, article header').draggable();
--------------------------------------------------------------*/
// https://gist.github.com/Arty2/11199162
$.fn.draggable = function () {
this
.css('cursor', 'move')
.on('mousedown touchstart', function (e) {
const $dragged = $(this);
const x0 = e.pageX;
const y0 = e.pageY;
if (!$.fn.draggable.stack) {
$.fn.draggable.stack = 1000;
}
const stack = $.fn.draggable.stack;
$(window)
.on('mousemove.draggable touchmove.draggable', (e) => {
e.preventDefault();
$dragged
.css({
transform: `translate(${e.pageX - x0}px, ${e.pageY - y0}px)`,
zIndex: stack
})
.find('a').one('click.draggable', (e) => {
e.preventDefault();
});
})
.one('mouseup touchend touchcancel', function () {
$(this).off('mousemove.draggable touchmove.draggable click.draggable');
const offset = $dragged.offset();
$dragged.css({
top: offset.top - e.pageY + y0,
left: offset.left - e.pageX + x0,
transform: 'unset',
zIndex: stack
});
$.fn.draggable.stack++;
});
e.preventDefault();
});
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment