Search code examples
jqueryjquery-uijquery-ui-draggablejquery-ui-sortablejquery-ui-droppable

How do I position JQuery UI Sortable item at mouse cursor while dragging?


I'm using Jquery sortable to reorder items. In my GUI I have a traschan icon where sort items can be thrown away. The trashcan is a droppable area.

Now, when the sort item helper hovers over the droppable area I change it's size to give the user the visual feedback that it's possible to throw it away. But I would also like to reposition the sort item helper so it aligns with the mouse cursor.

I tried:

$(trashcan)
    .droppable(
    {
        over: function (event, ui)
        {
            ui
                .draggable
                .css("transform", "scale(0.2)")
                .sortable("option", "cursorAt",
                {
                    left: 5,
                    top: 5
                });
        }
    });

But I only get the following js error: Error: cannot call methods on sortable prior to initialization; attempted to call method 'option'


Solution

  • You're calling the option method on an element before initializing it as sortable.

    try

    element.draggable()
        .sortable({ cursorAt: { left: 5, top: 5 } }); // pass the options while initializing
    

    or if it is not possible for some reason, try

    element.draggable()
        .sortable(); //initialize first
    
    element.sortable("option", "cursorAt", // then call option method
        {
            left: 5,
            top: 5
        });