benschwarz / developers.whatwg.org

Used to create the contents of developers.whatwg.org
http://developers.whatwg.org/
198 stars 39 forks source link

Drag and Drop #114

Closed micage closed 7 years ago

micage commented 7 years ago

Your Drag and Drop example is not working.

The drop event allows the actual drop to be performed. This event needs to be canceled, so that the dropEffect attribute's value can be used by the source

This is not true.

The drop event is a consequence of a successful drop. The correct way to make a drop operation possible is to handle the dragover event. Only after a successful drop you can react to the drop event via ondrop handler.

<ol ondragover="handleDragOver(event)" ondrop="handleDrop(event)"></ol>

Then inside the script:

function handleDragOver(event) {
    if (yourOkCondition) {
        event.preventDefault(); // this triggers the drop event (!)
    }
}

function handleDrop(event) {
    var data = event.dataTransfer.getData(internalDNDType);
    console.log('dropped: ' + data);
    event.preventDefault(); // to prevent the browsers default behavior
}

This allows the drop and further creates the drop event. Without calling preventDefault inside handleDragOver there is no drop event at all. So handleDrop would not get called. This is in fact the way to define conditions to permit/allow drop operations. Just don't call preventDefault for drops you want to permit and call it for drops you want to allow.

Note: call event.stopPropation if you want to prevent events to bubble up the DOM tree. E.g. helpful when implementing drag and drop for tree-like structures (cascaded lists).

Some information in the article seem to be misleading or just incorrect. I think it needs a complete revision and do not forget to test your samples. Sadly I have no time to give you a complete report, sorry for that. I would start with a minimal working sample then continue with a short trip into DOM structure (containment hierarchy) and event propagation and close with custom drag indicators. Without that knowledge you will shortly find yourself in a world of pain in an attempt to make more complex operations work.


Minor Note: It's quite difficult to drop into an element with height zero. Give the drop target a min-height!

CaseyLeask commented 7 years ago

@micage I found the section you're talking about: https://developers.whatwg.org/dnd.html#dnd It comes from https://html.spec.whatwg.org/multipage/interaction.html#dnd. The developers.whatwg.org site is just a wrapper over the information presented there. I'd recommend heading to https://github.com/whatwg/html to discuss this.