How can I disable image dragging on a element with Javascript?


I am unable to disable image dragging when using a <picture> element. I have used this in the past with an <img> element with success. I’m not sure why it doesn’t work with <picture>.

HTML Code:

<picture class="thumb">
<source class="nodrag" srcset="image.webp" type="image/webp">
<source class="nodrag" srcset="image.gif" type="image/gif">
<img class="thumb" src="image.gif">

My Javascript:

document.getElementsByClassName('thumb').ondragstart = function () { return false; };
document.getElementsByClassName('nodrag').ondragstart = function () { return false; };

The above did not work. Is there another way I can disable dragging of a element to prevent users from dragging to save the image?


Not sure if it will work for your use-case but have you tried the HTML draggable attribute?

<img class="thumb" src="image.gif" draggable="false">

Source: stackoverflow