views:

67

answers:

1

Hello,

I am using jquery ui for drag and drop. I am trying to get mouse position relative to div, here is my code:

$( "#db_tables " ).droppable({
  activeClass: "ui-state-default",
  hoverClass: "ui-state-hover",
  drop: function( event, ui ) {
    var x = ui.position.left - ui.offset.left; // tired event.pageX - this.offsetLeft;
    var y = ui.position.top - ui.offset.top; // tired event.pageY - this.offsetTop;
    $( '<div style="margin-top:' + y   + 'px; margin-left:' + x   + 'px; "></div>' ).html( ui.draggable.html() ).appendTo( this );
  }
});

But the position of dropped div is not correct, Can anybody please tell me what is wrong with code?

+2  A: 

Take a look here:

http://docs.jquery.com/Tutorials:Mouse_Position

event.pageX and event.pageY should give you mouse position

$("#drag").draggable({
    stop: function(event, ui){
        var x = event.pageX - ui.offset.left;
        var y = event.pageY - ui.offset.top;       
    }
});

EDIT: here's an example showing how to track the mouse position relative to the element you are dragging http://jsfiddle.net/87fqr/1/

ANOTHER EDIT:

This should work if you want the position of the mouse relative to the droppable:

$( "#db_tables " ).droppable({
    activeClass: "ui-state-default",
    hoverClass: "ui-state-hover",
    drop: function( event, ui ) {
        var x = event.pageX - $(this).offset().left;
        var y = event.pageY - $(this).offset().top; 
        '<div style="margin-top:' + y   + 'px; margin-left:' + x   + 'px; "></div>' ).html( ui.draggable.html() ).appendTo( this );
    }
});

More complete example here: http://jsfiddle.net/87fqr/2/

fehays
But how to make the position relative to the div in which I am dropping?
Shishant
you can track the position in the stop event of your draggable http://jqueryui.com/demos/draggable/#event-stop you just need to subtract the offset of the element from the mouse position
fehays
I'm sorry, i think i misunderstood. Did you want the position relative to the element you are dragging or relative to the element you dropped in?
fehays
relative to dropped in
Shishant
Thank You very much. Is there a better way to write? `'<div style="margin-top:' + y + 'px; margin-left:' + x + 'px; "></div>'`
Shishant
It's personal preference I suppose. You could use the jquery object $("<div/>").css({marginLeft: x, marginTop: y});
fehays