This content originally appeared on DEV Community and was authored by Anurag Gharat
Hey there! Today I will show you a simple implementation of HTML Drag and Drop API.
HTML allows you to drag and drop every element in the browser. Using a mouse you can grab a draggable element and place it inside a droppable element!
Below is a simple implementation!
Lets go through the code, one part at a time!
HTML code:
Here we are having two sections. One drag zone and one drop zone.
Div is the element which we wish to drag and drop. We then set the draggable attribute of the Div tag as "true".
"ondragstart" event runs when you grab the draggable item. Further more, in drop section, we have two events. “ondragover” starts firing when you move the dragged item over the drop zone and “ondrop” fires when you drop the item by releasing the mouse button.
We even have more events if you wish to apply more logic to your component. In our current implementation this 3 events are enough.
CSS code:
Basic CSS code where I am centering the sections and div so we can easily understand the drag and drop layout.
JavaScript code:
So using JS we add the draggable element using its ID to the dataTransfer object. Then on reaching the drop zone we append the draggable element to the drop zone section.
The explanation of each step in the functions has been added in the comments.
For further reference you can read this MDN documentation for Drag and Drop API. https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API
Hope this article helped you in knowing Drag and Drop feature in HTML. I regularly post tweets regarding HTML, CSS, JS, React, Cloud and Blockchain on my twitter. Do follow me if you love such topics. Thanks!
This content originally appeared on DEV Community and was authored by Anurag Gharat
Anurag Gharat | Sciencx (2022-01-22T11:39:04+00:00) HTML Drag and Drop API. Retrieved from https://www.scien.cx/2022/01/22/html-drag-and-drop-api-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.