HTML5 - Drag & Drop
By @islamzatary
By @islamzatary
For years, we've been using libraries like JQuery and Dojo to simplify complex UI elements like animations, rounded corners, and drag and drop.
DnD: Is a first class citizen in HTML5!
New attribute called draggable.
Set the draggable=true attribute on the element you want to make moveable.
Just about anything can be drag-enabled, including images, links, files, or other DOM nodes.
most browsers, text selections, img elements, and anchor elements with an href attribute are draggable by default.
which can be dropped in the address bar, a element, or even the desktop.
If you want to enable other types of content to be draggable, you'll need to leverage the HTML5 DnD APIs.
dragstart
drag
dragenter
dragleave
dragover
drop
dragend
The target is the drop zone (or set of drop zones) that accepts the data the user is trying to drop. Keep in mind that not all elements can be targets (e.g. images).
1. Starting a Drag (dragstart & dragend).
2. dragenter, dragover, and dragleave
return false vs e.preventDefault()
preventDefault : guaranteeing that the anchor's default behavior will not fire, incase we dragging something like a link
3. Completing a Drag
To process the actual drop, add an event listener for the drop and dragendevents.
It holds the piece of data sent in a drag action.
dataTransfer is set in the dragstart event and read/handled in the drop event. Calling e.dataTransfer.setData(format, data) will set the object's content to the mimetype and data payload passed as arguments.
getData(format) for fetching the drag data by mimetype.
1. dataTransfer.effectAllowed
Restricts what 'type of drag' the user can perform on the element, to initialize the dropEffect during the dragenter and dragover events.
values: none, copy, copyLink, copyMove, link, linkMove, move, all, and uninitialized.
2. dataTransfer.dropEffect
Controls the feedback that the user is given during the dragenter and dragover events.
When the user hovers over a target element, the browser's cursor will indicate what type of operation is going to take place (e.g. a copy, a move, etc.)
values: none, copy, link, move.
3. e.dataTransfer.setDragImage(imgElement, x, y)
by this property, you can optionally set a drag icon.
Dragging Files
Instead of using dataTransfer.getData() to access the files, their data will be contained in the dataTransfer.files property
HTML5's DnD model is complicated compared to other solutions like JQuery UI
by @islamzatary