#30 HTML Drag and Drop API

HTML Drag and Drop API allows the user to drag and drop element to one location to another. Interesting?

While dragging element a translucent representation of the element is follow the mouse pointer.

A number of events are fired during the different states of the drag and drop operation. mousemove not fired.

Various browsers like Chrome, Firefox, Safari etc supports drag and drop feature.

Following drag and drop events are useful to build this feature

EventDescription
ondragstartWhen a user starts dragging then this event gets fired
ondragenterWhen a draggable element is moved into the target element then this event gets fired
ondragoverWhen a user drags an element over the drop listener or target element then this event gets fired
ondragleaveWhen the user drags an element out of the drop listener then this event gets fired
ondragWhen the user drags an element this event gets fired
ondropWhen the user drops an element over the target element, this event is fired
ondragendWhen the drag action is complete this event gets fired

example

See the Pen drag and drop by Arpit (@soniarpit) on CodePen.

Here you can see <img> element set by draggable="true" attribute. You can set this any element.

When we try to drag an image into the box, ondragstart event fires. This event handled by user-defined function begin_drag using javascript.

Inside the begin_drag function we invoke a method named dataTransfer.setData. This DataTransfer object holds data about the drag and drop operation. Using setData method, the specified data is added.

For rectangle box, the ondrop event is triggered. This event handled using the function end_drop. Inside this method, the data hold during drag operation is acquired using getData method of dataTransfer object.

During the drag operation and before drop, the event ondragover is raised. This event is simply handled by using e.preventDefault() method. This method prevents the browser default handling of the data.

Must try

Previous: #29 HTML Geolocation API

Next: #31 HTML Web Storage API