Using HTML5 Drag and Drop

Kira Green
3 min readApr 11, 2019

--

In this tutorial I am going to step through how to make a simple drag and drop functionality using HTML5 drag and drop attributes. Any HTML elements can be made draggable.

We start with the basic layout with sky, ground split into two areas: grass and pond, and some animals. I will show you how to make it possible to drag and drop the animals between the grass and the pond. At the moment the code is as follows:

Code with elements before adding drag and drop

The first step is to make the ducks and frog draggable, this is done by adding:

draggable=”true” to the HTML element, as in the code snippet below:

draggable=”true” added to HTML tag

Step 2 is to specify what happens when we start to drag the element, using the ondragstart attribute which will call a function. This function will set what data it is that needs to be transported by the dragging action. In this case, the function is called ‘drag’. As the image is linked to using a URL, we can set the data type to ‘text’ so that the URL of the image is transported, and we need to transport the id of the element too. So now our HTML looks like this:

HTML for draggable element

And our JavaScript function drag is:

drag function

If we apply the same attributes to all the animals, we can now drag the animals but cannot drop them anywhere as the default for all elements is to prevent anything from being dropped. So, firstly we need to prevent this default by using the HTML attribute ondragover which will call a function to do that. So in the HTML for the pond and the grass we will put:

HTML atttribute

And in the JavaScript:

function that will allow us to drop onto the pond

Then we will need to get the data that was set when the drag started (in the ondragstart function). In the HTML we will use the ondrop attribute which will call a function that gets the transferred image and appends it to the element that it is being dropped into (here we are making both the grass area and the pond area droppable so put it on both).

Now the HTML is:

HTML for droppable element

and the JavaScript function:

function for the droppable area

Now you should be able to drag the animals to the pond and back to the grass. You can find the full code in my GitHub .

I hope you found this useful, get in touch if you have any questions.

--

--

Kira Green

I left a career in teaching in December 2018 to pursue a new career in tech. In Feb 2019 I joined the School of Code bootcamp .