Monthly Archives: February 2013

HTML5 Tips and Tricks: Drag and Drop

A useful feature in HTML5 is native browser support for drag and drop (DnD). HMTL5 drag and drop supports the designation of any element as draggable, as well as setting any element as a drop target, specifying the behavior for each step along the way. Additionally, drag and drop across browser windows and even to and from the desktop is supported. Drag and Drop is natively supported by all major browsers, and partially supported as far back as IE5.

By default, only images and hyperlinks are draggable. To allow other elements to be dragged, simply declare an attribute draggable and set to true. This will allow the user to drag the element and causes the drag events (dragStart, dragEnd, and drag) and drop events (dragEnter, dragOver, dragLeave, and drop) to fire. Elements can be set to copy their content, move completely, or simply link back to the source element. An important note is that elements are not eligible drop targets by default, and so the default behavior of the dragOver and dragEnter events must be cancelled to allow dropping. A simple example of HTML5 drag and drop is given in Figure 1.

<div draggable="true" id="dragBox">
<div id="dropBox"></div>
<script type="text/javascript">// <![CDATA[
var drag = document.querySelector("#dragBox");

addEvent(drag, "dragstart", function (e) {
    // required for non-text, non-image objects otherwise doesn't work
    e.dataTransfer.setData("Text", "data value as text");  
});

var drop = document.querySelector("#dropBox");
addEvent(drop, "dragover", cancel);   // Tells the browser that we *can* drop on this target
addEvent(drop, "dragenter", cancel);  // Tells the browser that we *can* drop on this target

addEvent(drop, "drop", function (e) {
    if (e.preventDefault)  
        e.preventDefault();  // stops the browser from redirecting off to the text.
    this.innerHTML += "

"
+ e.dataTransfer.getData("Text") + "

"
;
    return false;
});

function cancel(e) {
    if (e.preventDefault)  
        e.preventDefault();
    return false;
}
// ]]></script>

Figure 1 Simple example of drag and drop.

Some critics call the system cumbersome because of the number of event and event handlers involved, especially since the API is based on an older IE5 implementation. However, native cross browser support of drag and drop without relying on external libraries is a useful feature that developers should be aware of, especially with the inclusion of support for file drag and drop to and from the desktop.

Further Reading

  1. http://www.html5rocks.com/en/tutorials/dnd/basics/
  2. http://www.quirksmode.org/blog/archives/2009/09/the_html5_drag.html
  3. http://html5doctor.com/native-drag-and-drop/
  4. http://dev.opera.com/articles/view/drag-and-drop/
  5. http://www.w3schools.com/html/html5_draganddrop.asp

HTML5 Tips and Tricks: Web Storage

HTML5 is the new web standard and features of it are increasingly being supported by all the major browsers.  A key feature of HTML5 is the ability to store data on the client.  This allows a website or app to be used offline and upload information when a connection is next available, for user preference data to remain client-side, as well to reduce bandwidth required to use the site by implementing client-side caching.  This Web Storage feature is available across all modern browsers, including IE 8+.

HTML5 Web Storage provides a localStorage and sessionStorage object accessible via javascript.  These objects use a simple key-value pairing to store string-based data. The amount of data allocated per site varies by browser but ranges from 5 to 10 MB per domain.  The localStorage object acts as a persistent data storage that retains data after the window or browser is closed. Data stored in the sessionStorage does not persist after the window has been closed and is compartmentalized from other windows – otherwise it functions the same as localStorage.

sessionStorage.setItem("key", "value");
var value = sessionStorage.getItem("key");

localStorage.setItem("key", "myValue");
localStorage.getItem("key");    // returns "myValue"
localStorage.length;            // is equal to 1 in this case
localStorage.key(0);            // gets value by index
localStorage.removeItem("key"); // removes the key-value pair from
                                // the storage dictionary
localStorage.clear();           // removes all key-value pairs

window.addEventListener("storage", function(event) {
// event.key, event.oldValue, event.newValue
});

localStorage.setItem("user", JSON.stringify( { user: "John", id: 1 } );
var user = JSON.parse(localStorage.getItem("user");

Figure 1 Simple examples of using HTML5 Web Storage objects.

Figure 1 gives some examples of the manipulations you can make on the data in the Web Storage objects.  An important thing to remember is that only string values can be stored, so more complex objects can be stored using the JSON.stringify() function and retrieved using the JSON.parse() function.  Additionally, event listeners can be attached to the storage objects allowing multiple windows using the localStorage object to stay in sync and prevent race conditions.

localStorage is a good solution replacing cooking, retaining data such as user preferences that remain client-side, keeping data past a page refresh, and allowing apps to be used offline.  sessionStorage is a good solution for things such as shopping carts, or sensitive data that should be disposed of after the session is complete.  With the widespread adoption across all browsers and a simple API, Web Storage is a valuable tool to be used in web site or app development.

Additional Resources

  1. http://www.w3schools.com/html/html5_webstorage.asp
  2. http://dev.w3.org/html5/webstorage/
  3. http://sixrevisions.com/html/introduction-web-storage/
  4. http://www.html5rocks.com/en/tutorials/offline/storage/
  5. http://paperkilledrock.com/2010/05/html5-localstorage-part-one/