-
-
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/
This file contains 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
/*-------------------------------------------------------------- | |
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