Skip to content
Advertisement

How to prevent dragging of an element inside a ?

I am building an editor that uses an SVG element as the canvas. It provides custom drag-and-drop behavior to drag elements inside the svg around. However, when I try to drag an <image> tag, the native browser drag behavior where you’re dragging a “ghost” of the image kicks in. How do I stop it?

I tried setting user-select: none in CSS, which does prevent selecting text but not dragging the image. I tried setting the HTML draggable="false" property, which has no effect in SVG. I even tried to cancel the ondragstart event, which doesn’t seem to fire at all.

<svg>
  <image draggable="false" style="user-select: none;" ondragstart="return false" href="https://wehles.files.wordpress.com/2020/05/opamp.png?w=147"></image>
</svg>

JSfiddle: https://jsfiddle.net/1dnfpray/

How do I prevent the image from being dragged, so that I can implement my own drag behavior?

Advertisement

Answer

If you cancel the mousedown event, the drag is prevented:

<svg>
  <image draggable="false" style="user-select: none;" onmousedown="return false" href="https://wehles.files.wordpress.com/2020/05/opamp.png?w=147"></image>
</svg>

You’ll need to handle that event anyway, if you want to implement your own dragging behaviour.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement