Explain Codes LogoExplain Codes Logo

Disable dragging an image from an HTML page

html
responsive-design
pointer-events
accessibility
Nikita BarsukovbyNikita Barsukov·Sep 10, 2024
TLDR

Use the draggable="false" attribute to prevent an image from being dragged:

<img src="image.jpg" alt="" draggable="false">

In JavaScript, halt the drag event like so:

document.addEventListener('dragstart', event => { // If it's an image we snagged, let's anchor it. if (event.target.tagName === 'IMG') event.preventDefault(); });

Either of these methods will keep those pesky images from hitching a ride on your cursor.

Browser compatibility considerations

Unfortunately, not all browsers woke up and chose uniformity. While the draggable="false" attribute works with most modern browsers, some older versions of Firefox might beg to differ. So, do remember to test your solution on different platforms to ensure that your images behave themselves.

Clamping down on all drag events is another option. It's a bit like closing the entire park because a few kids can't play nice:

window.ondragstart = function() { return false; };

This will block drag-and-drop for all elements on your page, so use it wisely.

CSS can help too

If you're more of a CSS person, you could side-step the issue with pointer-events:

img { pointer-events: none; /* Now the image won't hitchhike with your cursor */ }

However, your image loses more than its luggage; it won't respond to clicks or follow other cursor demands either.

Even resizable images can behave

Even when you've forbidden them from dragging themselves around your page, your images can still hit their growth spurt with resize functionality:

document.addEventListener('mousedown', event => { // If it's an image, we'll handle the growing pains if (event.target.tagName === 'IMG') { // Image resizing magic happens here } });

Remember, you're only grounding them, not taking away all of their powers!

jQuery has your back

For those who've sworn their loyalty to jQuery, it's got your back:

$('img').on('dragstart', function(event) { event.preventDefault(); });

It's quite compact, but don't go to town and include jQuery just for this. It's handy, not miraculous.

Stay responsive

In this day and age, who isn't concerned with staying responsive? Don't worry, these tricks won't interfere with your image's ability to suit its environment.

Accessibility matters

No functionality should come at the cost of accessibility. Setting draggable="false" won't muss up the screen reader experience, ensuring everyone continues to access image information easily.

Pitfall alert

Just as you dodge potholes on the road, avoid -moz-user-select and similar vendor-specific CSS properties. They're as reliable as a fair-weather friend. Stick to standard properties that are notorious for their trustworthy behavior.