Search code examples
javascriptdrag-and-dropaddeventlistener

What happens with the events in nested drag drop AddEventListener?


I have the following nested addEventListener to keep track of the dragged element and the element i am dragging to.

var objects = document.querySelector('.objects');
var destination = document.querySelector('.dest');


objects.addEventListener('dragstart', function(e) {
    console.log("dragstart")
    destination.addEventListener('dragover', function(e2) { e2.preventDefault(); });
    destination.addEventListener('drop', function(e2) {
        console.log("drop")
        console.log(e.target);
        console.log(e2.target);

    })
})
<style>
  div >div {
    margin: 50px;
    width: 100px;
    height: 100px;
    background-color: green;
  }
</style>

<body>
  <div class="objects">
    <div draggable='true' id='o1'>A</div>
  </div>

  <div class="dest">
    <div id='D1' >1</div>
  </div>
</body>

The first time i am drag and dropping everything seems as i expected, but when i drag and drop a second time, the addEventListener for drop is executed twice, and the third time, three times. Why is that so? enter image description here If i only console.log the drag and drop strings, this behavior of doubling and trippling does't show up. What happens with the events e and e2?


Solution

  • You can use removeEventListener to remove the earlier events that were added so that it doesn't get re-added every time it's dragged, in order to do that you just have to store the function separately though

    var objects = document.querySelector('.objects');
    var destination = document.querySelector('.dest');
    
    
    function dragFnc(e2) { 
      e2.preventDefault(); 
    }
    function dropt(e2) {
            console.log("drop")
            console.log(e2.target);
            e2.target.removeEventListener("dragover",dropt)
            e2.target.removeEventListener("drop",dragFnc)
    }
    objects.addEventListener('dragstart', function(e) {
        console.log("dragstart")
        destination.addEventListener('dragover', dragFnc);
        destination.addEventListener('drop', dropt)
    })
    <style>
      div >div {
        margin: 50px;
        width: 100px;
        height: 100px;
        background-color: green;
      }
    </style>
    
    <body>
      <div class="objects">
        <div draggable='true' id='o1'>A</div>
      </div>
    
      <div class="dest">
        <div id='D1' >1</div>
      </div>
    </body>