Prevent child element from being dragged when parent is draggable
Asked Answered
B

2

7

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

Bandstand answered 18/5, 2017 at 13:9 Comment(3)
Dragging is going to drag the children. How could it not? To check the child dragged from, isn't that what target gives you?Abusive
But I want the drag event cancelled if it started over the childBandstand
Normally, cancelling the default and preventing the propagation should do the trick.Fabria
S
23

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().

Swarth answered 18/5, 2017 at 13:39 Comment(1)
I thought stopPropagation would do the trick, but thanks this helped.Cloninger
P
0

to stop propagation at child components use onKeyDown and onPointerDown events.

    <div 
       onDragStart={
       (e) => { this.bound_handleDragStart.call(this, e) }}        
       draggable="true"
    >
       <div>Stuff here</div>
       <div>
            <input  
               onKeyDown={(e)=>{
                 e.stopPropagation();
               }}
               onPointerDown={(e)=>{
                  e.stopPropagation();
               }}
            />
       </div>
    </div>
Priscilapriscilla answered 15/8 at 7:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.