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

javascript

In jQuery, you can use the draggable and droppable widgets to create drag and drop functionality. When an element is being dragged, you can use the ui object to get a reference to the element being dragged.

Here’s an example of how to get the element being dragged in a drag and drop interaction using jQuery:

HTML:

<div class="draggable">Drag me</div>
<div class="droppable">Drop here</div>

JavaScript:

$(function() {
  $(".draggable").draggable({
    start: function(event, ui) {
      // get the element being dragged
      var draggedElement = ui.helper;
      console.log("Dragging element:", draggedElement);
    }
  });

  $(".droppable").droppable({
    drop: function(event, ui) {
      // get the element being dropped
      var droppedElement = ui.draggable;
      console.log("Dropped element:", droppedElement);
    }
  });
});

In this example, the draggable function is called on the element with class draggable, and the droppable function is called on the element with class droppable. When the element is being dragged, the start callback function is called, and the ui.helper property is used to get a reference to the element being dragged. This reference is then logged to the console.

When the element is dropped onto the droppable area, the drop callback function is called, and the ui.draggable property is used to get a reference to the element being dropped. This reference is then logged to the console.

Note that the ui object also contains other useful information about the drag and drop interaction, such as the current position of the element being dragged and the offset from the mouse pointer to the element.