Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 22, 2022 11:39 am GMT

HTML Drag and Drop API

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!

HTML Drag and Drop API

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.

HTML code

CSS code:
Basic CSS code where I am centering the sections and div so we can easily understand the drag and drop layout.

CSS code

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.

JS code

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!


Original Link: https://dev.to/anuraggharat/html-drag-and-drop-api-5gd3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To