I’m trying to use the HTML5 draggable API (though I realize it has its problems). So far, the only showstopper I’ve encountered is that I can’t figure out a way to determine what is being dragged when a dragover or dragenter event fires:
el.addEventListener('dragenter', function(e) {
// what is the draggable element?
});
I realize I could assume that it’s the last element to fire a dragstart event, but… multitouch. I’ve also tried using e.dataTransfer.setData from the dragstart to attach a unique identifier, but apparently that data is inaccessible from dragover/dragenter:
This data will only be available once a drop occurs during the drop event.
So, any ideas?
Update: As of this writing, HTML5 drag-and-drop does not appear to be implemented in any major mobile browser, making the point about multitouch moot in practice. However, I’d like a solution that’s guaranteed to work across any implementation of the spec, which does not appear to preclude multiple elements from being dragged simultaneously.
I’ve posted a working solution below, but it’s an ugly hack. I’m still hoping for a better answer.
The short answer to my question turns out to be: No. The WHATWG spec doesn’t provide a reference to the element being dragged (called the “source node” in the spec) in the
dragenter,dragover, ordragleaveevents.Why not? Two reasons:
First, as Jeffery points out in his comment, the WHATWG spec is based on IE5+’s implementation of drag-and-drop, which predated multi-touch devices. (As of this writing, no major multi-touch browser implements HTML drag-and-drop.) In a “single-touch” context, it’s easy to store a global reference to the current dragged element on
dragstart.Second, HTML drag-and-drop allows you to drag elements across multiple documents. This is awesome, but it also means that providing a reference to the element being dragged in every
dragenter,dragover, ordragleaveevent wouldn’t make sense; you can’t reference an element in a different document. It’s a strength of the API that those events work the same way whether the drag originated in the same document or a different one.But the inability to provide serialized information to all drag events, except through
dataTransfer.types(as described in my working solution answer), is a glaring omission in the API. I’ve submitted a proposal for public data in drag events to the WHATWG, and I hope you’ll express your support.