Shawn31313 Shawn31313 - 1 month ago 14
Javascript Question

Drag and Drop - JQuery Plugin

I'm trying to create my own Drag and Drop Plugin.

My Plugin:

$.fn.drag = function(options) {
var defaults = {
revert: false,
onDrag: function() {},
onDrop: function() {}
};
var o = $.extend(defaults, options);
return this.each(function() {
var position = $(this).position();
var ptop = position.top;
var pleft = position.left;
var down = false;
$(this).mousedown(function(event) {
down = true;
$(this).css({
cursor: 'move',
}).mousemove(function(event) {
if (down == true) {
$(this).css({
cursor: 'move',
});
var w = $(this).width();
var h = $(this).height();
var left3 = (w / 2) + 7;
var top3 = (h / 2) + 7;
$(this).css({
cursor: 'move',
left: (event.clientX) + (3 * 3) - left3,
top: (event.clientY) + (3 * 3) - top3
});
}
}).bind('mousemove', o.onDrag).mouseup(function() {
down = false;
$(this).css({
cursor: 'default',
});
if (o.revert == true) {
$(this).animate({
top: ptop,
left: pleft
}, 300);
} else {}
}).bind('mouseup', o.onDrop);
});
});
}


My Problem: At the moment when I try to drag the matched element it centers the cursor inside. I did that on purpose because I didnt know how to make it so if I click on any part of the element it will drag. As you can see here

Centering Cursor inside element code:

var w = $(this).width();
var h = $(this).height();
var left3 = (w / 2) + 7;
var top3 = (h / 2) + 7;
$(this).css({
cursor: 'move',
left: (event.clientX) + (3 * 3) - left3,
top: (event.clientY) + (3 * 3) - top3
});


Is there a way not to center the cursor inside the element and be able to drag the element wherever you click it?

Thanks in advance :D

Answer

You can keep track of the difference in cursor position when mousemoveing with the starting cursor position when you mousedowned, and apply this data appropriately: http://jsfiddle.net/BggPn/15/.

$(this).mousedown(function(event) {
    down = true;
    var dx = event.pageX - $(this).position().left, // difference from left border
        dy = event.pageY - $(this).position().top;  // difference from top border

and:

$(this).css({
    cursor: 'move',         // you had set the cursor already by the way
    left: event.pageX - dx, // set left border to cursor x position minus difference
    top:  event.pageY - dy  // set top border to cursor y position minus difference
});