Skip to content
Advertisement

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">
</picture>

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?

Advertisement

Answer

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">
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement