Javascript – How to prevent drag on a child, but allow drag on the parent

drag and drophtmljavascript

I have a div which the user can drag, inside that div is a span with some text which I want to allow the user to select (thus they cannot drag it). How do I allow the div to drag, but not the span?

The dragstart event is on the div.

I'm probably overlooking something simple. I tried draggable=true on the div, and draggable=false on the span. That didn't work. Tried returning false on dragstart, that didn't work either.

dragstart (roughly):

var jTarget = $(e.target);
if ((jTarget.is('div.header') || (jTarget.parents('div.header')) 
       && !jTarget.is('a, input, span'))) 
{
   e.originalEvent.dataTransfer.setData("Text", "test");
}
else
{
   if(e.preventBubble)
      e.preventBubble();
   if(e.stopPropagation)
      e.stopPropagation();
   return false;//???
}

The if else portion works as I expect, but I cannot get anything to stop the drag and allow the select.

Best Answer

If you want to truly cancel out the drag and make it unnoticeable to parent drag handlers, you need to both preventDefault and stopPropagation:

<div draggable="true" ondragstart="console.log('dragging')">
    <span>Drag me! :)</span>
    <input draggable="true"
           ondragstart="event.preventDefault();
                        event.stopPropagation();"
           value="Don't drag me :(">
</div>

Without the stopPropagation, the parent ondragstart will still be called even if the default behavior will be prevented (event.defaultPrevented == true). If you have code in that handler that doesn't handle this case, you may see subtle bugs.

You can of course put the JavaScript above inside element.addEventListener('dragstart', ...) too.