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?
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.
The drop event is fired when an element or text selection is dropped on a valid drop target.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With