Skip to content

Instantly share code, notes, and snippets.

@NazarkinRoman
Last active September 25, 2018 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save NazarkinRoman/12654be37a35ca006375 to your computer and use it in GitHub Desktop.
Save NazarkinRoman/12654be37a35ca006375 to your computer and use it in GitHub Desktop.
Improved version of Draggable without jQuery UI https://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
// bug - on each click this code creates a new event listener for all $drag parents
// serious lack of memory and permormance
// solution - unbind this event on 'mouseup' and make 'mouseup' once-executable via one()
(function($) {
$.fn.drags = function(opt) {
opt = $.extend({handle: '', cursor: 'move'}, opt);
if(opt.handle === '') {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on('mousedown', function(e) {
if(opt.handle === '') {
var $drag = $(this).addClass('draggable');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
drg_h = $drag.outerHeight(),
drg_w = $drag.outerWidth(),
pos_y = $drag.offset().top + drg_h - e.pageY,
pos_x = $drag.offset().left + drg_w - e.pageX;
// bind first event
// why parents() ?
$drag.css('z-index', 1000).parents().on('mousemove.drags', function(e) {
$('.draggable').offset({
top:e.pageY + pos_y - drg_h,
left:e.pageX + pos_x - drg_w
}).one('mouseup', function() {
$(this).removeClass('draggable').css('z-index', z_idx);
// unbind first event
$drag.parents().unbind('mousemove.drags');
});
});
e.preventDefault(); // disable selection
}).on('mouseup', function() {
if(opt.handle === '') {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment