Disable built-in dragging of text and images

Posted . Visible to the public.

Most browsers have built-in drag and drop support for different page elements like text and images. While this may be useful in most situations, it may become annoying in others. If you e.g. want to allow the user to scroll/move horizontally within a container by grabbing an item and moving the mouse, you will notice that nothing will move and you'll instead start dragging that element.

To disable this, add the following CSS to your content:

-webkit-user-drag: none
user-drag: none

-webkit-user-drag is only fully supported in Safari. Chrome allows you to use the none-value, but not element (which is enough in this case). The unprefixed property is not supported in any modern browser up to this point and specific support is limited to Webkit. Thus, Firefox will still allow the user to drag elements due to the lack of support.

To solve this, you will need to introduce some JavaScript. In earlier Firefox versions, adding an inline ondragstart="false"-handler was enough to bypass the functionality. This does no longer work. You may now achieve this by explicitly preventing the startdrag-event:

<div class"no-drag-pls">...</div>
const noDragElement = document.querySelector('no-drag-pls')
noDragElement.addEventListener('dragstart', event => event.preventDefault())

You may want to adapt this to the event listening mechanism you use (Unpoly's up.on, jQuery's .on, ...) and wrap the element selection into a compiler function.

Dominic Beger
Last edit
Dominic Beger
License
Source code in this card is licensed under the MIT License.
Posted by Dominic Beger to makandra dev (2021-09-30 12:18)