Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener drop not firing

I am trying to attach a drop event to an HTML div:

document.getElementById('sub-main').addEventListener("drop", 
                                     () => {console.log('DROP')});

but it does not fire. Adding a click event for test purposes worked - this click event fires:

document.getElementById('sub-main').addEventListener("click", 
                                     () => {console.log('Click')});

I have read that returning false from ondragover will help:

document.getElementById('sub-main').addEventListener("ondragover", 
                                     () => {return false});

document.getElementById('sub-main').addEventListener("drop", 
                                     () => {console.log('Drop')});

But this does not work either. I tried setting draggable to true:

document.body.setAttribute('draggable', true);

But also no luck!

Logging the event listeners to the console with getEventListeners() shows all the events, even any random event name I chose:

getEventListeners(document.getElementById('sub-main'));

But the drop event still does not fire. Any ideas?

like image 299
Alex Avatar asked Oct 10 '17 13:10

Alex


People also ask

What event is triggered when an element is being dragged over a drop target?

The ondragover event occurs when a draggable element or text selection is being dragged over a valid drop target. By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element.

What is drop event?

The drop event is fired when an element or text selection is dropped on a valid drop target.

What is drop in Javascript?

The ondrop event occurs when a draggable element or text selection is dropped on a valid drop target. Drag and drop is a very common feature in HTML5. It is when you "grab" an object and drag it to a different location. For more information, see our HTML Tutorial on HTML5 Drag and Drop.


1 Answers

To enable dragging you should first of all disable the default behavior of the browser using the dragover event.

add this piece of code and it will work.

document.addEventListener("dragover", function(event) {
  event.preventDefault();
});
like image 191
Tamir Nakar Avatar answered Oct 10 '22 15:10

Tamir Nakar