Search code examples
javascriptjqueryjquery-uitriggersdrag-and-drop

jquery select a div where I released my drag and drop click


My HTML is like this

<div name="draggable">
<div>element1</div>
<div>element2</div>
...
</div>

<div id="dragDrop_target-1"></div>
<div id="dragDrop_target-2"></div>
...

I trigger an event with .mouseup by coding this in jQuery

jQuery( this ).find("[id^=dragDrop_target-]").mouseup(function() {...} );

It works well but the selector finds the target box from where my element comes and not the target box where the element goes. I logically tried with .mousedown but without success.

What is the right way to select the div I've dropped an element into ( /or/ where I released the click above)?


Solution

  • Since you have several drop targets and following @freedomn-m's advice to use the drop event I propose the following general code that also uses a delegated event handler.

    https://api.jquery.com/on/#on-events-selector-data-handler

    Using a delegated event handler allows you to have one common event handler for many drop targets and you can dynamically add and remove drop targets to the DOM without having to add or remove event handlers.

    In the general case your target drop element may have children that could end up as event.target therefore, we use $(event.target).closest() to find their parent of the desired class. https://api.jquery.com/closest/#closest-selector

    $("#SomeCommonParentElement").on({
        drop: function (event) {
            var $yourDiv = $(event.target).closest(".dropzone");
            // do something with $yourDiv (a jQuery object)
        }
    }, ".dropzone");
    

    Of course you will have to add the proposed class dropzone to all elements that should act as drop zone and choose one common parent element of all drop zones (here an element with id SomeCommonParentElement) as the holder of the event listener, like so:

    <div id="SomeCommonParentElement">
      <div id="dragDrop_target-1" class="dropzone"></div>
      <div id="dragDrop_target-2" class="dropzone"></div>
    </div>