karse23
karse23

Reputation: 4115

reposition element when the event dragstart is fired in jquery

I'm trying to reposition an item when the dragstart event is fired.

The item should be relocated from the current position of the mouse on the screen before being dragged.

The option of relocating the on the mousedown event that is fired just before the dragstart is not useful for what I'm looking for.

I'm trying by this way:

var xMouse = 0;
var yMouse = 0;

$(document).mousemove(function(e){
    xMouse = e.pageX; 
    yMouse = e.pageY;
});

$( "#obj" ).draggable({ 
    revert: false,
    start: function() { 
        $( "#obj" ).css("left", xMouse+"px");
        $( "#obj" ).css("top", yMouse+"px");    
    }
});

$( "#obj" )
.bind('dragstart',function( event ){
    $( "#obj" ).css("left", xMouse+"px");
    $( "#obj" ).css("top", yMouse+"px");                    
})
.bind('drag',function( event){

})

Thanks in advance.

Upvotes: 0

Views: 655

Answers (1)

Jordan Kasper
Jordan Kasper

Reputation: 13273

The problem is that jQuery UI's "dragging" uses absolute positioning to move the node around, thus your manual positioning in the drag start is completely overwritten. That said, you could use the cursorAt option to position the mouse cursor in the dragged node:

$( "#obj" ).draggable({ 
  revert: false,
  cursorAt: { left: 0, top: 0 }
});

Here's a jsFiddle for it.

Upvotes: 1

Related Questions