July 10, 2015 3:15 am

Useful HTML5 Features, Part 2

HTML 5 Drag and Drop API the days when one relied heavily on libraries and third-party plugins to achieve drag and drop functionality are coming to an end with the Drag and Drop API

Useful HTML5 Features

Browser support

The Drag and Drop API is not supported very well with 60.24% global support.

The following browsers support it:

  1. IE8+ have partial support
  2. Firefox 31+
  3. Chrome 31+
  4. Safari 7+
  5. Opera 29+
  6. To exemplify the drag and drop API we will be creating this:

It is a simple notes web app. We will just create the functionality to move your notes from the type Important Notes to the type Useless Notes. In fact, our code can be modified to include new notes and new note types with ease and the drag and drop functionality will handle them properly.

The HTML that we need is:

We have added some basic CSS:

As you can see from the CSS, when you drag the notes to a different section they will change colors immediately as we have added selectors that change the color of the note depending on which section it is located in. You can also see that we have set the cursor to move so our users would be aware they can drag the note.

At first, we set up our notes and note sections in variables on DOM load.

Then we loop for each note and add a unique class (we could have used an ID) to it. You will see why in a bit.

We add to the note an attribute of draggable so our notes can be draggable and so we do not have to manually add it when adding each note.

Then, we add an event listener that will catch the start of a drag and save its class name as data in transfer. Because the class names would be unique we would later listen for drop events and append the element with that class name to the container where the note was dropped.

Finally, we loop over each note section/type and add a drop listener to it. We get the data that we saved as data in transfer (the class name of the dragged element) and use it to find the element withdocument.getElementsByClassName and move it to note section where we have dropped the note in.

That’s it! Nothing really complicated. If you are working on a project whose user base have the latest technologies, then you can certainly use it but you should consider adding some kind of a fallback for now.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories: