<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>User Agent Man &#187; HTML</title>
	<atom:link href="http://www.useragentman.com/blog/category/technologies/html/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.useragentman.com/blog</link>
	<description>A Blog about Client Side Web Technology</description>
	<lastBuildDate>Wed, 08 Sep 2010 14:02:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Creating Cross Browser HTML5 Forms Now, Using modernizr, webforms2 and html5Widgets</title>
		<link>http://www.useragentman.com/blog/2010/07/27/cross-browser-html5-forms-using-modernizr-webforms2-and-html5widgets/</link>
		<comments>http://www.useragentman.com/blog/2010/07/27/cross-browser-html5-forms-using-modernizr-webforms2-and-html5widgets/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 03:50:06 +0000</pubDate>
		<dc:creator>zoltan</dc:creator>
				<category><![CDATA[Forms]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.useragentman.com/blog/?p=1110</guid>
		<description><![CDATA[Next generation web forms using HTML5 is hard to do today due to spotty browser support.  I demonstrate how a suite of JavaScript libraries can be used to help us use HTML5 Forms <strong>today</strong>.]]></description>
			<content:encoded><![CDATA[<div class="importantNotes">
<h3>Update (Aug. 6, 2010)</h3>
<p>This article has been <a href="http://nz.pe.kr/wordpress/?p=547">translated into Korean</a>
</div>
<div class="wp-caption alignright" style="width: 298px; border: solid 3px black;">
<div class="size-full wp-image-1387" style="width: 288px">
<form action="javascript:void(0)">
<table class="html5ExampleTable">
<tr>
<th>Range:</th>
<td>
<input type="range" /></td>
</tr>
<tr>
<th>Placeholder:</th>
<td>
<input type="text" placeholder="This is a test" /></td>
</tr>
<tr>
<th>Color:</th>
<td>
<input type="color" /></td>
</tr>
</table>
</form>
</div>
<p class="wp-caption-text" style="width: 288px;">Working example HTML5 Form using <a href="http://www.modernizr.com">Modernizr</a>, <a href="http://code.google.com/p/webforms2/">webforms2</a> and my new script, html5Widgets.  Go ahead &#8230; try them out.  You know you wanna!</p>
</div>
<p>Calendars, colour swatches, sliding widgets, client side validation: this is the nirvana that the HTML5 forms module promises. Some would say &#8220;So what? I&#8217;ve seen this on the web for years!&#8221;, and they&#8217;d be right. There have been some really brilliant people coding some really interesting widget and validation frameworks, so why should we change?</p>
<ul>
<li><strong>Ease the markup learning curve:</strong> HTML5 form widgets and validation have been built to be as dead simple to markup as a select box with no JavaScript knowledge required</li>
<li><strong>It&#8217;s a W3C standard:</strong> so you know that it&#8217;ll work for years to come and if you have problems, you could always ask almost anyone in the web development community for help.</li>
<li><strong>Cellular phone support:</strong> HTML5 form fields will have optimized user interfaces appropriate for the type of device.  <a href="http://devblog.blackberry.com/2010/03/use-html5-in-your-blackberry-web-content/">Blackberry already has optimized versions of the date/time and color widgets</a> and, according to <a href="http://diveintohtml5.org/">Mark Pilgrim&#8217;s</a> article <a href="http://diveintohtml5.org/forms.html">A Form of Madness</a>, the virtual keyboards that appear when using HTML5 form fields are optimized for the data being input.</li>
<li><strong>Web development tools will have to support it:</strong> It&#8217;s a safe bet that Aptana, Dreamweaver, and all the other IDEs out there will have HTML5 support.</li>
<li><strong>It&#8217;s HTML5:</strong> when you tell your non-techie co-workers that you use it, you will be the envy of all &mdash; after all, it <strong>must</strong> be five times better than regular HTML, right?  Your boss will be so impressed that you are now a guru in this futuristic technology with a cool numbered acronym that he or she will give you a big fat raise!!!
<p>(Okay, okay.  Don&#8217;t try to laugh too hard &#8230; your co-workers will start to worry).</li>
</ul>
<h2>The Support Dilemma</h2>
<p>Unfortunately, today&#8217;s support for the HTML5 Form Module is spotty with each browser supporting different parts of the specification.  Take a look at Wikipedia&#8217;s<a href="http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28HTML5%29"> HTML5 Forms comparison chart</a>.  You&#8217;ll see each browser supporting a different set of features, but the lowest common denominator they all support is rather small.</p>
<h2>But I Want To Use It <strong>Now!!!</strong></h2>
<p>HTML5 Forms started off as <a href="http://www.whatwg.org/specs/web-forms/2004-06-27-call-for-comments/">WebForms 2.0 back in 2004</a>, so I wasn&#8217;t surprised to see that a few developers had already coded some JavaScript implementations.  Weston Ruter&#8217;s cross browser library, <code>webforms2.js</code>, implements a huge chunk of it, including parts that didn&#8217;t make the transition from WebForms 2.0 to HTML5 forms (e.g. <a href="http://www.whatwg.org/specs/web-forms/current-work/#repeatingFormControls">Webform 2.0&#8242;s Repetition Model</a>).</p>
<p>Since widgets weren&#8217;t implemented in <code>webforms2</code>, I created <code>html5Widgets.js</code>.  This interface library is independent of <code>webforms2</code> &#8211; if all you want is a cross-browser HTML5 form with validation, then all you need is the original <code>webforms2.js</code>.  If you want special widgets that are not available for all browsers, include <code>html5Widgets.js</code>.  Since I did not want to re-invent the wheel by creating widgets from scratch, <code>html5Widgets.js</code> uses some really nice third party JavaScript libraries to create them (more on that below).  It also uses <code><a href="http://www.modernizr.com">Modernizr</a></code> to detect if there is native support for each of the HTML5 form widgets &#8211; if not, <code>html5Widgets</code> steps in to put the right widget in place.  To save bandwidth, developers only need to include the third party libraries for the widgets they need.</p>
<p>In the rest of this article, I will go over different parts of the HTML5 specification and show how you can use them in your applications today, step-by-step.  Each section will state which browser natively supports that part of the specification, and what is needed for browsers that don&#8217;t.  Eventually, when the browser manufacturers catch up with the standard, you won&#8217;t need to use any JavaScript at all.</p>
<h2>Form Validation Using the <code>required</code> and <code>pattern</code> Attributes</h2>
<p>The <code>required</code> attribute makes an input field mandatory and forces the user to enter in a value in order to submit the form data.  The markup is simple</p>
<blockquote class="code">
<pre>&lt;input type="text" name="firstName" value="" required="required" /&gt;
</pre>
</blockquote>
<p>(<strong>Note:</strong>, you can also just use <code>required</code> on its own if you aren&#8217;t trying to be XHTML compliant.)</p>
<p>The <code>pattern</code> attribute forces the user to enter in a value using a specified format.  It uses <a href="http://en.wikipedia.org/wiki/Regular_expressions">regular expressions</a> to define this format. For example, if you want to force the user to input a U.S. Zip Code inside a form field, you would use the following markup.</p>
<blockquote class="code">
<pre>&lt;--
     zip code regular expression from
     <a href="http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256F6B005294C2">http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256F6B005294C2</a>
--&gt;
&lt;input type="text" name="zipCode" value=""
   pattern="\d{5}([\-]\d{4})?" required="required"  /&gt;
</pre>
</blockquote>
<p>Note that <code>required</code> and <code>pattern</code> are independent from each other.  You can have a <code>pattern</code> set on a form field without it being <code>mandatory</code>  (i.e. the pattern would only be checked if the user enters in data into the field).</p>
<p>Opera 10+ (mobile and desktop editions) is the only browser that supports the validation routines natively.  To use this in all other browsers, all you need is to include the following script tags in the <code>head</code> of your document.</p>
<blockquote class="code">
<pre>&lt;script type="text/javascript" src="/path/to/archive/js/weston.ruter.net/webforms2/webforms2_src.js"&gt;
&lt;/script&gt;
</pre>
</blockquote>
<p>Let&#8217;s take a look at how this looks visually:</p>
<table class="screenshots">
<thead>
<tr>
<th>Opera 10+ Windows</th>
<th>Firefox 3.6 with webforms2.js</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="/tests/html5Widgets/patternRequired.html"><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/07/validityOpera.png" alt="[Screenshot of HTML5 Validation using Opera]" title="Screenshot of HTML5 Validation using Opera"  class="alignnone size-full wp-image-1282" /></a>
</td>
<td>
<a href="/tests/html5Widgets/patternRequired.html"><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/07/validityFirefoxWithHTML5Widgets.png" alt="[Screenshot of HTML5 Validation using Firefox and webforms2.js]" title="Screenshot of HTML5 Validation using Firefox and webforms2.js"  class="alignnone size-full wp-image-1282" /></a>
</td>
</tr>
</tbody>
</table>
<p>Note the &#8220;starred&#8221; style of the form field &mdash; this is not the default look and feel of the <code>required</code> fields, but something I added with a simple amount of CSS:</p>
<blockquote class="code">
<pre>input[required], select[required] {
	background: #ffffee url("../images/asterix.gif")  no-repeat left 2px;
	padding-left: 1.5em;
	width: 13.5em !important;
}
</pre>
</blockquote>
<p>(<strong>This CSS does <em>not</em> work in Internet Explorer 6.</strong>  Given that <strong>everything else in this article does</strong>, I hope the reader will overlook this one oversight considering that this browser should have entered retirement years ago (and have its driving license taken away, and shipped off to some really horrible nursing home watching really crappy talk shows all day and eating bad food &#8230;)</p>
<p><a class="exampleLink" href="/tests/html5Widgets/patternRequired.html">See an example of <code>pattern</code> and <code>required</code> in action.</a></p>
<p>Note that the same validation framework checks the values of inputs of type <code>email</code>, <code>url</code> and <code>number</code> to ensure that the values are in their respective valid formats.  As an added bonus, if you are using the iPhone or iPad version of Safari, the virtual keyboard that appears will be optimized for these type of form fields (e.g. when editing a <code>number</code> field, the keyboard that appears contains only digits and the &#8220;+&#8221;, &#8220;-&#8221;, and &#8220;.&#8221; keys.  This is native behaviour for iOS, and I hope other mobile browsers, such the Android&#8217;s, follow suit.</p>
<h2>The <code>autofocus</code> Attribute</h2>
<p>The <code>autofocus</code> attribute allows developers to choose which element has focus when the page is loaded.  The Google front page has done this via JavaScript, and now, 12 years later, there is finally an HTML attribute to easily handle this.</p>
<blockquote class="code">
<pre>&lt;input type="text" name="fullName" value=""
  required="required" autofocus="autofocus" /&gt;
</pre>
</blockquote>
<p>Safari, Chrome and Opera support it natively.  To make it work in other browsers, include the <code>webforms2.js</code> library, as we did in the <code>required</code> and  <code>pattern</code> examples.</p>
<p><a class="exampleLink" href="/tests/html5Widgets/autofocus.html">See an example of <code>autofocus</code> in action</a></p>
<h2>The <code>placeholder</code> Attribute</h2>
<p>A placeholder is a great visual cue to communicate any special information about a field (e.g. a description<br />
of the data to be input, if the field is required, etc). </p>
<div id="attachment_1317" class="wp-caption aligncenter" style="width: 397px"><a href="/tests/html5Widgets/placeholder.html"><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/07/placeholder.png" alt="An example of placeholder text.  The text disappears when the field has focus or if the user types information into the field." title="placeholder" width="387" height="94" class="size-full wp-image-1317" /></a><p class="wp-caption-text">An example of placeholder text.  The text disappears when the field has focus or if the user types information into the field.</p></div>
<p>Syntax is simple:</p>
<blockquote class="code">
<pre>&lt;input type="text" name="fullName" value="" required="required"
   placeholder="Required information" /&gt;
</pre>
</blockquote>
<p>Safari, Chrome and Firefox support this attribute natively.  To make it work in other browsers, it is necessary to load the html5Widgets library, with the necessary supporting libraries:</p>
<blockquote class="code">
<pre>&lt;script type="text/javascript"
   src="/path/to/shared/js/modernizr.com/modernizr-1.5.min.js"&gt;
&lt;/script&gt;

&lt;script type="text/javascript" src="/path/to/shared/js/EventHelpers.js"&gt;
&lt;/script&gt;

&lt;script type="text/javascript" src="/path/to/shared/js/html5Widgets.js"&gt;
&lt;/script&gt;
</pre>
</blockquote>
<p>What do these libraries do?</p>
<ul>
<li><a href="http://modernizr.com"><code>modernizr</code></a> is used to detect which HTML5 attributes and tags are supported by the users&#8217; browser</li>
<li><code>html5Widgets</code> is what actually does the placeholder logic, with <code>EventHelpers.js</code> providing cross-browser event-handling routines.</li>
</ul>
<p><a class="exampleLink" href="/tests/html5Widgets/placeholder.html">See an example of the HTML5 <code>placeholder</code><br />
tag in action.</a></p>
<h2>The <code>range</code> Input Type and <code>output</code> Tag</h2>
<p>Easily my favourite of the HTML5 widgets, <code>range</code> gives developers a sliding control to put inside their forms.  </p>
<p>The syntax is simple:</p>
<blockquote class="code">
<pre>&lt;input type="range"  name="rangeEl" value="" min="0" max="150" step="1" /&gt;
</pre>
</blockquote>
<p>The <code>min</code> and <code>max</code> attributes contain the minimum and maximum values, and <code>step</code> denotes by what increments the range slider increments by when moved.  Note that you can use these attributes with the <code>number</code> input type as well, but instead of having the fancy interface, it will use the validation engine to ensure the value follows what these attributes dictate.</p>
<p>At the time of this writing, Opera and WebKit based browsers (like Safari and Chrome), support it natively, and html5Widgets uses <a href="http://www.frequency-decoder.com/demo/slider-revisited/">the Frequency Decoder Slider Widget</a> to implement it in unsupported browsers.  To ensure cross-browser HTML5 range element goodness, place the following script tags in your document:</p>
<blockquote class="code">
<pre>&lt;!-- Needed for Range Element --&gt;
&lt;link type="text/css" rel="stylesheet" href="/path/to/shared/css/slider.css"&gt;

&lt;!--[if lte IE 6]&gt;
&lt;link type="text/css" rel="stylesheet" href="/path/to/shared/css/slider_ie.css" /&gt;
&lt;![endif]--&gt;

&lt;script type="text/javascript" src="/path/to/shared/js/frequency-decoder.com/slider.js"&gt;
&lt;/script&gt;

&lt;!-- Needed for Validation --&gt;
&lt;script type="text/javascript" src="/path/to/shared/js/weston.ruter.net/webforms2/webforms2_src.js"&gt;
&lt;/script&gt;

&lt;!-- Need for HTML5Widgets --&gt;
&lt;script type="text/javascript"
  src="/path/to/shared/js/modernizr.com/modernizr-1.5.min.js"&gt;
&lt;/script&gt;

&lt;script type="text/javascript" src="/path/to/shared/js/html5.js"&gt;
&lt;/script&gt;
&lt;script type="text/javascript" src="/path/to/shared/js/EventHelpers.js"&gt;
&lt;/script&gt;

&lt;script type="text/javascript" src="/path/to/shared/js/html5Widgets.js"&gt;
&lt;/script&gt;</pre>
</blockquote>
<p>Take a look at the screenshots below.  You will see that the way a <code>range</code> field varies among the browsers that natively support it, and even in some of the browsers that use html5Widgets:</p>
<table class="screenshots">
<thead>
<tr>
<th></th>
<th>Explorer 6.x+<br />
(html5Widgets support)</th>
<th>Firefox 3.5+<br />
(html5Widgets support)</th>
<th>Safari 4.0+<br />
(native support)</th>
<th>Chrome 3.0+<br />
(native support)</th>
<th>Opera 10.0+<br />
(native support)</th>
</tr>
</thead>
<tbody>
<tr>
<th>Windows</th>
<td><a href="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeExplorerWindows.png"><img title="Screenshot of range field for Internet Explorer 6" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeExplorerWindows.png" alt="Screenshot of range field for Internet Explorer 6" width="120" height="68" /></a></td>
<td><img title="Screenshot of range field for Windows Firefox" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeFirefoxWindows.png" alt="Screenshot of range field for Windows Firefox" width="120" height="68" /></td>
<td><img title="Screenshot of range field for Windows Safari" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeSafariWindows.png" alt="Screenshot of range field for Windows Safari " width="120" height="68" /></td>
<td><img title="Screenshot of range field for Chrome Windows" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeChromeWindows.png" alt="Screenshot of range field for Chrome Windows" width="120" height="68" /></td>
<td><img title="Screenshot of range field for Windows Opera" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeOperaWindows.png" alt="Screenshot of range field for Windows Opera" width="120" height="68" /></td>
</tr>
<tr>
<th>Mac</th>
<td>Not Applicable</td>
<td><img title="Screenshot of range field for Mac Firefox" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeFirefoxMac.png" alt="Screenshot of range field for Mac Firefox" width="120" height="68" /></td>
<td><img title="Screenshot of range field for Mac Safari" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeSafariMac.png" alt="Screenshot of range field for Mac Safari " width="120" height="68" /></td>
<td><img title="Screenshot of range field for Chrome Mac" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeChromeMac.png" alt="Screenshot of range field for Chrome Mac" width="120" height="68" /></td>
<td><img title="Screenshot of range field for Mac Opera" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeOperaMac.png" alt="Screenshot of range field for Mac Opera" width="120" height="68" /></td>
</tr>
<tr>
<th>Linux</th>
<td>Not Applicable</td>
<td><img title="Screenshot of range field for Linux Firefox" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeFirefoxUbuntu.png" alt="Screenshot of range field for Linux Firefox" width="120" height="68" /></td>
<td>Not Applicable</td>
<td><img title="Screenshot of range field for Linux Chrome" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeChromeUbuntu.png" alt="Screenshot of range field for Linux Chrome" width="120" height="68" /></td>
<td><img title="Screenshot of range field for Linux Opera" src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/rangeOperaUbuntu.png" alt="Screenshot of range field for Linux Opera" width="120" height="68" /></td>
</tr>
</tbody>
</table>
<p>The <code>output</code> tag can be used to show the value of a field, or the result of an operation performed on a number of fields, using JavaScript expressions.  Although the <code>output</code> tag may calculate fomulas referencing <em>any</em> form fields, it is useful especially for the <code>range</code> input type so users can see what value the range element is pointing to:</p>
<blockquote class="code">
<pre><span class="hilite">&lt;output onforminput="this.value = rangeEl.value"&gt;-&lt;/output&gt;</span>
&lt;input type="range"  name="rangeEl" value="" min="0" max="150" step="1" /&gt;
</pre>
</blockquote>
<p>The contents of the <code>output</code> tag is the default value.  Note the <code>this.value</code> syntax &#8211; I am not sure why the W3C HTML5 working group decided it was needed (why not just have the formula?), but it is.  If there are other types of expressions supported in the final specification, they are not supported by <code>html5Widgets</code> at this time.  Note that in order to apply CSS to the <code>output</code> tag in IE, it is necessary to use <a href="http://remysharp.com/2009/01/07/html5-enabling-script/">Remy Sharp&#8217;s HTML5 Enabling Script</a>.</p>
<p><a class="exampleLink" href="/tests/html5Widgets/range.html">See an example of the <code>range</code> input being used with the <code>output</code> tag.</a></p>
<p><a class="exampleLink" href="/tests/html5Widgets/output.html">See an example of the <code>output</code> tag being used <em>without</em> a <code>range</code> field.</a></p>
<h2>The <code>datetime</code>, <code>datetime-local</code>, <code>date</code>, <code>week</code> and <code>week</code> Input Types</h2>
<p>At the time of this writing, Opera is the only desktop browser that supports HTML5 date fields.  To support the other browsers, html5Widgets uses a slightly modified version of <a href="http://www.dynarch.com/">DynArch.com</a>&#8216;s <a href="http://www.dynarch.com/projects/calendar/old/">Ex-&#8221;Coolest&#8221; DHTML Calendar</a> (I decided not to use <a href="http://www.dynarch.com/projects/calendar/">the coolest one</a> because the Ex-Coolest has a more permissive license and it works really well). Now all browsers can support the <code>datetime</code>, <code>datetime-local</code>, <code>date</code>, <code>month</code> and <code>week</code> input fields, and submit these values in a consistent format.</p>
<p>Here are the scripts needed for the browsers that need it:</p>
<blockquote class="code">
<pre>
&lt;!-- Needed for Date/Time Elements --&gt;
&lt;link type="text/css" rel="stylesheet" href="/path/to/shared/js/jscalendar-1.0/calendar-win2k-1.css" /&gt;
&lt;script type="text/javascript" src="/path/to/shared/js/jscalendar-1.0/calendar.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="/path/to/shared/js/jscalendar-1.0/lang/calendar-en.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="/path/to/shared/js/jscalendar-1.0/calendar-setup.js"&gt;&lt;/script&gt;

&lt;!-- Needed for Validation --&gt;
&lt;script type="text/javascript" src="/path/to/shared/js/weston.ruter.net/webforms2/webforms2_src.js"&gt;
&lt;/script&gt;

&lt;!-- What glues all the above together --&gt;

&lt;script type="text/javascript" src="/path/to/shared/js/modernizr.com/modernizr-1.5.min.js"&gt;
&lt;/script&gt;
&lt;script type="text/javascript" src="/path/to/shared/js/EventHelpers.js"&gt;
&lt;/script&gt;
&lt;script type="text/javascript" src="/path/to/shared/js/html5Widgets.js"&gt;
&lt;/script&gt;
</pre>
</blockquote>
<p>Note that the calendar widget uses language packs and that I am using the English one (<code>calendar-en.js</code>.  Other language packs are included.</p>
<p>Below is a comparison between Opera&#8217;s native date widget vs. the one provided by the DynArch/HTML5Widget combo:</p>
<table class="screenshots">
<thead>
<tr>
<th></th>
<th>DateTime Widget</th>
<th>Month Widget</th>
</tr>
<tr>
<th>Opera Windows</th>
<td><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/dateTimeOperaWindows.png" /></td>
<td><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/monthOperaWindows.png" /></td>
</tr>
<tr>
<th>Opera Mac</th>
<td><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/dateTimeOperaMac.png" /></td>
<td><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/monthOperaMac.png" /></td>
</tr>
<tr>
<th>Firefox 3.5+ Windows<br />
(html5Widgets support)</th>
<td><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/datetimeFirefoxWithHTML5Widgets.png" /></td>
<td><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/05/monthFirefoxWithHTML5Widgets.png" /></td>
</tr>
</table>
<p>It looks like the native calendar for Opera for Mac is a smaller than the Windows version &#8211; hopefully this is just on my copy of the browser.</p>
<p>The display formats, and they values that they submit to the server, are pretty much the same</p>
<table class="screenshots">
<thead>
<tr>
<th>Input type</th>
<th>Format displayed on page</th>
<th>Format sent to server</th>
</tr>
</thead>
<tbody>
<tr>
<td>datetime</td>
<td><em>yyyy-mm-dd HH:MM</em></td>
<td><em>yyyy-mm-dd</em>T<em>HH:MM</em>Z</td>
</tr>
<tr>
<td>datetime-local</td>
<td><em>yyyy-mm-dd HH:MM</em></td>
<td><em>yyyy-mm-dd</em>T<em>HH:MM</em></td>
</tr>
<tr>
<td>date</td>
<td><em>yyyy-mm-dd</em></td>
<td><em>yyyy-mm-dd</em></td>
</tr>
<tr>
<td>month</td>
<td><em>yyyy-mm</em></td>
<td><em>yyyy-mm</em></td>
</tr>
<tr>
<td>week</td>
<td><em>yyyy-mm</em>W</td>
<td><em>yyyy-mm</em>W</td>
</tr>
</tbody>
</table>
<p><a class="exampleLink" href="/tests/html5Widgets/dateTime.html">See the HTML5 <code>date</code> widgets in action.</a></p>
<p><strong>Note:</strong> In this example, The Opera Mobile Windows Emulator incorrectly displays the <code>datetime</code> and <code>datetime-local</code> calendars in the upper left-hand corner of the screen, but <strong>not</strong> the other ones.  Since this is Opera&#8217;s own calendar widget, and not html5Widgets&#8217;, this bug will have to fixed by Opera.  </p>
<div id="attachment_1269" class="wp-caption aligncenter" style="width: 501px"><a href="http://www.useragentman.com/blog/wp-content/uploads/2010/07/operaMobileDateTimeBug.png"><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/07/operaMobileDateTimeBug.png" alt="Screenshot of Opera Mobile bug" title="operaMobileDateTimeBug" width="491" height="768" class="size-full wp-image-1269" /></a><p class="wp-caption-text">Screenshot of Opera Mobile bug</p></div>
<h2>The <code>color</code> Input Type</h2>
<p>Currently <strong>none</strong> of the desktop browser manufacturers support the <code>color</code> input type (although the new WebKit based <a href="http://devblog.blackberry.com/2010/03/use-html5-in-your-blackberry-web-content">Blackberry browser seems to have a neat implementation</a>). While we wait to see how the major browser manufacturers decide to implement <code>color</code>, you can use html5Widgets&#8217; implementation which uses <a href="http://www.softwareishard.com">Jan Odvarko</a>&#8216;s <a href="http://jscolor.com">jscolor</a>.  The script has been configured to allow only allow lower case hexadecimal rgb values to be entered, and that a blank value not be allowed, as per the W3C spec.</p>
<p>Here are the script tags needed to implement this in all browsers:</p>
<blockquote class="code"><pre>&lt;!-- Needed for Color Element --&gt;
&lt;script type="text/javascript" src="../../shared/js/jscolor/jscolor.js"&gt;
&lt;/script&gt;

&lt;!-- What glues all the above together --&gt;
&lt;script type="text/javascript" src="../../shared/js/modernizr.com/modernizr-1.5.min.js"&gt;
&lt;/script&gt;

&lt;script type="text/javascript" src="../../shared/js/EventHelpers.js"&gt;
&lt;/script&gt;

&lt;script type="text/javascript" src="../../shared/js/html5Widgets.js"&gt;
&lt;/script&gt;
</pre>
</blockquote>
<p>Below is a comparison between the Blackberry&#8217;s implementation (grabbed from <a href="http://devblog.blackberry.com/">the Blackberry Development Blog</a>) and HTML5Widget/jscolor&#8217;s. </p>
<table class="screenshot">
<thead>
<tr>
<th>Blackberry Web Browser</th>
<th>Firefox 3.5 with html5Widgets.js</th>
</thead>
<tbody>
<tr>
<td>
<a href="http://www.useragentman.com/blog/wp-content/uploads/2010/07/html5-color-input.jpg"><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/07/html5-color-input.jpg" alt="HTML5 Color form field, Blackberry" title="html5-color-input"  class="alignnone size-full wp-image-1292" /></a>
</td>
<td><a href="http://www.useragentman.com/blog/wp-content/uploads/2010/07/jscolor.png"><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/07/jscolor.png" alt="HTML5 color input field with html5Widgets and jscolor." title="jscolor"  class="alignnone size-full wp-image-1291" /></a>
</td>
</tr>
</tbody>
</table>
<p><a class="exampleLink" href="/tests/html5Widgets/color.html">See HTML5Widget&#8217;s implementation of the<br />
<code>color</code> input type.</a></p>
<p><strong>Note:</strong> Like other HTML syntax, <code>color</code> uses the unfortunate American spelling instead of the Queen&#8217;s Proper English (i.e. colour). Ensure you spell it incorrectly in order to make this work.  ;-)</p>
<h2>How Well Do These Libraries Handle the Official Specification?</h2>
<p>I have done some testing on some existing examples that use HTML5 forms to ensure that it works the way developers expect.  Here are a few examples that I have taken, with the necessary JavaScript added:</p>
<ul>
<li><a href="/tests/html5Widgets/24ways.org/index.html"><strong>A cool looking payment form</strong></a> by <a href="http://yaili.com/">Inayaili de León</a> (originally from<a href="http://24ways.org/2009/have-a-field-day-with-html5-forms"> her HTML5 forms tutorial</a>)</li>
<li><a href="/tests/html5Widgets/bradshawenterprises.com/index.html"><strong>An HTML5 Form Demo</strong></a> by <a href="http://www.bradshawenterprises.com/">Richard Bradshaw</a> (originally from his <a href="http://www.bradshawenterprises.com/blog/2010/fancy-forms-html5-css3-js/"><em>Fancy Forms: HTML5 + CSS3 – JS</em></a> article)</li>
<li><a href="/tests/html5Widgets/dev.opera.com"><strong>Another cool Example</strong></a> by <a href="http://annevankesteren.nl/">Anne van Kesteren</a> (originally from his article <a href="http://dev.opera.com/articles/view/improve-your-forms-using-html5/"><em>Improve your forms using HTML5!</em></a> on the <a href="http://dev.opera.com">The Opera Developer Community Website</a>).</li>
</ul>
<p>However, the HTML5 Forms specification is large, and unfortunately, the <code>webforms2</code> and <code>html5Widgets</code> libraries don&#8217;t implement everything &#8230; <strong>yet!!!!</strong>  Since I am really motivated with what HTML5 forms can do, I am committed to completing support to most, if not all, of the HTML5 Forms specification.  The version of <code>webforms2</code> in this blog post has been modified from Weston Ruter&#8217;s original verison, but it will be merged with the official Google Code version in the next week or so and will include compressed versions of all the library. The <code>html5Widgets</code> library will also have a permanent home there.</p>
<p>Things that I will be working on in the near future are:</p>
<ul>
<li><strong>Support for other HTML5 form elements</strong>, among other things, <code>datalist</code>, <code>number</code>, <code>keygen</code>, <code>progress</code>, <code>time</code> and <code>meter</code></li>
<li><strong>Support for CSS styling of HTML5 form widgets</strong> as well as the ability to style form fields according to their validation state (e.g. <code>:valid</code> and <code>:invalid</code> psudo-classes).  Opera seems to be the only browser currently supporting this.</li>
<li><strong>Default styling for some of the new input types</strong>, like <code>tel</code>, <code>email</code>, <code>url</code>.  Opera for Mac and Opera Mobile are the only browsers I know of that support this for <code>email</code> and <code>url</code>.
<p><div id="attachment_1298" class="wp-caption aligncenter" style="width: 340px"><a href="http://www.useragentman.com/blog/wp-content/uploads/2010/07/operaMacURLandEmail.png"><img src="http://www.useragentman.com/blog/wp-content/uploads/2010/07/operaMacURLandEmail.png" alt="email and url form fields in Opera Mac" title="" width="330" height="156" class="size-full wp-image-1298" /></a><p class="wp-caption-text"><code>email</code> and <code>url</code> form fields in Opera Mac</p></div></li>
<li><strong>Support for customizing the validation look and feel.</strong>  This is one I would love to do, since I&#8217;m sure a lot of developers would want to change how validation errors appear on the screen.  Unfortunately, the HTML5 specification doesn&#8217;t describe a standard way of doing this.  It will be interesting to see how the browser manufacturers deal with this issue (<em><strong>To any browser developer reading this is working on the display form validation errors:</strong> I would love to know how you are doing this if you are willing to share.  <strong>Hint, HINT! ;-)</strong></em>)</li>
<li><strong>In Internet Explorer 7 and lower, the ability to style input types it doesn&#8217;t support natively</strong> with CSS code like <code>input[type="range"]</code></li>
<li><strong>Enabling HTML5 forms validation on the server side</strong> to ensure data integrity for browser that don&#8217;t support HTML5 forms that have JavaScript disabled.</li>
<li><strong>Support for internationalization of the error messages used in <code>webforms2</code>.</strong>  If anyone wants to help in the translation of these error messages, please drop me a line &mdash; I need help!</li>
</ul>
<p>Below is a modified version of the Wikipedia&#8217;s HTML5 forms compatibility table and see what how things the support situation stands today.</p>
<table class="screenshots">
<thead>
<tr>
<th></th>
<th>Trident</th>
<th>Gecko</th>
<th>WebKit</th>
<th>Presto</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="5">Attributes</th>
</tr>
<tr>
<th><code>autocomplete</code></th>
<td class="table-yes">Yes</td>
<td class="table-yes">Yes</td>
<td class="table-yes">Yes</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>list</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>required</code></th>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>multiple</code></th>
<td class="table-no">No</td>
<td class="table-yes">1.9.2</td>
<td class="table-yes">526</td>
<td class="table-no">No</td>
</tr>
<tr>
<th><code>pattern</code></th>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="nightly table-yesWithWebforms2 table-nightly">Yes (with webforms2, and natively in Nightly build)</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>min</code>, <code>max</code></th>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>step</code></th>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="nightly table-nightly table-yesWithWebforms2">Yes (with webforms2 and Nightly build natively)</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>placeholder</code></th>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="table-yes">Yes</td>
<td class="table-yesWithWebforms2">Yes (with webforms2)</td>
</tr>
<tr>
<th><code>form</code></th>
<td class="table-no">No</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="table-no">No</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>autofocus</code></th>
<td class="table-yesWithhtml5Widgets">Yes (with html5Widgets)</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="nightly table-nightly table-yesWithhtml5Widgets">Yes (with html5Widgets and Nightly build natively)</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>maxlength</code></th>
<td class="table-no">No</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="nightly table-nightly">Nightly build</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>novalidate</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="nightly table-nightly">Nightly build</td>
<td class="table-no">No</td>
</tr>
<tr>
<th><code>control</code></th>
<td class="table-no">No</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
</tr>
<tr>
<th><code>accept</code></th>
<td class="table-no">No</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
</tr>
<tr>
<th><code>formtarget</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
</tr>
<tr>
<th><code>formaction</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
</tr>
<tr>
<th colspan="5">Elements</th>
</tr>
<tr>
<th><code>datalist</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>keygen</code></th>
<td class="table-no">No</td>
<td class="incorrect">1.0</td>
<td class="table-yes">125</td>
<td class="table-yes">1.0</td>
</tr>
<tr>
<th><code>output</code></th>
<td class="table-no">No</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="table-no">No</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>progress</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="nightly table-nightly">Nightly build</td>
<td class="table-no">No</td>
</tr>
<tr>
<th><code>meter</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="table-no">No</td>
</tr>
<tr>
<th colspan="5">Input types</th>
</tr>
<tr>
<th><code>search</code></th>
<td class="table-no">No</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="table-yes">312</td>
<td class="table-no">No</td>
</tr>
<tr>
<th><code>tel</code></th>
<td class="table-no">No</td>
<td class="nightly table-nightly">1.9.3</td>
<td class="nightly table-nightly">Nightly build</td>
<td class="table-no">No</td>
</tr>
<tr>
<th><code>url</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="nightly table-nightly">Nightly build</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>email</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="nightly table-nightly">Nightly build</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>datetime</code></th>
<td class="table-yesWithhtml5Widgets" rowspan="6">Yes (with html5Widgets)</td>
<td class="table-yesWithhtml5Widgets" rowspan="6">Yes (with html5Widgets)</td>
<td class="nightly table-nightly table-yesWithhtml5Widgets" rowspan="6">Yes (with html5Widgets and Nightly build natively)</td>
<td class="table-yes" rowspan="6">2.0</td>
</tr>
<tr>
<th><code>date</code></th>
</tr>
<tr>
<th><code>month</code></th>
</tr>
<tr>
<th><code>week</code></th>
</tr>
<tr>
<th><code>time</code></th>
</tr>
<tr>
<th><code>datetime-local</code></th>
</tr>
<tr>
<th><code>number</code></th>
<td class="table-no">No</td>
<td class="table-no">No</td>
<td class="nightly table-nightly">Nightly build</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>range</code></th>
<td class="table-yesWithhtml5Widgets">Yes (with html5Widgets)</td>
<td class="table-yesWithhtml5Widgets">Yes (with html5Widgets)</td>
<td class="table-yes">Yes</td>
<td class="table-yes">2.0</td>
</tr>
<tr>
<th><code>color</code></th>
<td class="table-yesWithhtml5Widgets">Yes (with html5Widgets)</td>
<td class="table-yesWithhtml5Widgets">Yes (with html5Widgets)</td>
<td class="nightly table-nightly table-yesWithhtml5Widgets">Yes (with html5Widgets and Nightly build natively)</td>
<td class="table-yesWithhtml5Widgets">Yes (with html5Widgets)</td>
</tr>
</tbody>
</table>
<h2>Integrating With <code>visibleIf</code> To Make Even <strong>Cooler</strong> Looking Forms</h2>
<p>The <code>webforms2</code> and <code>html5Widgets</code> libraries are designed to co-exist well with <code><a href="http://www.useragentman.com/blog/2010/06/20/visibleif-html5-custom-data-attributes-with-javascript-make-dynamic-interactive-forms/">visibleIf</a></code> to create interactive forms with fields that only validate the ones that visibleIf is displaying.</p>
<p><a class="exampleLink" href="/tests/html5Widgets/patternRequiredWithVisibleIf.html">See an example of HTML5 validation working with the <code>visibleIf</code> JavaScript library</a></p>
<h2>Acknowledgments, Shout-outs and Kudos</h2>
<ul>
<li><strong><a href="http://farukat.es/">Faruk Ates</a> and <a href="http://paulirish.com/">Paul Irish</a></strong> for <em>the</em> definitive HTML5 and CSS3 feature detector, <a href="http://www.modernizr.com/">modernizr</a>.</li>
<li><strong><a href="http://weston.ruter.net/">Weston Ruter</a></strong> for doing the insane amount of work on <a href="http://code.google.com/p/webforms2/">webforms2</a> <em>years ago</em>.</li>
<li><strong><a href="http://www.frequency-decoder.com/">Brian McAllister:</a></strong> for making the excellent <a href="http://www.frequency-decoder.com/2008/08/01/unobtrusive-slider-control-v2">Unobtrusive slider control</a> which I used for the range element.</li>
<li><strong><a href="http://www.dynarch.com/">Mihai Bazon</a></strong> for keeping the <a href="http://www.dynarch.com/projects/calendar/old/">The Ex-“Coolest” DHTML Calendar</a> around even though he has a paid product.</li>
<li><strong><a href="http://www.softwareishard.com">Jan Odvárko</a></strong> for his rocking <a href="http://jscolor.com/">jscolor</a> widget.</li>
<li><strong><a href="http://remysharp.com/">Remy Sharp</a></strong> for his fine <a href="<a href="http://remysharp.com/2009/01/07/html5-enabling-script/">HTML5 Enabling Script</a> so we can force IE to style things like the <code>output</code> tag.</li>
<li><strong><a href="http://yaili.com/">Inayaili de Leon</a>, <a href="http://annevankesteren.nl/">Anne van Kesteren</a> and <a href="http://www.bradshawenterprises.com/">Richard Bradshaw</a></strong> for allowing me to show how easy it is to make their original HTML5 Form demos work with html5Widgets.</li>
</ul>
<h2>Further Reading</h2>
<ul>
<li><strong><a href="http://www.w3.org/TR/html5/forms.htm">The W3C HTML5 Forms Specification Working Draft:</a></strong> The Working Draft is in &#8220;Last call for comments&#8221; status, so there may be some last minute changes.</li>
<li><strong><a href="http://diveintohtml5.org/forms.html">A Form of Madness:</a></strong> Chapter 10 of Mark Pilgrim&#8217;s great reference on HTML5.</li>
<li><strong><a href="http://www.whatwg.org/specs/web-forms/current-work/">Web Forms 2.0 Working Draft:</a></strong> The WHATWG spec that the W3C spec is based on.  It includes the repetition model which didn&#8217;t make it into the W3C spec</li>
<li><strong><a href="http://code.google.com/p/webforms2/">webforms2 -Web Forms 2.0 Cross-Browser Implementation:</a></strong> Weston Ruter&#8217;s original script on Google Code.  In the next few weeks, this will be the contain the updated script presented here, and will be the official home for html5Widgets.</li>
</ul>
<h2>Download</h2>
<p>This archive is the temporary home for <code>html5Widgets</code>.  It will soon be hosted at the <a href="http://code.google.com/p/webforms2/"><code>webforms2</code> Google Code page</a>.</p>
<p><a href="/downloads/html5Widgets-1.0.zip" class="exampleLink"><code>html5Widgets</code> v. 1.0 and example code (zip format)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.useragentman.com/blog/2010/07/27/cross-browser-html5-forms-using-modernizr-webforms2-and-html5widgets/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Cross Browser HTML5 Drag and Drop</title>
		<link>http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/</link>
		<comments>http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 03:52:17 +0000</pubDate>
		<dc:creator>zoltan</dc:creator>
				<category><![CDATA[Drag and Drop]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[drag]]></category>
		<category><![CDATA[dragend]]></category>
		<category><![CDATA[dragenter]]></category>
		<category><![CDATA[draggable]]></category>
		<category><![CDATA[dragleave]]></category>
		<category><![CDATA[dragover]]></category>
		<category><![CDATA[dragstart]]></category>
		<category><![CDATA[drop]]></category>
		<category><![CDATA[dropEffect]]></category>
		<category><![CDATA[effectAllowed]]></category>
		<category><![CDATA[getData]]></category>
		<category><![CDATA[html5 drag and drop]]></category>
		<category><![CDATA[on]]></category>
		<category><![CDATA[ondragstart]]></category>
		<category><![CDATA[setData]]></category>

		<guid isPermaLink="false">http://www.useragentman.com/blog/?p=734</guid>
		<description><![CDATA[HTML5 Drag and Drop is one of the least understood modules of the HTML5 specification and it can be a pain to implement in a cross browser fashion.  This article is for those who want to use it today in their web applications and goes into a lot of detail so you can "get the job done"]]></description>
			<content:encoded><![CDATA[<div class="importantNotes">
<h3>Update (Feb 3, 2009):</h3>
<ul>
<li>A <a href="http://code.google.com/p/chromium/issues/detail?id=14654">bug in Webkit</a> seems to be the culprit in the permissions form example below not working correctly in Safari 4.  The code has been updated to work around this bug and the article below has been updated.  Thanks to <code>russbuelt</code> for pointing this out.</li>
<li>Apparently, an example made by Apple which I reported not working in Safari <em>does</em> work in Safari 4.0.4 for Mac OS X.  Thanks for Scott Straker for this information.</li>
</div>
<div id="attachment_538" class="wp-caption alignleft" style="width: 267px"><a href="http://flickr.com/photos/svartling/3822068125/"><img class="size-full wp-image-538   " title="HTML5 Drag and Drop" src="http://www.useragentman.com/blog/wp-content/uploads/2010/12/html5DragAndDrop.png" alt="Remixed version of image by Svartling." width="257" height="174" /></a><p class="wp-caption-text">Image Credit: Flickr user svartling</p></div>
<p><a href="http://dev.w3.org/html5/spec/editing.html#dnd">HTML5 Drag and Drop</a> has been talked about a lot lately, but it&#8217;s hard to find really useful information about implementing it across multiple browsers.   <a href="http://hacks.mozilla.org/2009/07/html5-drag-and-drop/">Mozilla</a>, <a href="http://developer.apple.com/Mac/library/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/DragAndDrop.html">Apple</a> and <a href="http://msdn.microsoft.com/en-us/library/ms537658%28VS.85%29.aspx">Microsoft</a> all have pages describing how to use it, but their examples seem to work only in their particular browser (<strike><em><a href="http://developer.apple.com/Mac/library/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/DragAndDrop.html">Apple&#8217;s example</a> doesn&#8217;t even work in their own!</em></strike> <strong>Updated, Jan. 11, 2009:</strong> 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&#8217;s great article <a href="http://html5doctor.com/native-drag-and-drop/">Native Drag and Drop</a> was a good place for me to start — however, the examples didn&#8217;t work in Internet Explorer.  I also thoroughly enjoyed JavaScript guru <a href="http://www.quirksmode.org/">Peter-Paul Koch&#8217;s</a> <a href="http://www.quirksmode.org/blog/archives/2009/09/the_html5_drag.html">humorous and lengthy rant about cross-browser drag and drop headaches</a> where he uses creative and colourful language to describe what he thought of the standard, the browser manufacturers, and the WHAT-WG.</p>
<p>When normal people see the author of the <a href="http://www.quirksmode.org/compatibility.html">Compatibility Master Tables</a> respond negatively to a web technology, they would probably assume it would be a good sign to stay away from it.</p>
<p>However, I am not normal.  <strong>With a name like Zoltan, how could I <em>possibly</em> be normal?</strong> (and yes, <a href="http://www.useragentman.com/blog/the-infamous-zoltan-faq/">it <em>is</em> my real name</a>).</p>
<p>So, I decided to find out for myself how bad HTML5 Drag and Drop really is. Almost immediately, I understood Koch&#8217;s reaction &#8211; the browser vendors have not implemented all the same features, and there are even a few quirks in how the features that <em>are </em>implemented work.  However, after doing <em>a lot</em> of research, <strong>I found a common denominator that works well</strong>, with the help of a small bit of JavaScript that smooths out the edges.  Despite the implementation flaws, <strong>Future-proof HTML5 Drag and Drop is not too hard for developers to use in their own applications.</strong> 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:</p>
<p><a class="exampleLink" href="/tests/dragAndDrop/permissionForm.html#">See an example of HTML5 Drag and Drop in action.</a></p>
<h2>Advantages Over Existing Drag and Drop Implementations</h2>
<p>Koch mentioned in his blog post that &#8220;Web developers MUST NOT (in the sense of RFC 2119) use HTML 5 drag and drop. They should use <a href="http://www.quirksmode.org/js/dragdrop.html">old-school scripts</a> instead&#8221;.  I would argue that developers <em>should</em> use HTML5 drag and drop for the following reasons:</p>
<ul>
<li><strong>JavaScript Framework Independent: </strong>Most other (but not all) drag and drop implementations are tied into 3rd party frameworks like <a href="http://www.dojotoolkit.org/">Dojo</a>, <a href="http://www.prototypejs.org/">Prototype</a> or <a href="http://jquery.com/">jQuery</a>.</li>
<li><strong>Built-in Browser Support: </strong>HTML5 Drag and Drop is supported in Firefox 3.5+, Chrome 3.0+, Safari 3.0+ and Internet Explorer 5.0 (<strong>Note:</strong> that is not a typo &mdash; HTML5 Drag and Drop is based on work done by Microsoft <strong>in 1999</strong>).  Because it is part of HTML5, I assume Opera support should be inevitable.</li>
<li><strong>Integration With Other Web Applications:</strong> the HTML5 specification will allow developers to <em><strong>produce  drag and drop scripts that work across frames, and across browser windows.</strong></em></li>
<li><strong>Integration With Non-Web Applications:</strong> the HTML5 specification also allows users to <em><strong>drag and drop data to and from non-web applications</strong></em></li>
</ul>
<h2>The Basics of Drag and Drop, Step by Step</h2>
<p>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.</p>
<div class="steps">
<h3>Step 1: Defining a Draggable Object</h3>
<p>First you need to define the HTML nodes that you want to drag.  Firefox requires that these nodes have their <code>draggable</code> attribute set to <code>"true"</code>, Internet Explorer requires that the node must be an <code>&lt;a&gt;</code> tag with (the <code>href</code> attribute set) or an <code>&lt;img&gt;</code> tag.</p>
<blockquote class="code">
<pre>&lt;a href="#" id="toDrag" draggable="true"&gt;This is a draggable item&lt;/a&gt;</pre>
</blockquote>
<p>To show how this works, I have written a very simple page with a the above markup in the <code>&lt;body&gt;</code>:</p>
<blockquote class="code">
<pre>&lt;!DOCTYPE html&gt;

&lt;html lang="en"&gt;
    &lt;head&gt;
        &lt;meta name="generator" content="HTML Tidy, see www.w3.org"&gt;

        &lt;title&gt;Test #1: A Simple Draggable Object&lt;/title&gt;

      &lt;script type="text/javascript" src="../../shared/js/EventHelpers.js"&gt;
      &lt;/script&gt;
      &lt;script type="text/javascript" src="../../shared/js/DragDropHelpers.js"&gt;
      &lt;/script&gt;

        &lt;link rel="stylesheet" type="text/css" media="screen" href=
        "css/test1.css"&gt;
    &lt;/head&gt;

    &lt;body&gt;
        &lt;h1&gt;Test #1: A Simple Draggable Object&lt;/h1&gt;

<span class="hilite">        &lt;a href="#" id="toDrag" draggable="true"&gt;This is a
        draggable item&lt;/a&gt;</span>

        &lt;p&gt;Try to drag the red box around. You will see the
        draggable object cloned in every browser except Explorer
        and Chrome.&lt;/p&gt;

        &lt;a href=
        "http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/"&gt;
        Go back to the User Agent Man HTML5 Drag and Drop
        article&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
</blockquote>
<p>Note that this HTML page has two scripts in the <code>&lt;head&gt;</code>:</p>
<ul>
<li><strong><code>EventHelpers.js</code>:</strong> 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.</li>
<li><strong><code>DragDropHelpers.js</code>:</strong> among other things that I will get to later, will activate dragging on <code>draggable="true"</code> objects in Safari and Chrome using a built-in copy of Dean Edwards&#8217; <a href="http://dean.edwards.name/my/cssQuery/">cssQuery</a>.  It does this by inserting the following CSS code into the HTML document:<br />
<blockquote class="code">
<pre>[draggable=true] {
  -khtml-user-drag: element;
  -webkit-user-drag: element;
  -khtml-user-select: none;
  -webkit-user-select: none;
}</pre>
</blockquote>
<p>The first two rules allow the dragging of the <code>draggable="true"</code> 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 <code>-khtml </code>properties work in older versions of Safari, while <code>-webkit</code> ones work in newer versions.  <strong>Without these CSS properties, these nodes will not be draggable when using the Safari web browser</strong></li>
</ul>
<p><a class="exampleLink" href="/tests/dragAndDrop/01-dragObject.html">See Example  #1: a draggable object</a></p>
<p>A couple of notes:</p>
<ol>
<li> You&#8217;ll notice that when you hover the mouse pointer over the draggable item, it will change to <img class="alignnone size-full wp-image-599" title="The  &quot;Move&quot; cursor" src="http://www.useragentman.com/blog/wp-content/uploads/2010/01/cursor-move.gif" alt="The  &quot;Move&quot; cursor" width="24" height="28" />(i.e. I the &#8220;move&#8221; cursor).  This is not the default behavior of the web browser &#8211; it is something I added in <code>DragDropHelpers</code>, since I believe that it&#8217;s a nice visual cue to show users that an object is draggable (if you don&#8217;t want this behavior, it is possible to turn it off in your own scripts by setting <code>DragDropHelpers.showMouseoverCue</code> to false</li>
<li>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):<br />
<table class="screenshots" border="0">
<thead>
<tr>
<th>Firefox (Windows XP)</th>
<th>Safari (Windows XP)</th>
<th>Explorer &amp; Chrome (Windows XP)</th>
</tr>
</thead>
<tbody>
<tr>
<td><img class="alignnone size-full wp-image-514" title="Dragging of a link element, Firefox Windows" src="http://www.useragentman.com/blog/wp-content/uploads/2010/12/dragLink-firefoxWindows.png" alt="[Dragging of a link element, Firefox Windows]" width="180" height="190" /></td>
<td><img class="alignnone size-full wp-image-514" title="Dragging of a link element, Safari Windows" src="http://www.useragentman.com/blog/wp-content/uploads/2010/12/dragLink-safariWindows.png" alt="[Dragging of a link element, Safari Windows]" width="180" height="190" /></td>
<td><img class="alignnone size-full wp-image-514" title="Dragging of a link element, Explorer Windows" src="http://www.useragentman.com/blog/wp-content/uploads/2010/12/dragLink-explorerWindows.png" alt="[Dragging of a link element, Explorer Windows]" width="180" height="190" /></td>
</tr>
</tbody>
</table>
<p>Note the differences between these three browsers:</p>
<ul>
<li>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 &#8220;This is a draggable item&#8221; written inside.  Explorer and Chrome don&#8217;t show any effect at all (We will address this issue later).</li>
<li>Since we have not established <em>where</em> we are going to drag our object, all Windows browsers will change the mouse pointer cursor to <img class="alignnone size-full wp-image-567" title="&quot;Not-Allowed&quot; cursor." src="http://www.useragentman.com/blog/wp-content/uploads/2010/12/cursor_not-allowed.gif" alt="&quot;Not-Allowed&quot; cursor." width="22" height="22" /> (a.k.a. the &#8220;not-allowed&#8221; mouse pointer).  This is the expected behavior, and you will see later that it will help the user know where to drop the object.</li>
</ul>
<p>On OS X, Firefox and Safari look similar to Firefox for Windows, except that the &#8220;not-allowed&#8221; mouse-pointer doesn&#8217;t show up:</p>
<table class="screenshots" border="0">
<thead>
<tr>
<th>Firefox (OS X)</th>
<th>Safari (OS X)</th>
<th>Chrome (OS X)</th>
</tr>
</thead>
<tbody>
<tr>
<td><img class="alignnone size-full wp-image-513" title="Dragging of a link element, Firefox OS X" src="http://www.useragentman.com/blog/wp-content/uploads/2010/12/dragLink-firefoxMac.png" alt="[Dragging of a link element, Firefox Windows]" width="180" height="190" /></td>
<td><img class="alignnone size-full wp-image-514" title="Dragging of a link element, Safari OS X" src="http://www.useragentman.com/blog/wp-content/uploads/2010/12/dragLink-safariMac.png" alt="[Dragging of a link element, Safari OS X]" width="180" height="190" /></td>
<td><img class="alignnone size-full wp-image-653" title="Chrome for Mac" src="http://www.useragentman.com/blog/wp-content/uploads/2010/01/dragLink-chromeMac.png" alt="Chrome for Mac" width="180" height="190" /></td>
</tr>
</tbody>
</table>
<p>The Linux browsers don&#8217;t have the &#8220;not-allowed&#8221; mouse cursor either.  Also, the cloned version of the draggable object isn&#8217;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).</p>
<table class="screenshots" border="0">
<thead>
<tr>
<th>Firefox (Ubuntu)</th>
<th>Chrome (Ubuntu)</th>
</tr>
</thead>
<tbody>
<tr>
<td><img class="size-full wp-image-698 alignnone" title="dragLink-firefoxUbuntu" src="http://www.useragentman.com/blog/wp-content/uploads/2010/01/dragLink-firefoxUbuntu.png" alt="Firefox Linux" width="180" height="190" /></td>
<td><img class="size-full wp-image-697 alignnone" title="dragLink-chromeUbuntu" src="http://www.useragentman.com/blog/wp-content/uploads/2010/01/dragLink-chromeUbuntu.png" alt="Chrome Linux" width="180" height="190" /></td>
</tr>
</tbody>
</table>
<p>The fact that Explorer and Chrome don&#8217;t have any visual dragging cues bugged me, so I put a &#8220;fix&#8221; inside <code>DragDropHelpers.js</code> which can be turned on by setting <code>DragDropHelpers.fixVisualCues</code> to true.  Let&#8217;s look at a slightly refactored version of Example #1 where we insert the following code in the <code>&lt;head&gt;:</code></p>
<blockquote class="code">
<pre>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
   &lt;head&gt;
      &lt;title&gt;Test #1: A Simple Draggable Object (with visual cues added to Explorer and Chrome)&lt;/title&gt;
      &lt;script type="text/javascript" src="../../shared/js/EventHelpers.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="../../shared/js/DragDropHelpers.js"&gt;&lt;/script&gt;
<span class="hilite">      &lt;script type="text/javascript"&gt;
      &lt;!--
      DragDropHelpers.fixVisualCues=true;
      --&gt;
      &lt;/script&gt;</span>

      &lt;link rel="stylesheet" type="text/css" media="screen" href="css/test1.css" /&gt;

   &lt;/head&gt;
   &lt;body&gt;

      &lt;h1&gt;Test #1: A Simple Draggable Object (with visual cues added to Explorer and Chrome)&lt;/h1&gt;

      &lt;a href="#" id="toDrag" draggable="true"&gt;This is a draggable item&lt;/a&gt;

      &lt;p&gt;Try to drag the red box around.  You will see the draggable object cloned in all browsers.&lt;/p&gt;

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

   &lt;/body&gt;
&lt;/html&gt;
</pre>
</blockquote>
</li>
</ol>
<p><a class="exampleLink" href="/tests/dragAndDrop/01a-dragObject.html">See Example #1a, a draggable object with visual cue fix for Explorer and Chrome</a></p>
<p>Voila!  The visual cue now shows up.  I&#8217;ll explain how this works at the end of the article.</p>
<h3>Step 2: Setting Events on the Draggable Object</h3>
<p>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:</p>
<table class="dataTable" border="0">
<thead>
<tr>
<th>Event name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>dragstart</code></td>
<td>Fires when the user starts dragging of the object.</td>
</tr>
<tr>
<td><code>drag</code></td>
<td>Fires every time the mouse is moved while the object is being dragged.</td>
</tr>
<tr>
<td><code>dragend</code></td>
<td>Fires when the user releases the mouse button while dragging an object.</td>
</tr>
</tbody>
</table>
<p>A developer would attach these events the way they would any other JavaScript event &#8211; I use <code>EventHelpers.addEvent</code>, but one could use jQuery&#8217;s <code>bind()</code> method, prototype&#8217;s <code>Event.observe()</code> or whatever you favourite framework provides for event handling.  Developers can also use the old school inline events (i.e. <code>&lt;a href="#" id="toDrag" draggable="true" <span class="hilite">ondragstart="somefunction();"</span>&gt;This is a draggable item&lt;/a&gt;</code>), but I try to stay away from using those to seperate document structure from behavior.</p>
<p>Let&#8217;s take the example in step 1 and change it so we can log when these events happen to the <code>toDrag</code> node:</p>
<blockquote class="code">
<pre>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
   &lt;head&gt;
      &lt;title&gt;Example #2: a draggable object with events attached &lt;/title&gt;
<span class="hilite">      &lt;script type="text/javascript" src="../../shared/js/sprintf.js"&gt;&lt;/script&gt;</span>
      &lt;script type="text/javascript" src="../../shared/js/EventHelpers.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="../../shared/js/DragDropHelpers.js"&gt;&lt;/script&gt;

<span class="hilite">      &lt;script type="text/javascript" src="js/02-dragObjectWithEvent.js"&gt;&lt;/script&gt;</span>

      &lt;link rel="stylesheet" type="text/css" media="screen" href="css/test1.css" /&gt;

   &lt;/head&gt;
   &lt;body&gt;

      &lt;h1&gt;Example #2: a draggable object with events attached&lt;/h1&gt;

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

<span class="hilite">      &lt;p&gt;&lt;strong&gt;Is dragging:&lt;/strong&gt; &lt;span id="dragEventNotice"&gt;no&lt;/span&gt;

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

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

      &lt;a href="#" id="toDrag" draggable="true"&gt;This is a draggable item&lt;/a&gt;

   &lt;/body&gt;
&lt;/html&gt;
</pre>
</blockquote>
<p>In the <code>02-dragObjectWithEvent.js</code> script, the <code>dragEventNotice</code> node will be used to report whether the user is dragging the object around, and the <code>eventNotice</code> will be used to log what events the user has fired:</p>
<blockquote class="code">
<pre>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 */
<span class="hilite">      EventHelpers.addEvent(dragNode, 'dragstart', dragStartEvent);
      EventHelpers.addEvent(dragNode, 'drag', dragEvent);
      EventHelpers.addEvent(dragNode, 'dragend', dragEndEvent);</span>
   }

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

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

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

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

EventHelpers.addPageLoadEvent('dragObject.init');</pre>
</blockquote>
<p>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:</p>
<ul>
<li>the <code>var me = this </code>line ensures that the script doesn&#8217;t confuse the <code>this </code>keyword of the object with the <code>this </code>keyword inside an event handler.</li>
<li><code>EventHelpers.addPageLoadEvent()</code> (which is part of <code>EventHelpers.js</code>) will execute <code>dragObject.init</code> when the HTML has loaded.  <code>addPageLoadEvent()</code> is based on code from Dean Edwards&#8217; article <a href="http://dean.edwards.name/weblog/2005/09/busted/">The window.onload Problem &#8211; Solved!</a>.  It is similar to jQuery&#8217;s<code> $(document).ready()</code>method and prototype&#8217;s <code>dom:loaded</code> event.</li>
<li>This code uses a JavaScript version of <code>sprintf()</code> that <a href="/blog/2009/12/22/my-favourite-third-party-javascript-libraries/">I had mentioned in a previous blog post</a>.  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).</li>
</ul>
<p>Let&#8217;s get back to the drag events — you&#8217;ll notice that I have set the <code>dragstart</code>, <code>drag</code> and <code>dragend</code> events.  When this page is loaded, it will tell you if the draggable object is currently being dragged, and will log all <code>dragstart</code> and <code>dragstop</code> events on-screen. Click on the example link below and see for yourself:</p>
<p><a class="exampleLink" href="/tests/dragAndDrop/02-dragObjectWithEvents.html">See Example #2, a draggable object with events attached</a></p>
<h3>Step 3: Setting Events on the Target Object</h3>
<p>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&#8217;s define a <strong>drop target</strong> to be <strong>an object where draggable objects can be dropped</strong>.  A drop target can have the following event handlers attached to it:</p>
<table class="dataTable" border="0">
<thead>
<tr>
<th>Event name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>dragenter</code></td>
<td>Fires when a draggable object is <strong>first dragged inside</strong> an object.</td>
</tr>
<tr>
<td><code>dragover</code></td>
<td>Fires everytime a draggable object is <strong>moved inside</strong> an object.  <strong>Note: if you want to allow the draggable object to be <em>dropped </em>inside this object, <em>you must cancel the default behaviour of this event handler.</em></strong></td>
</tr>
<tr>
<td><code>dragleave</code></td>
<td>Fires when a draggable object is <strong>dragged out</strong> of an object.</td>
</tr>
<tr>
<td><code>drop</code></td>
<td>Fired when a draggable object is <strong>dropped into</strong> an object.</td>
</tr>
</tbody>
</table>
<p><strong>If you want an object to become a drop target, you must attach both the <code>dragover</code> and <code>drop</code> events to it.</strong> You may ask &#8220;I understand why I need to implement <code>drop</code> (after all, it is one half of the term &#8220;drag and drop&#8221;) but why do I need <code>dragover</code>?&#8221;  <strong>As stated in the table above, the <code>drop</code> event will not fire unless you cancel the default behaviour of the event target&#8217;s <code>dragover</code> event</strong>.  This point is really important and <strong>your scripts will not work correctly unless you do this</strong>.</p>
<p>You may ask &#8220;Why is there even a <code>dragover</code> event in the first place?  Isn&#8217;t <code>drag</code> sufficient?&#8221; (In his article, Peter-Paul Koch <a href="http://www.quirksmode.org/blog/archives/2009/09/the_html5_drag.html#link8"> asked this question a bit more emphatically that I did</a>).  The <code>dragover</code> event object does contain some useful information, such as <strong>the coordinates of the  mouse pointer inside the event target</strong>, (When I created <code>DragDropHelpers</code>, this information allowed me to fix Explorer and Chrome&#8217;s visual cue issue that I mentioned in step #1).  These coordinates are stored in the properties <code>offsetX</code> and <code>offsetY</code>, <strong>except in Firefox 3.5</strong> which keeps these values inside of the event properties <code>layerX</code> and <code>layerY</code>.  For convenience, <code>DragDropHelpers</code> includes a method called <code>getEventCoords()</code> that will use the appropriate property to get these values (<strong>Note:</strong> <code>layerX</code> and <code>layerY</code> are only accurate when the drop target&#8217;s CSS <code>position</code> propety is set to <code>relative</code>,<code> absolute</code> or <code>fixed</code>).</p>
<p>To show how to add drop functionality to your code, lets take the code from example #2 and add a drop target:</p>
<blockquote class="code">
<pre>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
   &lt;head&gt;
      &lt;title&gt;Example #3: a dragable object with a drop target&lt;/title&gt;
      &lt;script type="text/javascript" src="../../shared/js/sprintf.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="../../shared/js/EventHelpers.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="../../shared/js/DragDropHelpers.js"&gt;&lt;/script&gt;

<span class="hilite">      &lt;script type="text/javascript" src="js/03-dragObjectWithTargetObject.js"&gt;&lt;/script&gt;</span>

      &lt;link rel="stylesheet" type="text/css" media="screen" href="css/test1.css" /&gt;

   &lt;/head&gt;
   &lt;body&gt;

      &lt;h1&gt;Example #3: a dragable object with a drop target&lt;/h1&gt;

      &lt;p&gt;Try to drag the red box around and dropping it in the target object.&lt;/p&gt;

      &lt;p&gt;&lt;strong&gt;Is dragging:&lt;/strong&gt; &lt;span id="dragEventNotice"&gt;no&lt;/span&gt;

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

      &lt;a href="#" id="toDrag" draggable="true"&gt;This is a draggable item&lt;/a&gt;
<span class="hilite">      &lt;div id="dropTarget"&gt;This is a "target" object&lt;/div&gt;</span>

   &lt;/body&gt;
&lt;/html&gt;
</pre>
</blockquote>
<p>The drop target will be the <code>&lt;div&gt;</code> with an <code>id</code> of <code>dropTarget</code>.   The <code>03-dragObjectWithTargetObject.js</code> script is the same code in example #2 except we add two event handlers:</p>
<ul>
<li>a <code>dragover</code> event that reports where the mouse is inside <code>dropTarget</code></li>
<li>a <code>drop</code> event that reports when the drop happened.</li>
</ul>
<blockquote class="code">
<pre>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 */
   	<span class="hilite">EventHelpers.addEvent(targetNode, 'dragover', dragOverEvent);</span>
   	<span class="hilite">EventHelpers.addEvent(targetNode, 'drop', dropEvent);</span>

   }

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

   function dragEvent(e) {
   	dragEventNoticeNode.innerHTML = "Currently dragging.&lt;br /&gt;";
   }

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

<span class="hilite">   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);
   }</span>

<span class="hilite">   function dropEvent(e) {
   	showMessage("Drop event happened on node with id " + this.id);
   	EventHelpers.preventDefault(e);
   }</span>

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

}

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

EventHelpers.addPageLoadEvent('dragObject.init');</pre>
</blockquote>
<p>(<strong>Note:</strong> <code>EventHelpers.preventDefault(e)</code> does what you&#8217;d expect: it prevents the default behavior of the event handler, similar to prototype&#8217;s <code>Event.stop()</code> or jQuery&#8217;s <code>event.preventDefault()</code>)</p>
<p><a class="exampleLink" href="/tests/dragAndDrop/03-dragObjectAndTargetObject.html">See Example #3: a dragable object with a drop target</a></p>
<p>Note that in the above example, the time that the draggable object&#8217;s <code>dragend</code> event fires and the time that the drag target&#8217;s <code>drop</code> event fires is not consistant among browsers.  Safari and Chrome fire <code>dragend</code> first, while Firefox and Internet Explorer fire <code>drop</code> first.</p>
<p>The two other drop target events, <code>dragenter</code> and <code>dragleave</code> are not absolutely necessary for every script, but let&#8217;s add these events to example #3 anyway to see how they work:</p>
<blockquote class="code">
<pre>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);
<span class="hilite">      EventHelpers.addEvent(targetNode, 'dragenter', dragEnterEvent);
      EventHelpers.addEvent(targetNode, 'dragleave', dragLeaveEvent);</span>
   }

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

   function dragEvent(e) {
      dragEventNoticeNode.innerHTML = "Currently dragging.&lt;br /&gt;";
   }

   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);

   }

<span class="hilite">   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);
   }</span>

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

}

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

