How to Prevent Drag on a Child, But Allow Drag on the Parent

Prevent child element from being dragged when parent is draggable

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

How to avoid a child div in react invoking a parent's `onDragLeave` event

The simplest way to do this would be to set pointerEvents: "none" in the style prop of the child <div>, so that all pointer-related events on this div are ignored. That would introduce some limitations, though - like you couldn't bind click events to the child div.

If this doesn't fit within the constraints of your application, you can modify your onDragLeave handler to inspect the relatedTarget of the event (see docs). If the drag is leaving the parent <div> but entering a child of the parent, then the relatedTarget (i.e. child div), will be contained (see docs) by the currentTarget (i.e. the parent <div>)

Here's the code that should work:

const onDragLeave = (event) => {
preventDefaults(event);
// This condition will be true when the drag leaves the parent for a child,
// but false when the drag leaves the parent for somewhere else.
if (event.currentTarget.contains(event.relatedTarget)) return;
console.log("LEAVE");
setDragOver(false);
};

See this codesandbox.

Drag and Drop 'dragover' event to catch the draggable parent and not the child when I drag over an item? Simple Example Inside

We can go up the hierarchy until we are satisfied with the results:

document.addEventListener('dragover', function (event) { allowDrop(event); }, true);
function allowDrop(ev)
{ el = ev.target;
while ((el.tagName !== "LI") && (el.tagName !== "BODY")) el = el.parentNode;
document.getElementById("result").innerHTML = el.innerHTML;
}


Fiddle: https://jsfiddle.net/Lnrt2zx1/



Related Topics



Leave a reply



Submit