JavaScript - Disable the drag and drop on html element
In this tutorial, we are going to learn about how to disable drag and drop on an html element using JavaScript.
Consider, that we have the following div element in our HTML:
<div id="container">
<h1>Placeholder image</h1>
<img src="https://via.placeholder.com/150" />
</div>
To disable the drag and drop on an element, first we need to access that element inside the JavaScript using the document.getElementById()
method, then add the dragstart
and drop
events to the element and call the event.preventDefault()
method inside it
The event.preventDefault()
method prevents the browser from default actions, so it disables the element from drag and drop.
Here is an example:
<div id="container">
<h1>Placehodler image</h1>
<img src="https://via.placeholder.com/150" />
</div>
const divEl = document.getElementById("container");
divEl.addEventListener("dragstart",(event)=>{
event.preventDefault();
})
div.addEventListener('drop', (event) => {
e.preventDefault();
})
In the example above, we have added the dragstart
and drop
events to the div
element and called the event.preventDefault()
method inside it, so it prevents the user from dragging and dropping.
The HTML dragstart event is fired when a user tries to drag an element inside the webpage.
The HTML drop event is fired when a user tries to drop an element inside the webpage.
Similarly, we can also disable the drag and drop on an element by calling the event.preventDefault()
method inside a mousedown
event handler function.
Here is an example:
<div id="container">
<h1>Placehodler image</h1>
<img src="https://via.placeholder.com/150" />
</div>
const divEl = document.getElementById("container");
divEl.addEventListener("mousedown",(event)=>{
event.preventDefault();
})
The mousedown event is fired at an element when a user presses the mouse button.
Disable Drag and Drop using CSS
We can also disable drag and drop on the html elements by setting the css pointer-events
property to none
.
When we set a pointer-events property to a value "none"
, the element doesn’t respond to any cursor or touch events.
Here is an example:
<div id="container">
<h1>Placehodler image</h1>
<img src="https://via.placeholder.com/150" />
</div>
#container{
pointer-events: none;
}