Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery drag and drop - how to get at element being dragged

People also ask

How do you get the position of the draggable element?

The . position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with . offset() , which retrieves the current position relative to the document.

What is jQuery draggable?

Draggable() Method This method allows the elements to be dragged with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port.

What is jQuery Ondrop?

The ondrop event occurs when a draggable element or text selection is dropped on a valid drop target.


Is it not the ui.draggable?

If you go here (in Firefox and assuming you have firebug) and look in the firebug console youll see I am doing a console.dir of the ui.draggable object which is the div being dragged

http://jsbin.com/ixizi

Therefore the code you need in the drop function is

       drop: function(ev, ui) {
                 //to get the id
                 //ui.draggable.attr('id') or ui.draggable.get(0).id or ui.draggable[0].id
                 console.dir(ui.draggable)  
       }

$(ui.draggable).attr("id")    

...


The ui.draggable() does not seem to work any more. To get the id one can use

$(event.target).attr("id");

ANSWER THAT WORKS IN 2017

A lot of time has passed by, and I found that the current accepted answer no longer works.

A solution that currently works:

$('#someDraggableGroup').draggable({
                helper: 'clone',
                start: function( event, ui ) {
                    console.log(ui.helper.context)
                    console.log(ui.helper.clone())
                }
            })

Here, ui.helper.context refers to the original object you're trying to drag, and clone() refers to the cloned version.

EDIT

The above is too see which object you're dragging using the draggable() function. For detecting what draggable object was dropped in a droppable(), the following works:

$('#myDroppable').droppable({
    drop: function(event, ui){
        console.log(ui.draggable.context)
                 OR
        console.log(ui.draggable.clone() )
    }
})