Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery UI Draggable: Align helper to mouse position

With jQuery I have a draggable element. It's a div with a size of 200 x 40. Of course the user can start dragging this div by clicking at variuos positions in the div. What I want is when the startdrag event happens, the helper (clone) div will always be aligned to the cursor the same way, no matter where in the div the user started dragging.

So after the mousedown the helper's top and left values need to be the same as the mouses x and y. I've tried this using this coffeescript code:

onStartDrag: ( e, ui ) =>
    ui.helper.css
        left: e.clientX
        top: e.clientY

    console.log( e )

But it doesn't work and my guess is that this is happening because the values I put in are directly overwritten by the draggable plugin because of mouse movement..

Any ideas?

like image 926
Tim Baas Avatar asked Nov 05 '12 10:11

Tim Baas


2 Answers

After trying Amar's answer and realizing that it screws up interactions with droppable, I dug deeper, and found that there is an option specifically to support this called cursorAt.

$('blah').draggable
  helper: ->
    ... custom helper ...
  cursorAt:
    top: 5
    left: 5

This places the top-left corner of the helper 5 pixels above and to the left of the cursor, and interacts correctly with droppable.

http://api.jqueryui.com/draggable/#option-cursorAt

And let's give credit where credit is due. Thanks, jquery-ui mailing list archives!

https://groups.google.com/forum/#!topic/jquery-ui/Evb94G_QvNw

like image 62
Dan Burton Avatar answered Oct 26 '22 18:10

Dan Burton


Try setting like this,

       start: function (event, ui) {
                $(ui.helper).css("margin-left", event.clientX - $(event.target).offset().left);
                $(ui.helper).css("margin-top", event.clientY - $(event.target).offset().top);
            }

Take a look at this jqFAQ.com , it will be more helpful for you.

like image 39
Amar Avatar answered Oct 26 '22 19:10

Amar