HTML5 Drag and Drop interfaces enable applications to use drag and drop (using mouse) features in web browser. It involves dragging an element and dropping it to a drop zone (another element which allows dropping). This feature is mostly supported by Desktop browsers.
HTML Drag and drop flow
A basic drag and drop implementation involves the following flow:
- Make the element to be dragged draggable using attribute draggable as shown below:
<p draggable="true">drag me</p>
- Implement
ondragstart
event handler on the element to be dragged. This handler can copy the Id of the element which initiated the drag.
<p id="src" draggable="true" ondragstart="dragStartHandler(event)">Drag me</p> <script> function dragStartHandler(e) { e.dataTransfer.setData("my_element_id", e.target.id); } </script>
- Implement
ondragover
event handler on dropzone element. This will make drop effect when dragged element is in dropzone element. We can also customize the effect usingevent.dataTransfer.dropEffect
. Note that we also need to callevent.preventDefault()
as default event handler does not allow dragging over an element.
<div class="dropbox" ondragover="dragOverHandler(event)">Or Drop here</div> <script> function dragOverHandler(e) { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; } </script>
- Implement
ondrop
event handler on dropzone element. This handler will move the dragged element.
<div class="dropbox" ondragover="dragOverHandler(event)" ondrop="dropHandler(event)"">Drop here</div> <script> function dropHandler(e) { var elementId = e.dataTransfer.getData("my_element_id"); e.target.appendChild(document.getElementById(elementId)); } </script>
Example – drag and drop – move element to dropzone
<style type="text/css"> .dropbox { width:100px; height:60px; margin:2px; background-color:lightgray; } </style> <div class="dropbox" ondragover="dragOverHandler(event)" ondrop="dropHandler(event)"">Drop here</div> <div class="dropbox" ondragover="dragOverHandler(event)" ondrop="dropHandler(event)" >Or drop here</div> <p id="src" draggable="true" ondragstart="dragStartHandler(event)">Drag me</p> <script> function dragStartHandler(e) { e.dataTransfer.setData("my_element_id", e.target.id); } function dragOverHandler(e) { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; } function dropHandler(e) { var elementId = e.dataTransfer.getData("my_element_id"); e.target.appendChild(document.getElementById(elementId)); } </script>
Specification and Browser compatibility
Specification | Status | Categories |
---|---|---|
Drag and Drop | WHATWG Living Standard | HTML5 |
Chrome | Firefox | IE | Edge | Safari | Opera |
---|---|---|---|---|---|
Yes 4+ | Yes 3.5+ | Partial 5.5+ | Partial 12+ | Yes 3.1+ | Yes 12+ |
Android Chrome | Android Firefox | iOS Safari | IE Mobile | Opera Mobile |
---|---|---|---|---|
No | No | No | Yes 10+ | No |
source: caniuse.com