We can disable drag and drop on HTML elements by setting the draggable
attribute to false
.
For instance, we can write:
<div draggable="false">
hello world
</div>
We set draggable
to false
so we can’t drag it.
To make it more robust, we can also stop the default drag and drop behavior with:
const div = document.querySelector('div')
div.addEventListener('dragstart', (e) => {
e.preventDefault()
})
div.addEventListener('drop', (e) => {
e.preventDefault()
})
We add event listeners for the dragstart
and drop
events with addEventListener
.
And we call e.preventDefault()
on both to stop the default drag and drop action.
One reply on “How to Disable Drag and Drop on HTML Elements?”
The addEventListener didn’t work in my case.
There’s a turnaround:
window.onload = function() {
// your stuff
// takes all images and loops through them
let imgs = document.querySelectorAll(‘img’);
for (let i=0; i<imgs.length; i++) {
// sets element undraggable
imgs[i].draggable = false;
}
Hope that helps.
Daniele