EventHelpers.addPageLoadEvent('dragObject.init');</pre>
</blockquote>
<p><a class="exampleLink" href="/tests/dragAndDrop/03a-dragEnterDragLeave.html">See Example #3a: a drop target with dragenter and dragleave event handlers</a></p>
<p>(Note that in Firefox 3.5, a <code>dragleave</code> event will fire just before a <code>drop</code> event, which the other browsers don&#8217;t fire <code>dragleave</code> when dropping).</p>
<h3>Step 4: Passing Data Between the Draggable and Target Objects</h3>
<p>Once a draggable object is dropped into a drop target, the two objects can pass information between them using the drop event&#8217;s <code>dataTransfer</code> property.  This property has two methods, <code>setData()</code> and <code>getData()</code>.  In order to pass data between the two, a developer must use <code>setData()</code> during one of the draggable node&#8217;s drag events (e.g. <code>dragstart</code>).  The drop target can then receive this data during one of it&#8217;s events using the <code>getData()</code> method.</p>
<table class="dataTable" border="0">
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="methodName"><code>setData(dataType, data)</code></td>
<td>
<p>Sets the data that can be shared between the draggable node and the drag target.</p>
<p><strong>Parameters</strong></p>
<ul>
<li><code>dataType</code> &#8211; The type of data that is to be set.  So far, the only cross-browser dataTypes that can be set are &#8216;Text&#8217; and &#8216;Url&#8217;.</li>
<li><code>data</code> &#8211; The data that is going to be set.</li>
</ul>
</td>
</tr>
<tr>
<td class="methodName"><code>getData(dataType)</code></td>
<td>
<p>Gets the data that was previously set by <code>dataTransfer.setData()</code>.  <strong>It can also get data that was set by a <code>dataTransfer.setData()</code> call from another page, another browser window, and <em>another vendor&#8217;s web browser on the same machine</em>.</strong> It also can get data that was set by a drop event of another desktop application (for example, Windows WordPad).</p>
<p><strong>Parameters</strong></p>
<ul>
<li><code>dataType</code> &#8211; The type of data that is to be set.  So far, the only cross-browser dataTypes that can be set are &#8216;Text&#8217; and &#8216;Url&#8217;.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p><code>setData()</code> takes one string parameter, which is the data you want to share between the draggable object and a drop target.</p>
<p>Let&#8217;s take the code from step #3 and mix it up a bit: instead of having one draggable object, let&#8217;s make four.  I have taken <a href="http://commons.wikimedia.org/wiki/File:The_Fabs.JPG">four photos of the Beatles from the Wikmedia Commons</a> and made them draggable.</p>
<blockquote class="code">
<pre>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
   &lt;head&gt;
      &lt;title&gt;Test 4: setData() and getData()&lt;/title&gt;
      &lt;script type="text/javascript" src="../../shared/js/sprintf.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="../../shared/js/helpers.js"&gt;&lt;/script&gt;
      &lt;script type="text/javascript" src="../../shared/js/DragDropHelpers.js"&gt;&lt;/script&gt;

<span class="hilite">      &lt;script type="text/javascript" src="js/04-setDataGetData.js"&gt;&lt;/script&gt;</span>

      &lt;link rel="stylesheet" type="text/css" media="screen" href="css/test1.css" /&gt;

   &lt;/head&gt;
   &lt;body&gt;

      &lt;h1&gt;Test 4: &lt;code&gt;setData()&lt;/code&gt; and &lt;code&gt;getData()&lt;/code&gt;&lt;/h1&gt;

<span class="hilite">      &lt;img draggable="true" src="images/george.png" alt="George Harrison" /&gt;
      &lt;img draggable="true" src="images/john.png" alt="John Lennon" /&gt;
      &lt;img draggable="true" src="images/paul.png" alt="Paul McCartney" /&gt;
      &lt;img draggable="true" src="images/ringo.png" alt="Ringo Starr" /&gt;</span>

      &lt;div id="dropTarget"&gt;&lt;span&gt;Drop an image here to find out more information about it.&lt;/span&gt;&lt;/div&gt;

   &lt;/body&gt;
&lt;/html&gt;</pre>
</blockquote>
<p>The script <code>04-setDataGetData.js</code> uses <code>dataTransfer.setData()</code> and <code>.getData()</code> to copy the <code>&lt;img&gt;</code> of the Beatle being dragged, as well as placing the <code>alt</code> attribute&#8217;s contents underneath the image.</p>
<blockquote class="code">
<pre>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 &lt; 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) {
<span class="hilite">      e.dataTransfer.setData('Text',
         sprintf('&lt;img src="%s" alt="%s" /&gt;&lt;br /&gt;&lt;p class="caption"&gt;%s&lt;/p&gt;',
            this.src, this.alt, this.alt
         )
      );</span>
   }

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

   function dropEvent(e) {
<span class="hilite">      this.innerHTML = e.dataTransfer.getData('Text');</span>
      EventHelpers.preventDefault(e);
   }

}

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

