How to Drag & Drop HTML Elements and Files using Javascript
--
Are you trying to add the drag & drop functionality to your website, but you don’t know exactly how to do it? Well, worry not, this story explains all you need to know to get you started.
To be able to drag & drop HTML elements or just drop files in your website, the following steps will be your best friend. Well, until you add the feature to your website. Then, it will be bye bye friendship.
Just note that the steps are based on the HTML drag & drop API explained in MDN web docs.
1) Detect the Drag & Drop Feature Support in Your Browser
Before using the HTML drag & drop API, add feature detection code to ensure browser support.
The following code is the feature detection code for the HTML drag & drop API from Modernizr.
2) Decide which HTML Element is going to be dragged
In order to make a chosen HTML element be a draggable element, the element must have the following:
- The draggable attribute, which determines whether the element can be dragged or not.
- The ondragstart event handler, which executes when the drag event starts.
The following is an example of identifying a paragraph element <p> as a draggable element.