Disable dragging an image from an HTML page
Use the draggable="false"
attribute to prevent an image from being dragged:
In JavaScript, halt the drag event like so:
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:
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
:
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:
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:
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.
Was this article helpful?