EventHelpers.addPageLoadEvent('dragObject.init');</pre>
</blockquote>
<p><a class="exampleLink" href="/tests/dragAndDrop/04-setDataGetData.html">See Example #4: using setData() and getData()</a></p>
<p>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&#8217;ll see the data that was given to setData() during the dragstart event.</p>
<p>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.</p>
<h3>Step 5: Drag  and  Drop Effects</h3>
<p>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 &#8220;copy objects&#8221; to only drop on drop targets that are programmed to accept them.</p>
<p>These features can be implemented using <code>e.dataTransfer.effectAllowed</code> on the draggable object and <code>e.dataTransfer.dropEffect()</code>on the drop target:</p>
<table class="dataTable" border="0">
<thead>
<tr>
<th>Method</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>e.dataTransfer.effectAllowed</code></td>
<td>Sets the type of effect a draggable object is allowed to make.  Valid values are  <code>copy</code>, <code>move</code>, <code>link</code>, <code>copyMove</code>, <code>copyLink</code>, <code>linkMove</code>, <code>all</code>, and <code>none</code>.</td>
</tr>
<tr>
<td><code>e.dataTransfer.dropEffect</code></td>
<td>Sets the type of effect a drop target is allowed to accept.  Valid effects include <code>copy</code>, <code>move</code>, and <code>link</code>.</td>
</tr>
</tbody>
</table>
<p>When these are set correctly, drag and drop will only work when the draggable object&#8217;s <code>effectAllowed</code> and the drop target&#8217;s <code>dropEffect</code> are compatible.  To illustrate this, let&#8217;s first change the <code>dragstart</code> and <code>dragover</code> events in example #4 to do the <code>copy</code> effect:</p>
<blockquote class="code">
<pre>   function dragStartEvent(e) {
<span class="hilite">      e.dataTransfer.effectAllowed="copy";</span> 

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

   function dragOverEvent(e) {
<span class="hilite">      e.dataTransfer.dropEffect = "copy";</span>
      EventHelpers.preventDefault(e);
   }</pre>
</blockquote>
<p><a class="exampleLink" href="/tests/dragAndDrop/05-dataTransfer.html">Example #5: matching drag and drop effects</a></p>
<p>Note that unlike <a href="/tests/dragAndDrop/04-setDataGetData.html">example #4</a>, the mouse pointer has changed from the copy icon (in Windows, <img class="alignnone size-full wp-image-616" title="Windows Copy Icon" src="http://www.useragentman.com/blog/wp-content/uploads/2010/01/copyWindows.gif" alt="[Windows Copy Icon]" width="23" height="32" />) to the move icon (<img class="alignnone size-full wp-image-615" title="Windows Move Icon" src="http://www.useragentman.com/blog/wp-content/uploads/2010/01/moveWindows.gif" alt="[Windows Move Icon]" width="13" height="27" />).</p>
<p>Now let&#8217;s change the code so that the draggable object and the drop target don&#8217;t have matching effects:</p>
<blockquote class="code">
<pre>   function dragStartEvent(e) {
<span class="hilite">      e.dataTransfer.effectAllowed="copy";</span> 

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

   function dragOverEvent(e) {
<span class="hilite">      e.dataTransfer.dropEffect = "move";</span>
      EventHelpers.preventDefault(e);
   }</pre>
</blockquote>
<p><a class="exampleLink" href="/tests/dragAndDrop/05a-dataTransferNoMatch.html">See Example #5a: unmatching drag and drop effects</a></p>
<p>You&#8217;ll see that the user is not able to drop the image on the drop target.</p>
<p><strong>Update (Jan 28, 2010):</strong>  There is a documented bug in Safari and Chrome for Windows where <a href="http://code.google.com/p/chromium/issues/detail?id=14654">drag and drop will not occur if <code>effectAllowed</code> and <code>dropEffect</code> are set to <code>move</code></a>.  This bug does not occur in the Mac editions of these browsers.  </p>
</div>
<h2>A More Complex Example</h2>
<p>Let&#8217;s take all the information we have gathered and make a &#8220;real-world&#8221; script. Let&#8217;s say you were asked to create a &#8220;user entitlement&#8221; administration widget for a website.  The widget will have three entitlement catagories: &#8220;Unassigned Users&#8221;, &#8220;Restricted Users&#8221; (e.g. users who have restricted access to the website) and &#8220;Power Users&#8221; (e.g. users who would have administration access to a website):</p>
<div id="attachment_684" class="wp-caption aligncenter" style="width: 403px"><img class="size-full wp-image-684" title="permissionFormScreenshot" src="http://www.useragentman.com/blog/wp-content/uploads/2010/01/permissionFormScreenshot1.png" alt="Screenshot of the user entitlement screen we want to implement" width="393" height="185" /><p class="wp-caption-text">Screenshot of the user entitlement screen we want to implement</p></div>
<p>It should be rather easy for an administrator to drag and drop users back and forth between entitlement &#8220;buckets&#8221; in order to elevate or lower a users credentials.</p>
<p>Let&#8217;s go through the steps we established above to implement this script.</p>
<div class="steps">
<h3>Step 1: Defining a Draggable Objects</h3>
<p>First let&#8217;s take a look at the table in the HTML:</p>
<blockquote class="code">
<pre>&lt;table&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;Unassigned Users&lt;/th&gt;
            &lt;th&gt;Restricted Users&lt;/th&gt;
            &lt;th&gt;Power Users&lt;/th&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;

    &lt;tbody&gt;
        &lt;tr&gt;
            &lt;td id="unassignedUsers"&gt;
            	&lt;a href="#" draggable="true"&gt;Moe Howard&lt;/a&gt;
		&lt;a href="#" draggable="true"&gt;Curly Howard&lt;/a&gt;
		&lt;a href="#" draggable="true"&gt;Shemp Howard&lt;/a&gt;
            	&lt;a href="#" draggable="true"&gt;Larry Fine&lt;/a&gt;
	    &lt;/td&gt;

            &lt;td id="restrictedUsers"&gt;
            &lt;/td&gt;

            &lt;td id="powerUsers"&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/tbody&gt;
    &lt;tfoot&gt;
	&lt;td id="unassignedUsersHelp"&gt;
	  Drag a user from this list to another list to change the
	  user's permissions.
	&lt;/td&gt;
	&lt;td id="restrictedUsersHelp"&gt;
	  Dragging user here will give this user restricted
	  permissions.
	&lt;/td&gt;
	&lt;td id="powerUsersHelp" &gt;
	  Dragging a user here will give this user power user access.
	&lt;/td&gt;
    &lt;/tfoot&gt;
&lt;/table&gt;</pre>
</blockquote>
<p>(Note that the contents in the <code>tfoot</code> node are hidden by CSS).</p>
<h3>Step 2: Setting Events on the Draggable Objects</h3>
<p>The &#8220;users&#8221; are draggable objects.  In the script, we find all these nodes using Dean Edwards&#8217; <a href="http://dean.edwards.name/my/cssQuery/">cssQuery</a> and  set <code>dragstart</code> and <code>dragend</code> event handlers on each of them (Note: cssQuery allows us to select nodes by CSS selector, similar to the built-in functionality inside jQuery).</p>
<blockquote class="code">
<pre>userNodes = cssQuery('[draggable=true]');
for (var i=0; i&lt;userNodes.length; i++) {
   EventHelpers.addEvent(userNodes[i], 'dragstart', userDragStartEvent);
   EventHelpers.addEvent(userNodes[i], 'dragend', userDragEndEvent);
}</pre>
</blockquote>
<p>It then keeps track of the current node being dragged in the object variable <code>currentlyDraggedNode</code> and makes that node transparent by making it a member of the <code>draggedUser</code> class, which the page&#8217;s stylesheet defines as transparent.</p>
<blockquote class="code">
<pre>function userDragStartEvent(e) {
   currentlyDraggedNode = this;
   currentlyDraggedNode.className = 'draggedUser';
}</pre>
</blockquote>
<p>The <code>dragend</code> event removes the transparency of the <code>currentlyDraggedNode</code>:</p>
<blockquote class="code">
<pre>function userDragEndEvent(e) {
   currentlyDraggedNode.className = '';
}</pre>
</blockquote>
<h3>Step 3: Setting Events on the Target Objects</h3>
<p>All the table cells in the <code>&lt;tbody&gt;</code> are drop targets, so we use cssQuery again to grab all those nodes and set the appropriate events.</p>
<blockquote class="code">
<pre>userListNodes = cssQuery('.userList');

for (var i=0; i&lt;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);
}</pre>
</blockquote>
<p>The most important event is the <code>drop</code> event handler.  This event handler takes the <code>currentlyDraggedNode</code>, removes it from its current table cell (using <code>removeChild()</code>) and  drops it into the drop target (using <code>appendChild()</code>).</p>
<blockquote class="code">
<pre>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);
}</pre>
</blockquote>
<p>They show the contents of the table cell below it by making it a member of the class <code>showHelp</code>.  They also</p>
<p>prevent the <code>dragover</code> default behaviour so that <code>drop</code> events will fire in the drop target.</p>
<blockquote class="code">
<pre>function userDragOverListEvent(e) {
   setHelpVisibility(this, true);
   EventHelpers.preventDefault(e);
}</pre>
</blockquote>
<p>The <code>dragleave</code> re-hides the contents of the table cell below it.</p>
<blockquote class="code">
<pre>function userDragLeaveListEvent(e) {
  setHelpVisibility(this, false);
}</pre>
</blockquote>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 4921px; width: 1px; height: 1px;">
<pre>function userDragEndEvent(e) {
   currentlyDraggedNode.className = '';
}</pre>
</div>
<h3>Steps 4 and 5</h3>
<p>We do not actually pass any data between the draggable object and the drag target — when the <code>drop</code> event occurs, the draggable object is moved from one column to another without the need of any <code>dataTransfer</code> data.  The drag and drop effects were already handled in step 3, so we are all done.</p>
<p><a class="exampleLink" href="/tests/dragAndDrop/permissionForm.html">See the above example in action</a></p>
</div>
<h2>Drag and Drop Between Frames</h2>
<p>Using the above information, it is also possible to drag and drop objects between frames (this is something that I don&#8217;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.</p>
<p><a class="exampleLink" href="/tests/dragAndDrop/05a-crossFrameSetData/">See the inter-frame drag and drop example in action</a></p>
<h2>Cross-Browser Issues I Have Seen</h2>
<p>These are the cross-browser issues I know of so far.  I will update this list with others I find in the future.</p>
<ul>
<li>in Firefox 3.5, a <code>dragleave</code> event will fire just before a <code>drop</code> event, which the other browsers don’t fire <code>dragleave</code> when dropping.</li>
<li>the time that the draggable object’s <code>dragend</code> event fires and the time that the drag target’s <code>drop</code> event fires is not consistant among browsers. Safari and Chrome fire <code>dragend</code> first, while Firefox and Internet Explorer fire <code>drop</code> first.</li>
<li>According to <a href="http://www.alertdebugging.com/drag-and-drop-bugs/">Francisco Tolmasky</a>, <a href="http://www.alertdebugging.com/drag-and-drop-bugs/"><code>setData()</code> cannot be called during drag events in Firefox</a>.  Hopefully this will be fixed in a future release of the browser.</li>
<li><code>DragDropHelpers</code> implements a workaround for Explorer so it can drag <em>any</em> object around. However, I did not use this functionality in any of the examples because it exposes a problem with <a href="http://lists.apple.com/archives/web-dev/2009/Jul/msg00042.html">Safari not being able to drag an object correctly when the user initiates the drag on the text inside it</a>.  This problem doesn&#8217;t happen with text inside of links, but with text inside other nodes (like a <code>&lt;div&gt;</code> 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.</li>
<li>DragDropHelpers.js &#8220;fixes&#8221; the dragging visual cues in Explorer and Chrome by:
<ul>
<li>making a transparent and absolutely positioned clone of a draggable object when it&#8217;s <code>dragstart</code> event is fired</li>
<li>moving the cloned object near the mouse when the <code>&lt;body&gt;</code>&#8216;s <code>drag</code> event is fired.</li>
<li>destroying the clone when draggable object&#8217;s <code>dragend</code> event is fired.</li>
</ul>
<p>I didn&#8217;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&#8217;t work well when dragging objects from one window or frame to another, since the cloned visual cue can&#8217;t jump from page to page.  Feel free to use it (or not) as you see fit.</li>
<li>As mentioned previously, because of a <a href="http://code.google.com/p/chromium/issues/detail?id=14654">bug in Webkit</a>, drag and drop will not occur if <code>effectAllowed</code> and <code>dropEffect</code>  are set to <code>move</code> in Safari 4.0.4.  Hopefully this will be fixed in a future version of Webkit.</li>
</ul>
<h2>Conclusion</h2>
<p>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 &#8211; 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 &#8220;what the hell are you doing up at this hour&#8221; look, so I think I&#8217;ll stop here for now.</p>
<h2>Download</h2>
<p><code>DragDropHelpers</code>, and all code used in this article can be downloaded below.</p>
<p><a class="exampleLink" href="/downloads/DragDropHelpers-1.0a.zip">DragDropHelpers.js v.1.0a and sample code.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
	</channel>
</rss>
