javascripthtmlreactjseventsdrag

Prevent child element from being dragged when parent is draggable


I have the following HTML (react) setup:

<div 
    onDragStart={
    (e) => { this.bound_handleDragStart.call(this, e) }}        
    draggable="true"
>
   <div>Stuff here</div>
   <div><input .../></div>
</div>

This setup makes the whole outer div draggable.

However, if the drag starts on the input, I want it to be cancelled.

I have tried adding onDragStart to the input, adding an eventListener to the input and returning false, disabling propogation on the handle drag start, and many other things, but none of them work.

As a not, when event.target returns the outer div, so I cannot see a way to work out which child started the drag.

I am sure this can be done and cannot be too difficult?

I have thought about moving the drag to all the inner divs, but I am not sure if this will solve my problem, or create a whole new set of problems, plus I feel like this is not the right way to go


Solution

  • Believe it or not, but you actually need to set draggable="true" on the input and then add an event handler for dragstart on the input where you run event.preventDefault():

    <div 
        onDragStart={
        (e) => { this.bound_handleDragStart.call(this, e) }}        
        draggable="true"
    >
       <div>Stuff here</div>
       <div><input draggable="true" onDragStart={
         (e) => e.preventDefault()
       }/></div>
    </div>
    

    This will prevent the actual dragging, but the dragstart event on the parent will still be triggered since it bubbles up. If you want to prevent that too you need to also call event.stopPropagation().