Thought leadership from the most innovative tech companies, all in one place.

How to Disable Dragging an Image from an HTML Page

image

Sometimes, we may want to disable dragging an image from an HTML page.

In this article, we'll look at ways to disable dragging an image from a page.

Set the ondragstart Property to a Function that Returns false

One way to disable dragging an image from an HTML page is to set the ondragstart property of an image element to a function that returns false .

For instance, if we have the following HTML:

<img
  src="https://i.picsum.photos/id/49/200/300.jpg?hmac=mC_cJaZJfrb4JZcnITvz0OOwLCyOTLC0QXH4vTo9syY"
/>

We can write:

const img = document.querySelector("img");
img.ondragstart = () => {
  return false;
};

to set ondragstart to a function that returns false .

Set the pointer-event CSS Property to none

Another way to disable dragging an image is to set the pointer-event CSS property to none .

For example, if we have the following HTML:

<img
  src="https://i.picsum.photos/id/49/200/300.jpg?hmac=mC_cJaZJfrb4JZcnITvz0OOwLCyOTLC0QXH4vTo9syY"
/>

Then we can disable dragging by writing:

img {
  pointer-events: none;
}

Setting the draggable HTML Attribute to false

We can also set the draggable HTML attribute of the img element we want to disable dragging for to false .

To do this, we write:

<img
  draggable="false"
  src="https://i.picsum.photos/id/49/200/300.jpg?hmac=mC_cJaZJfrb4JZcnITvz0OOwLCyOTLC0QXH4vTo9syY"
/>

to disable dragging.

To do the same thing with JavaScript, we can use the setAttribute method:

const img = document.querySelector("img");
img.setAttribute("draggable", false);

We call setAttribute with the attribute name and value respectively.

Conclusion

There are several ways to disable the dragging of an image with HTML, CSS, or JavaScript.




Continue Learning