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 😀
You can keep track of the difference in cursor position when
mousemoveing with the starting cursor position when youmousedowned, and apply this data appropriately: http://jsfiddle.net/BggPn/15/.and: