shapeshed

Ruby & JavaScript Hacker

Drag and Drop in HTML5

Not interested in the explanation? Go straight to the demo page or download the source code from Github

Browser based computing

The more I explore HTML5 the more I feel that a browser based Operating System is coming sooner rather than later. Drag and drop is another important feature that will make this happen. Granted the spec is still work in progress but in Firefox 3.5 there is a workable API that developers can use and build UIs with. For this simple example I’m proposing that a user will want to drag a file to the trash. Later on I might take this further and implement a light client-side database using storage, but for now you can only drag a file to the trash. This example only works in Firefox 3.5

Creating the drag

To make an element draggable you can do this.

1
<li draggable="true" id="file1" ondragstart="drag(this, event)"><span>filename.txt</span></li>

To create a draggable area you can do this.

1
<div id="trash" ondrop="drop(this, event)" ondragenter="return false" ondragover="return false"></div>

Then you just need a bit of JavaScript to hook it all up

1
2
3
4
5
6
7
8
function drag(target, e) {
    e.dataTransfer.setData('Text', target.id);
}
function drop(target, e) {
    var id = e.dataTransfer.getData('Text');
    target.appendChild(document.getElementById(id));
    e.preventDefault();
}

A dose of CSS3

The example also features CSS3 (border-radius, box-shadow, text-shadow, rgba) and @font-face embdding with the excellent open source Junction font.

Reservations

Because I’m a standards zealot I’m not sure about the inline javascript proposed in the spec. There is also a big issue about what happens for users who cannot use the mouse. These are all expected issues though that I hope will be ironed out. Great progress has been made already.

Further reading