public
Created

A CodePen by Chris Coyier. jQuery Draggable with out jQuery UI - It doesn't have all the fancy callbacks and options, but hey, it makes things draggable. From: http://reader-download.googlecode.com/svn/trunk/jquery-draggable/index.html

  • Download Gist
index.html
HTML
1
<div>Drag me</div>
script.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
(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;
$drag.css('z-index', 1000).parents().on("mousemove", function(e) {
$('.draggable').offset({
top:e.pageY + pos_y - drg_h,
left:e.pageX + pos_x - drg_w
}).on("mouseup", function() {
$(this).removeClass('draggable').css('z-index', z_idx);
});
});
e.preventDefault(); // disable selection
}).on("mouseup", function() {
if(opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
 
}
})(jQuery);
 
$('div').drags();
style.css
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14
div {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
background: red;
color: white;
position: absolute;
left: 20px;
top: 20px;
}
 
body {
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.