Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Cross Browser HTML5 Drag and Drop

  zoltan        2011-09-20 13:42:45       501,013        0    

HTML5 Drag and Drop has been talked about a lot lately, but it’s hard to find really useful information about implementing it across multiple browsers.MozillaApple and Microsoft all have pages describing how to use it, but their examples seem to work only in their particular browser (Apple’s example doesn’t even work in their own! Updated, Jan. 11, 2009: Although I have not been able to get this example working on Safari 2.0.4 and 3.1.2 for OS X and 4.0.4 for Windows, I have received word that it works on Safari 4.0.4 on OS X). Remy Sharp’s great article Native Drag and Drop was a good place for me to start — however, the examples didn’t work in Internet Explorer. I also thoroughly enjoyed JavaScript guru Peter-Paul Koch’s humorous and lengthy rant about cross-browser drag and drop headaches where he uses creative and colourful language to describe what he thought of the standard, the browser manufacturers, and the WHAT-WG.

When normal people see the author of the Compatibility Master Tables respond negatively to a web technology, they would probably assume it would be a good sign to stay away from it.

However, I am not normal. With a name like Zoltan, how could I possibly be normal? (and yes, it is my real name).

So, I decided to find out for myself how bad HTML5 Drag and Drop really is. Almost immediately, I understood Koch’s reaction – the browser vendors have not implemented all the same features, and there are even a few quirks in how the features that areimplemented work. However, after doing a lot of research, I found a common denominator that works well, with the help of a small bit of JavaScript that smooths out the edges. Despite the implementation flaws, Future-proof HTML5 Drag and Drop is not too hard for developers to use in their own applications. This article will explain how to do this step by step with many examples along the way. By the time you are done, you will be able to write useful drag and drop scripts of your own like in this example:

See an example of HTML5 Drag and Drop in action.

Advantages Over Existing Drag and Drop Implementations

Koch mentioned in his blog post that “Web developers MUST NOT (in the sense of RFC 2119) use HTML 5 drag and drop. They should use old-school scripts instead”. I would argue that developers should use HTML5 drag and drop for the following reasons:

  • JavaScript Framework Independent: Most other (but not all) drag and drop implementations are tied into 3rd party frameworks like DojoPrototype or jQuery.
  • Built-in Browser Support: HTML5 Drag and Drop is supported in Firefox 3.5+, Chrome 3.0+, Safari 3.0+ and Internet Explorer 5.0 (Note: that is not a typo — HTML5 Drag and Drop is based on work done by Microsoft in 1999). Because it is part of HTML5, I assume Opera support should be inevitable.
  • Integration With Other Web Applications: the HTML5 specification will allow developers to produce drag and drop scripts that work across frames, and across browser windows.
  • Integration With Non-Web Applications: the HTML5 specification also allows users to drag and drop data to and from non-web applications

The Basics of Drag and Drop, Step by Step

In order to save other developers from the headaches I got deciphering cross browser drag and drop, I present the following guide that shows how to do in five easy steps. Every step will describe a set of related concepts, and will show examples, most of which are built on code from previous steps. At the end of each step, I will discuss any issues and interesting bits I came across.

Step 1: Defining a Draggable Object

First you need to define the HTML nodes that you want to drag. Firefox requires that these nodes have their draggableattribute set to "true", Internet Explorer requires that the node must be an <a> tag with (the href attribute set) or an<img> tag.

<a href="#" id="toDrag" draggable="true">This is a draggable item</a>

To show how this works, I have written a very simple page with a the above markup in the <body>:

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta name="generator" content="HTML Tidy, see www.w3.org">

        <title>Test #1: A Simple Draggable Object</title>

      <script type="text/javascript" src="../../shared/js/EventHelpers.js">
      </script>
      <script type="text/javascript" src="../../shared/js/DragDropHelpers.js">
      </script>

        <link rel="stylesheet" type="text/css" media="screen" href=
        "css/test1.css">
    </head>

    <body>
        <h1>Test #1: A Simple Draggable Object</h1>

        <a href="#" id="toDrag" draggable="true">This is a
        draggable item</a>

        <p>Try to drag the red box around. You will see the
        draggable object cloned in every browser except Explorer
        and Chrome.</p>

        <a href=
        "http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/">
        Go back to the User Agent Man HTML5 Drag and Drop
        article</a>
    </body>
</html>

