Search code examples
javascripthtmldrag-and-drop

Drag and Drop 'dragover' event to catch the draggable parent and not the child when I drag over an item? Simple Example Inside


The code I present below is fully functional. When you drag an item over another, the dragover event catches and displays it.

To understand what I mean try it yourself here: https://jsfiddle.net/athanasis/oydbrsxt/2/

The behavior I don't like: With my code, try to drag any item over to any "Sub-Content" or "Content" word in the list. The dragover event catches and displays that element's text and not the parent draggable li element's text.

Javascript (Pure):

<script>
  document.addEventListener('dragover', function (event) { allowDrop(event); }, true);
    function allowDrop(ev) 
    {   el = ev.target;
        document.getElementById("result").innerHTML = el.innerHTML;
    }    
</script>

HTML:

<div id="result">CLICK AND DRAG ON ANOTHER ITEM</div>
<ul>Category 1 
    <li draggable="true">item 1 <span> Content 1 <span> Sub-Content 1</span> </span> </li>
    <li draggable="true">item 2 <span> Content 2 <span> Sub-Content 2</span> </span> </li>     
    <li draggable="true">item 3 <span> Content 3 <span> Sub-Content 3</span> </span> </li>
    <li draggable="true">item 4 <span> Content 4 <span> Sub-Content 4</span> </span> </li>
    <li draggable="true">item 5 <span> Content 5 <span> Sub-Content 5</span> </span> </li>
</ul>

Any idea as to how I can catch and display the parent element when I drag over to any child AND NOT the child itself ???


Solution

  • We can go up the hierarchy until we are satisfied with the results:

    document.addEventListener('dragover', function (event) { allowDrop(event); }, true);
        function allowDrop(ev) 
        {   el = ev.target;
                while ((el.tagName !== "LI") && (el.tagName !== "BODY")) el = el.parentNode;
            document.getElementById("result").innerHTML = el.innerHTML;
        }    
    
        
    

    Fiddle: https://jsfiddle.net/Lnrt2zx1/