Search code examples
javascripthtmlcssstyling

Disable dragging of image in entire project HTML pages


I want to disable dragging of all the images in my project which has a large amount of images. The results that I found on web was to disable a particular image. Putting draggable="false" inside every image tag would take a lot of time. So I want a solution to disable them together.

I was successful to disable dragging with this code but it's still draggable in Firefox .

img {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-user-drag: none;
  user-drag: none;
  -webkit-touch-callout: none;
}

I've already gone through Disable dragging an image from an HTML page but found no answer to my question.


Solution

  • You could add ondragstart attribute to single image & return false.

    If you want to address multiple images

    const imgs = document.getElementsByTagName('img');
    for(let i = 0; i < imgs.length; i++ ) {
        imgs[i].setAttribute("ondragstart", "return false")
    }
    

    Note from React Synthetic events

    As of v0.14, returning false from an event handler will no longer stop event propagation. Instead, e.stopPropagation() or e.preventDefault() should be triggered manually, as appropriate.

    So you need add to each image.

    <img src={source} onDragStart={e => e.preventDefault()} />