Read more

Disable built-in dragging of text and images

Dominic Beger
September 30, 2021Software engineer at makandra GmbH

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.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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.

Posted by Dominic Beger to makandra dev (2021-09-30 14:18)