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

[wpdm_file id=141]DEMO

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:

<div class="notes important-notes">
        <h1>Important Notes</h1>
        <div class="note">
            Turn on my PC.
        </div>
        <div class="note">Get rid of referral spam</div>
        <div class="note">Responsify a website</div>
    </div>
    <div class="useless-notes notes">
        <h1>Useless Notes</h1>
        <div class="note">
            Test the project on my mobile.
        </div>
        <div class="note">
            Eat a pizza
        </div>
        <div class="note">
            Waste some time
        </div>
    </div>

We have added some basic CSS:

 .note {
            float: left;
            margin: 5px;
            cursor: move;
            background-color: yellow;
            border: 1px solid black;
            width: 100px;
            height: 100px;
            overflow: auto;
            padding: 5px;
        }

        .important-notes .note {
            background-color: lime;
        }

        .useless-notes .note {
            background-color: yellow;
        }

        .notes h1 {
            color: #fff;
        }
        .notes {
            float: left;
            border: 2px solid crimson;
            background-color: #000;
            width: 48%;
            margin: 0.5%;
        }

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.

window.onload = function() {
    var notes =  document.getElementsByClassName("note");
    var noteTypes =  document.getElementsByClassName("notes");

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.

for (var i = 0,n = notes.length;i < n;i++) {
        notes[i].className += " note-" + i;
        notes[i].setAttribute("draggable", true);
        notes[i].addEventListener("dragstart",function(evt) {
            evt.dataTransfer.setData("text", evt.target.className);
        })
    }

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.

for (var j = 0,nt = noteTypes.length;j<nt;j++) {
        noteTypes[j].addEventListener("dragover", function(evt) {
            evt.preventDefault();
        })
        onDrop(j);
        function onDrop(j) {
            noteTypes[j].addEventListener('drop',function(evt) {
                evt.preventDefault();
                var draggedData = evt.dataTransfer.getData('text');
                noteTypes[j].appendChild(document.getElementsByClassName(draggedData)[0]);
            })
        }

    }

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:

Leave a Reply

Your email address will not be published. Required fields are marked *