HTML5 – code example of drag and drop on a web page


ibm.com/developerworks

I have recently attended a couple of analysts meetings where the subject of HTML5 was a recurring theme.  With my curiosity peeked, I decided to explore what HTML5 has to offer today.  Of particular interest is the drag and drop (d&d) API… as this has always been the holy grail of early HTML practitioners.  What I discovered was very cool… as d&d is now a simple matter of implementing a few effortless method calls.

For my example of d&d, I created a simple network configuration demo that illustrates an administrator UI to provision resources.  You can drag the example resources between zones, add resources to a zone, or simply remove a resource that is no longer required.  I kept my example basic for educational purposes, but as you can see, one could develop a full blown network administration tool using drag & drop as a central element of the user interface.

Here is my example, give it a test drive (requires Firefox 3.5 or greater):

 https://www.ibm.com/developerworks/mydeveloperworks/blogs/bobleah/resource/d_and_d.html?lang=en 

The key methods to implement d&d are basic and easily implemented as follows:  

  1. function dragIt(target, e) {
  2.     e.dataTransfer.setData(SpanImg’, target.id);
  3. }

  4. function dropIt(target, e) {
  5.     var id = e.dataTransfer.getData(SpanImg’);
  6.     target.appendChild(document.getElementById(id));
  7.     e.preventDefault();
  8. }

 
I used table elements to provide both layout structure and as a target for 
ondrop events:
 

  1. <td align=center” width=100″ id=blue” ondrop=dropIt(this, event) ondragenter=return false ondragover=return false>   ….  </td>

 
I chose the span element (wrapping an image) as my 
draggable object:
 

  1. <span draggable=true” id=t_1″ ondragstart=dragIt(this, event)><img src=https://www.ibm.com/developerworks/mydeveloperworks/blogs/bobleah/resource/tower.jpg></span>

 
  
You can download the complete HTML of my d&d example by
 clicking here.  

 
Based on my initial experience, HTML5 is going to offer some exciting possibilities.  Today, the API set is limited and only available within certain browsers.  For example, to run my app requires Firefox 3.5 or greater.  I will continue to explore  what’s available today, and create a few more examples… stay tuned!

Anuncios

Autor: Gabriel Catalano - human being | (#IN).perfección®

Lo importante es el camino que recorremos, las metas son apenas el resultado de ese recorrido. Llegar generalmente significa, volver a empezar!