Note that this HTML page has two scripts in the <head>:

  • EventHelpers.js: this script implements cross-browser event handling routines without the need for a JavaScript framework. All the examples in this article use it, but feel free to refactor all the code in this article to use a third party framework like Dojo, jQuery or whatever framework you like.
  • DragDropHelpers.js: among other things that I will get to later, will activate dragging ondraggable="true" objects in Safari and Chrome using a built-in copy of Dean Edwards’ cssQuery. It does this by inserting the following CSS code into the HTML document:
    [draggable=true] {
      -khtml-user-drag: element;
      -webkit-user-drag: element;
      -khtml-user-select: none;
      -webkit-user-select: none;
    }

    The first two rules allow the dragging of the draggable="true" nodes, while the last two prevent the user from selecting the text within the node (which can cause some unexpected behavior in Webkit browsers). The -khtml properties work in older versions of Safari, while -webkit ones work in newer versions. Without these CSS properties, these nodes will not be draggable when using the Safari web browser

See Example #1: a draggable object

A couple of notes:

  1. You’ll notice that when you hover the mouse pointer over the draggable item, it will change to The  "Move" cursor(i.e. I the “move” cursor). This is not the default behavior of the web browser – it is something I added inDragDropHelpers, since I believe that it’s a nice visual cue to show users that an object is draggable (if you don’t want this behavior, it is possible to turn it off in your own scripts by settingDragDropHelpers.showMouseoverCue to false
  2. How draggable objects look in the various browsers varies. Here are screenshots of how it looks in Windows web browsers (Note: although all screenshots were taken using Windows XP, similar results occur when viewing under Windows Vista or Windows 7):
    Firefox (Windows XP)Safari (Windows XP)Explorer & Chrome (Windows XP)
    [Dragging of a link element, Firefox Windows][Dragging of a link element, Safari Windows][Dragging of a link element, Explorer Windows]

    Note the differences between these three browsers:

    • Firefox for Windows shows a cloned version of the draggable object underneath the mouse pointer when the object is being dragged, while Safari displays a grey box with the text “This is a draggable item” written inside. Explorer and Chrome don’t show any effect at all (We will address this issue later).
    • Since we have not established where we are going to drag our object, all Windows browsers will change the mouse pointer cursor to "Not-Allowed" cursor.(a.k.a. the “not-allowed” mouse pointer). This is the expected behavior, and you will see later that it will help the user know where to drop the object.

    On OS X, Firefox and Safari look similar to Firefox for Windows, except that the “not-allowed” mouse-pointer doesn’t show up:

    Firefox (OS X)Safari (OS X)Chrome (OS X)
    [Dragging of a link element, Firefox Windows][Dragging of a link element, Safari OS X]Chrome for Mac

    The Linux browsers don’t have the “not-allowed” mouse cursor either. Also, the cloned version of the draggable object isn’t transparent using the Linux version of Firefox, and Chrome under Linux behaves pretty much the same as on the other platforms (Note: all Linux testing was done using Ubuntu 9.10 using the standard Gnome window manager).

    Firefox (Ubuntu)Chrome (Ubuntu)
    Firefox LinuxChrome Linux

    The fact that Explorer and Chrome don’t have any visual dragging cues bugged me, so I put a “fix” insideDragDropHelpers.js which can be turned on by setting DragDropHelpers.fixVisualCues to true. Let’s look at a slightly refactored version of Example #1 where we insert the following code in the <head>:

    <!DOCTYPE html>
    <html lang="en">
       <head>
          <title>Test #1: A Simple Draggable Object (with visual cues added to Explorer and Chrome)</title>
          <script type="text/javascript" src="../../shared/js/EventHelpers.js"></script>
          <script type="text/javascript" src="../../shared/js/DragDropHelpers.js"></script>
          <script type="text/javascript">
          <!--
          DragDropHelpers.fixVisualCues=true;
          -->
          </script>
    
          <link rel="stylesheet" type="text/css" media="screen" href="css/test1.css" />
    
       </head>
       <body>
    
          <h1>Test #1: A Simple Draggable Object (with visual cues added to Explorer and Chrome)</h1>
    
          <a href="#" id="toDrag" draggable="true">This is a draggable item</a>
    
          <p>Try to drag the red box around.  You will see the draggable object cloned in all browsers.</p>
    
          <a href="http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/">Go back to the User Agent Man HTML5 Drag and Drop article</a>
    
       </body>
    </html>
    

See Example #1a, a draggable object with visual cue fix for Explorer and Chrome

Voila! The visual cue now shows up. I’ll explain how this works at the end of the article.

Step 2: Setting Events on the Draggable Object

Now that you have defined an object as draggable, you should attach some events to it so the browser knows what to do while it is being dragged. There are three events that a draggable object can fire:

Event nameDescription
dragstartFires when the user starts dragging of the object.
dragFires every time the mouse is moved while the object is being dragged.
dragendFires when the user releases the mouse button while dragging an object.

A developer would attach these events the way they would any other JavaScript event – I use EventHelpers.addEvent, but one could use jQuery’s bind() method, prototype’s Event.observe() or whatever you favourite framework provides for event handling. Developers can also use the old school inline events (i.e. <a href="#" id="toDrag" draggable="true" ondragstart="somefunction();">This is a draggable item</a>), but I try to stay away from using those to seperate document structure from behavior.

Let’s take the example in step 1 and change it so we can log when these events happen to the toDrag node:

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Example #2: a draggable object with events attached </title>
      <script type="text/javascript" src="../../shared/js/sprintf.js"></script>
      <script type="text/javascript" src="../../shared/js/EventHelpers.js"></script>
      <script type="text/javascript" src="../../shared/js/DragDropHelpers.js"></script>

      <script type="text/javascript" src="js/02-dragObjectWithEvent.js"></script>

      <link rel="stylesheet" type="text/css" media="screen" href="css/test1.css" />

   </head>
   <body>

      <h1>Example #2: a draggable object with events attached</h1>

      <p>Try to drag the red box around.  This page will tell you if the
      object is currently dragging, and will log all <code>dragstart</code>
      and <code>dragstop</code> events</p>

      <p><strong>Is dragging:</strong> <span id="dragEventNotice">no</span>

      <p id="eventLog"><strong>Event now firing:</strong><br /><span id="eventNotice"></span>

      <a class="goBack" href="http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/">Go back to the User Agent Man HTML5 Drag and Drop article</a></p>

      <a href="#" id="toDrag" draggable="true">This is a draggable item</a>

   </body>
</html>

In the 02-dragObjectWithEvent.js script, the dragEventNotice node will be used to report whether the user is dragging the object around, and the eventNotice will be used to log what events the user has fired:

var dragObject = new function () {
   var me = this;

   var dragNode;
   var eventNoticeNode, dragEventNoticeNode;

   /* runs when the page is loaded */
   me.init = function () {

      if (EventHelpers.hasPageLoadHappened(arguments)) {
         return;
      }   

      /* The node being dragged */
      dragNode=document.getElementById('toDrag');

      /* The nodes that report to the user what is happening to that node*/
      eventNoticeNode = document.getElementById('eventNotice');
      dragEventNoticeNode = document.getElementById('dragEventNotice');

      /* The drag event handlers */
      EventHelpers.addEvent(dragNode, 'dragstart', dragStartEvent);
      EventHelpers.addEvent(dragNode, 'drag', dragEvent);
      EventHelpers.addEvent(dragNode, 'dragend', dragEndEvent);
   }

   /*
    * The dragstart event handler logs to the user when the event started.
    */
   function dragStartEvent(e) {
      eventNoticeNode.innerHTML =
         sprintf("<strong>%s</strong>: Drag Event started.<br />%s",
            new Date(),  eventNoticeNode.innerHTML);
   }

   /*
    * The drag event reports to the user that dragging is on.
    */
   function dragEvent(e) {
      dragEventNoticeNode.innerHTML = "Currently dragging.";
   }

   /*
    * The dragend event logs to the user when the event had finished *and*
    * also reports that dragging has now stopped.
    */
   function dragEndEvent(e) {
      eventNoticeNode.innerHTML =
         sprintf("<strong>%s</strong>: Drag Event stopped.<br />%s",
            new Date(), eventNoticeNode.innerHTML);
      dragEventNoticeNode.innerHTML = "Dragging stopped."
   }
}

// fixes visual cues in IE and Chrome.
DragDropHelpers.fixVisualCues=true;

EventHelpers.addPageLoadEvent('dragObject.init');

Before we get to the drag events, a word about the coding conventions I use for this and all the other code examples in this article:

  • the var me = this line ensures that the script doesn’t confuse the this keyword of the object with thethis keyword inside an event handler.
  • EventHelpers.addPageLoadEvent() (which is part of EventHelpers.js) will executedragObject.init when the HTML has loaded. addPageLoadEvent() is based on code from Dean Edwards’ article The window.onload Problem – Solved!. It is similar to jQuery’s$(document).ready()method and prototype’s dom:loaded event.
  • This code uses a JavaScript version of sprintf() that I had mentioned in a previous blog post. I have used it in all the remaining examples because I think it makes the code a lot easier to read (however, it is not necessary in order to make HTML5 drag and drop work).

Let’s get back to the drag events — you’ll notice that I have set the dragstartdrag and dragend events. When this page is loaded, it will tell you if the draggable object is currently being dragged, and will log all dragstart and dragstop events on-screen. Click on the example link below and see for yourself:

See Example #2, a draggable object with events attached

Step 3: Setting Events on the Target Object

Step 2 showed us how we can drag an object around the screen and know when each drag starts and ends. Now we need to drop the object. Let’s define a drop target to be an object where draggable objects can be dropped. A drop target can have the following event handlers attached to it:

Event nameDescription
dragenterFires when a draggable object is first dragged inside an object.
dragoverFires everytime a draggable object is moved inside an object. Note: if you want to allow the draggable object to be dropped inside this object, you must cancel the default behaviour of this event handler.
dragleaveFires when a draggable object is dragged out of an object.
dropFired when a draggable object is dropped into an object.

If you want an object to become a drop target, you must attach both the dragover and drop events to it. You may ask “I understand why I need to implement drop (after all, it is one half of the term “drag and drop”) but why do I needdragover?” As stated in the table above, the drop event will not fire unless you cancel the default behaviour of the event target’s dragover event. This point is really important and your scripts will not work correctly unless you do this.

You may ask “Why is there even a dragover event in the first place? Isn’t drag sufficient?” (In his article, Peter-Paul Kochasked this question a bit more emphatically that I did). The dragover event object does contain some useful information, such as the coordinates of the mouse pointer inside the event target, (When I created DragDropHelpers, this information allowed me to fix Explorer and Chrome’s visual cue issue that I mentioned in step #1). These coordinates are stored in the properties offsetX and offsetYexcept in Firefox 3.5 which keeps these values inside of the event properties layerXand layerY. For convenience, DragDropHelpers includes a method called getEventCoords() that will use the appropriate property to get these values (Note: layerX and layerY are only accurate when the drop target’s CSS positionpropety is set to relative, absolute or fixed).

To show how to add drop functionality to your code, lets take the code from example #2 and add a drop target:

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Example #3: a dragable object with a drop target</title>
      <script type="text/javascript" src="../../shared/js/sprintf.js"></script>
      <script type="text/javascript" src="../../shared/js/EventHelpers.js"></script>
      <script type="text/javascript" src="../../shared/js/DragDropHelpers.js"></script>

      <script type="text/javascript" src="js/03-dragObjectWithTargetObject.js"></script>

      <link rel="stylesheet" type="text/css" media="screen" href="css/test1.css" />

   </head>
   <body>

      <h1>Example #3: a dragable object with a drop target</h1>

      <p>Try to drag the red box around and dropping it in the target object.</p>

      <p><strong>Is dragging:</strong> <span id="dragEventNotice">no</span>

      <p id="eventLog"><strong>Event now firing:</strong><br /><span id="eventNotice"></span>
      <a class="goBack" href="http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/">Go back to the User Agent Man HTML5 Drag and Drop article</a></p>

      <a href="#" id="toDrag" draggable="true">This is a draggable item</a>
      <div id="dropTarget">This is a "target" object</div>

   </body>
</html>

The drop target will be the <div> with an id of dropTarget. The 03-dragObjectWithTargetObject.js script is the same code in example #2 except we add two event handlers:

  • dragover event that reports where the mouse is inside dropTarget
  • drop event that reports when the drop happened.
var dragObject = new function () {
   var me = this;

   var dragNode, targetNode;
   var eventNoticeNode, dragEventNoticeNode;
   me.init = function () {

   	if (EventHelpers.hasPageLoadHappened(arguments)) {
   		return;
   	}	

   	dragNode=document.getElementById('toDrag');
   	targetNode=document.getElementById('dropTarget');
   	eventNoticeNode = document.getElementById('eventNotice');
   	dragEventNoticeNode = document.getElementById('dragEventNotice');

   	/* These are events for the draggable object */
   	EventHelpers.addEvent(dragNode, 'dragstart', dragStartEvent);
   	EventHelpers.addEvent(dragNode, 'drag', dragEvent);
   	EventHelpers.addEvent(dragNode, 'dragend', dragEndEvent);

   	/* These are events for the object to be dropped */
   	EventHelpers.addEvent(targetNode, 'dragover', dragOverEvent);
   	EventHelpers.addEvent(targetNode, 'drop', dropEvent);

   }

   function dragStartEvent(e) {
   	showMessage("Drag Event started");
   }

   function dragEvent(e) {
   	dragEventNoticeNode.innerHTML = "Currently dragging.<br />";
   }

   function dragEndEvent(e) {
   	showMessage("Drag Event stopped");
   	dragEventNoticeNode.innerHTML = "Dragging stopped."
   }

   function dragOverEvent(e) {
   	var coords = DragDropHelpers.getEventCoords(e);
   	showMessage(sprintf(
   	   "Drag over event happened on node with id %s at coordinate (%d, %d)",
   	   this.id, coords.x, coords.y));
   	EventHelpers.preventDefault(e);
   }

   function dropEvent(e) {
   	showMessage("Drop event happened on node with id " + this.id);
   	EventHelpers.preventDefault(e);
   }

   function showMessage(message) {
   	eventNoticeNode.innerHTML =
   		sprintf("<strong>%s</strong>: %s<br />%s",
   			new Date(), message, eventNoticeNode.innerHTML);
   }

}

// fixes visual cues in IE and Chrome.
DragDropHelpers.fixVisualCues=true;

EventHelpers.addPageLoadEvent('dragObject.init');

(Note: EventHelpers.preventDefault(e) does what you’d expect: it prevents the default behavior of the event handler, similar to prototype’s Event.stop() or jQuery’s event.preventDefault())

See Example #3: a dragable object with a drop target

Note that in the above example, the time that the draggable object’s dragend event fires and the time that the drag target’sdrop event fires is not consistant among browsers. Safari and Chrome fire dragend first, while Firefox and Internet Explorer fire drop first.

The two other drop target events, dragenter and dragleave are not absolutely necessary for every script, but let’s add these events to example #3 anyway to see how they work:

var dragObject = new function () {
   var me = this;

   var dragNode, targetNode;
   var eventNoticeNode, dragEventNoticeNode;
   me.init = function () {

      if (EventHelpers.hasPageLoadHappened(arguments)) {
         return;
      }   

      dragNode=document.getElementById('toDrag');
      targetNode=document.getElementById('dropTarget');
      eventNoticeNode = document.getElementById('eventNotice');
      dragEventNoticeNode = document.getElementById('dragEventNotice');

      /* These are events for the draggable object */
      EventHelpers.addEvent(dragNode, 'dragstart', dragStartEvent);
      EventHelpers.addEvent(dragNode, 'drag', dragEvent);
      EventHelpers.addEvent(dragNode, 'dragend', dragEndEvent);

      /* These are events for the object to be dropped */
      EventHelpers.addEvent(targetNode, 'dragover', dragOverEvent);
      EventHelpers.addEvent(targetNode, 'drop', dropEvent);
      EventHelpers.addEvent(targetNode, 'dragenter', dragEnterEvent);
      EventHelpers.addEvent(targetNode, 'dragleave', dragLeaveEvent);
   }

   function dragStartEvent(e) {
      showMessage("Drag Event started");
   }

   function dragEvent(e) {
      dragEventNoticeNode.innerHTML = "Currently dragging.<br />";
   }

   function dragEndEvent(e) {
      showMessage("Drag Event stopped");
      dragEventNoticeNode.innerHTML = "Dragging stopped.";
   }

   function dragOverEvent(e) {
      var coords = DragDropHelpers.getEventCoords(e);

      showMessage(sprintf(
         "Drag over event happened on node with id %s at coordinate (%d, %d)",
         this.id, coords.x, coords.y));

      EventHelpers.preventDefault(e);
   }

   function dropEvent(e) {
      showMessage("Drop event happened on node with id " + this.id);
      EventHelpers.preventDefault(e);

   }

   function dragEnterEvent(e) {
      showMessage("Drag Enter event happened on node with id " + this.id);
   }

   function dragLeaveEvent(e) {
      showMessage("Drag Leave event happened on node with id " + this.id);
   }

   function showMessage(message) {
      eventNoticeNode.innerHTML =
         sprintf("<strong>%s</strong>: %s<br />%s",
            new Date(), message, eventNoticeNode.innerHTML);
   }

}

// fixes visual cues in IE and Chrome.
DragDropHelpers.fixVisualCues=true;

EventHelpers.addPageLoadEvent('dragObject.init');

See Example #3a: a drop target with dragenter and dragleave event handlers

(Note that in Firefox 3.5, a dragleave event will fire just before a drop event, which the other browsers don’t firedragleave when dropping).

Step 4: Passing Data Between the Draggable and Target Objects

Once a draggable object is dropped into a drop target, the two objects can pass information between them using the drop event’s dataTransfer property. This property has two methods, setData() and getData(). In order to pass data between the two, a developer must use setData() during one of the draggable node’s drag events (e.g. dragstart). The drop target can then receive this data during one of it’s events using the getData() method.

MethodDescription
setData(dataType, data)

Sets the data that can be shared between the draggable node and the drag target.

Parameters

  • dataType â€“ The type of data that is to be set. So far, the only cross-browser dataTypes that can be set are ‘Text’ and ‘Url’.
  • data â€“ The data that is going to be set.
getData(dataType)

Gets the data that was previously set by dataTransfer.setData()It can also get data that was set by a dataTransfer.setData() call from another page, another browser window, and another vendor’s web browser on the same machine. It also can get data that was set by a drop event of another desktop application (for example, Windows WordPad).

Parameters

  • dataType â€“ The type of data that is to be set. So far, the only cross-browser dataTypes that can be set are ‘Text’ and ‘Url’.

setData() takes one string parameter, which is the data you want to share between the draggable object and a drop target.

Let’s take the code from step #3 and mix it up a bit: instead of having one draggable object, let’s make four. I have taken four photos of the Beatles from the Wikmedia Commons and made them draggable.

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Test 4: setData() and getData()</title>
      <script type="text/javascript" src="../../shared/js/sprintf.js"></script>
      <script type="text/javascript" src="../../shared/js/helpers.js"></script>
      <script type="text/javascript" src="../../shared/js/DragDropHelpers.js"></script>

      <script type="text/javascript" src="js/04-setDataGetData.js"></script>

      <link rel="stylesheet" type="text/css" media="screen" href="css/test1.css" />

   </head>
   <body>

      <h1>Test 4: <code>setData()</code> and <code>getData()</code></h1>

      <img draggable="true" src="images/george.png" alt="George Harrison" />
      <img draggable="true" src="images/john.png" alt="John Lennon" />
      <img draggable="true" src="images/paul.png" alt="Paul McCartney" />
      <img draggable="true" src="images/ringo.png" alt="Ringo Starr" />

      <div id="dropTarget"><span>Drop an image here to find out more information about it.</span></div>

   </body>
</html>

The script 04-setDataGetData.js uses dataTransfer.setData() and .getData() to copy the <img> of the Beatle being dragged, as well as placing the alt attribute’s contents underneath the image.

var dragObject = new function () {
   var me = this;

   var targetNode;
   var eventNoticeNode, dragEventNoticeNode;

   var dataTransferCommentString;

   me.init = function () {

      if (EventHelpers.hasPageLoadHappened(arguments)) {
         return;
      }   

      targetNode=document.getElementById('dropTarget');
      eventNoticeNode = document.getElementById('eventNotice');
      dragEventNoticeNode = document.getElementById('dragEventNotice');

      /* These are events for the draggable objects */
      var dragNodes = cssQuery('[draggable=true]');
      for (var i = 0; i < dragNodes.length; i++) {
         var  dragNode=dragNodes[i]
         EventHelpers.addEvent(dragNode, 'dragstart', dragStartEvent);
      }

      /* These are events for the object to be dropped */
      EventHelpers.addEvent(targetNode, 'dragover', dragOverEvent);
      EventHelpers.addEvent(targetNode, 'drop', dropEvent);
   }

   function dragStartEvent(e) {
      e.dataTransfer.setData('Text',
         sprintf('<img src="%s" alt="%s" /><br /><p class="caption">%s</p>',
            this.src, this.alt, this.alt
         )
      );
   }

   function dragOverEvent(e) {
      EventHelpers.preventDefault(e);
   }

   function dropEvent(e) {
      this.innerHTML = e.dataTransfer.getData('Text');
      EventHelpers.preventDefault(e);
   }

}

// fixes visual cues in IE and Chrome.
DragDropHelpers.fixVisualCues=true;

EventHelpers.addPageLoadEvent('dragObject.init');

See Example #4: using setData() and getData()

As previously mentioned the data that is set in setData() can be read in other applications. If you are in Windows, open up WordPad and drag one of the images into it. You’ll see the data that was given to setData() during the dragstart event.

This interoperability with the operating system will allow developers to do some very interesting things which are out of the scope of this article. I will, however, want to explore this in future postings.

Step 5: Drag and Drop Effects

In a traditional desktop application, you can use drag and drop to copy objects, move objects, and create links to things. You can use the HTML5 drag and drop events to do this as well, but it would be nice to give the user visual cues to show what kind of action a draggable object can do, and what kind of action a drop target can accept. It would also be nice to only allow “copy objects” to only drop on drop targets that are programmed to accept them.

These features can be implemented using e.dataTransfer.effectAllowed on the draggable object ande.dataTransfer.dropEffect()on the drop target:

MethodDescription
e.dataTransfer.effectAllowedSets the type of effect a draggable object is allowed to make. Valid values arecopymovelinkcopyMovecopyLinklinkMoveall, and none.
e.dataTransfer.dropEffectSets the type of effect a drop target is allowed to accept. Valid effects includecopymove, and link.

When these are set correctly, drag and drop will only work when the draggable object’s effectAllowed and the drop target’s dropEffect are compatible. To illustrate this, let’s first change the dragstart and dragover events in example #4 to do the copy effect:

   function dragStartEvent(e) {
      e.dataTransfer.effectAllowed="copy"; 

      e.dataTransfer.setData('Text',
         sprintf('<img src="%s" alt="%s" /><br /><p class="caption">%s</p>',
            this.src, this.alt, this.alt
         )
      );
   }

   function dragOverEvent(e) {
      e.dataTransfer.dropEffect = "copy";
      EventHelpers.preventDefault(e);
   }

Example #5: matching drag and drop effects

Note that unlike example #4, the mouse pointer has changed from the copy icon (in Windows, [Windows Copy Icon]) to the move icon ([Windows Move Icon]).

Now let’s change the code so that the draggable object and the drop target don’t have matching effects:

   function dragStartEvent(e) {
      e.dataTransfer.effectAllowed="copy"; 

      e.dataTransfer.setData('Text',
         sprintf('<img src="%s" alt="%s" /><br /><p class="caption">%s</p>',
            this.src, this.alt, this.alt
         )
      );
   }

   function dragOverEvent(e) {
      e.dataTransfer.dropEffect = "move";
      EventHelpers.preventDefault(e);
   }

See Example #5a: unmatching drag and drop effects

You’ll see that the user is not able to drop the image on the drop target.

Update (Jan 28, 2010): There is a documented bug in Safari and Chrome for Windows where drag and drop will not occur ifeffectAllowed and dropEffect are set to move. This bug does not occur in the Mac editions of these browsers.

A More Complex Example

Let’s take all the information we have gathered and make a “real-world” script. Let’s say you were asked to create a “user entitlement” administration widget for a website. The widget will have three entitlement catagories: “Unassigned Users”, “Restricted Users” (e.g. users who have restricted access to the website) and “Power Users” (e.g. users who would have administration access to a website):

Screenshot of the user entitlement screen we want to implement

Screenshot of the user entitlement screen we want to implement

It should be rather easy for an administrator to drag and drop users back and forth between entitlement “buckets” in order to elevate or lower a users credentials.

Let’s go through the steps we established above to implement this script.

Step 1: Defining a Draggable Objects

First let’s take a look at the table in the HTML:

<table>
    <thead>
        <tr>
            <th>Unassigned Users</th>
            <th>Restricted Users</th>
            <th>Power Users</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td id="unassignedUsers">
            	<a href="#" draggable="true">Moe Howard</a>
		<a href="#" draggable="true">Curly Howard</a>
		<a href="#" draggable="true">Shemp Howard</a>
            	<a href="#" draggable="true">Larry Fine</a>
	    </td>

            <td id="restrictedUsers">
            </td>

            <td id="powerUsers">
            </td>
        </tr>
    </tbody>
    <tfoot>
	<td id="unassignedUsersHelp">
	  Drag a user from this list to another list to change the
	  user's permissions.
	</td>
	<td id="restrictedUsersHelp">
	  Dragging user here will give this user restricted
	  permissions.
	</td>
	<td id="powerUsersHelp" >
	  Dragging a user here will give this user power user access.
	</td>
    </tfoot>
</table>

(Note that the contents in the tfoot node are hidden by CSS).

Step 2: Setting Events on the Draggable Objects

The “users” are draggable objects. In the script, we find all these nodes using Dean Edwards’ cssQuery and set dragstartand dragend event handlers on each of them (Note: cssQuery allows us to select nodes by CSS selector, similar to the built-in functionality inside jQuery).

userNodes = cssQuery('[draggable=true]');
for (var i=0; i<userNodes.length; i++) {
   EventHelpers.addEvent(userNodes[i], 'dragstart', userDragStartEvent);
   EventHelpers.addEvent(userNodes[i], 'dragend', userDragEndEvent);
}

It then keeps track of the current node being dragged in the object variable currentlyDraggedNode and makes that node transparent by making it a member of the draggedUser class, which the page’s stylesheet defines as transparent.

function userDragStartEvent(e) {
   currentlyDraggedNode = this;
   currentlyDraggedNode.className = 'draggedUser';
}

The dragend event removes the transparency of the currentlyDraggedNode:

function userDragEndEvent(e) {
   currentlyDraggedNode.className = '';
}

Step 3: Setting Events on the Target Objects

All the table cells in the <tbody> are drop targets, so we use cssQuery again to grab all those nodes and set the appropriate events.

userListNodes = cssQuery('.userList');

for (var i=0; i<userListNodes.length; i++) {
   var userListNode = userListNodes[i];
   EventHelpers.addEvent(userListNode, 'dragover', cancel);
   EventHelpers.addEvent(userListNode, 'dragleave', userDragLeaveListEvent);
   EventHelpers.addEvent(userListNode, 'drop', userDropListEvent);
   EventHelpers.addEvent(userListNode, 'dragenter', userDragOverListEvent);
}

The most important event is the drop event handler. This event handler takes the currentlyDraggedNode, removes it from its current table cell (using removeChild()) and drops it into the drop target (using appendChild()).

function setHelpVisibility(node, isVisible) {
   var helpNodeId = node.id + "Help";
   var helpNode = document.getElementById(helpNodeId);

   if (isVisible) {
      helpNode.className =  'showHelp';
   } else {
      helpNode.className =  '';
   }
}

function userDropListEvent(e) {
   currentlyDraggedNode.parentNode.removeChild(currentlyDraggedNode);
   this.appendChild(currentlyDraggedNode);
   setHelpVisibility(this, false);
   userDragEndEvent(e);
}

They show the contents of the table cell below it by making it a member of the class showHelp. They also

prevent the dragover default behaviour so that drop events will fire in the drop target.

function userDragOverListEvent(e) {
   setHelpVisibility(this, true);
   EventHelpers.preventDefault(e);
}

The dragleave re-hides the contents of the table cell below it.

function userDragLeaveListEvent(e) {
  setHelpVisibility(this, false);
}
function userDragEndEvent(e) {
   currentlyDraggedNode.className = '';
}

Steps 4 and 5

We do not actually pass any data between the draggable object and the drag target — when the drop event occurs, the draggable object is moved from one column to another without the need of any dataTransfer data. The drag and drop effects were already handled in step 3, so we are all done.

See the above example in action

Drag and Drop Between Frames

Using the above information, it is also possible to drag and drop objects between frames (this is something that I don’t think any old school drag and drop script can do). I made an example below, and I leave it as an exercise to the reader to go through the code and figure out how it works.

See the inter-frame drag and drop example in action

Cross-Browser Issues I Have Seen

These are the cross-browser issues I know of so far. I will update this list with others I find in the future.

  • in Firefox 3.5, a dragleave event will fire just before a drop event, which the other browsers don’t firedragleave when dropping.
  • the time that the draggable object’s dragend event fires and the time that the drag target’s drop event fires is not consistant among browsers. Safari and Chrome fire dragend first, while Firefox and Internet Explorer fire drop first.
  • According to Francisco TolmaskysetData() cannot be called during drag events in Firefox. Hopefully this will be fixed in a future release of the browser.
  • DragDropHelpers implements a workaround for Explorer so it can drag any object around. However, I did not use this functionality in any of the examples because it exposes a problem with Safari not being able to drag an object correctly when the user initiates the drag on the text inside it. This problem doesn’t happen with text inside of links, but with text inside other nodes (like a <div> tag). I understand this problem has been fixed in the Safari nightly builds, so I left the functionality in the DragDropHelpers library for future use.
  • DragDropHelpers.js “fixes” the dragging visual cues in Explorer and Chrome by:
    • making a transparent and absolutely positioned clone of a draggable object when it’s dragstart event is fired
    • moving the cloned object near the mouse when the <body>‘s drag event is fired.
    • destroying the clone when draggable object’s dragend event is fired.

    I didn’t turn it on by default because I am not sure when (or if) this problem will be fixed in Internet Explorer or Chrome. I also doesn’t work well when dragging objects from one window or frame to another, since the cloned visual cue can’t jump from page to page. Feel free to use it (or not) as you see fit.

  • As mentioned previously, because of a bug in Webkit, drag and drop will not occur if effectAllowed anddropEffect are set to move in Safari 4.0.4. Hopefully this will be fixed in a future version of Webkit.

Conclusion

HTML5 drag and drop will be an important part of our front-end toolkit. Even though the flavors that browser-vendors offer today are incomplete, it is possible to smooth out these flaws to produce useful web applications. What I have covered here only scratches the surface – there are more properties and methods that some of browsers offer that can be used to further enhance the drag and drop experience. But I have been working on this blog entry way to long, and my wife is giving me that “what the hell are you doing up at this hour” look, so I think I’ll stop here for now.

Download

DragDropHelpers, and all code used in this article can be downloaded below.

DragDropHelpers.js v.1.0a and sample code.

Source : http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/

HTML5  DRAG AND DROP  DEMO  SOURCE CODE  CR 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.