Web Development with jQuery®

(Elliott) #1

(^288) ❘ CHAPTER 11 HTML5 DRAG AND DROP
elements present in this using each(). jQuery always passes elements to plugins as an
array, never as a single element, to make working with jQuery and writing plugins for
jQuery simpler.
Drag-and-drop functionality is fi rst enabled in older WebKit-based browsers, such as Safari and
Chrome. (It is worth noting that the order in which these methods are used isn’t important, though.)
To enable drag and drop in older WebKit-based browsers, the proprietary CSS property -web-
kit-user-drag is set to the value element. But before you set the value, you fi rst test the CSS property
to see if it exists by looking for whether the typeof is undefined. If the property exists, the typeof
will not be undefined, but will instead be string.
if (typeof this.style.WebkitUserDrag != 'undefined')
{
this.style.WebkitUserDrag = 'element';
}
When you set a proprietary CSS property in JavaScript, the hyphens are omitted, and the fi rst letter
is capitalized, so –webkit-user-drag becomes WebkitUserDrag. If it were a property implemented in
Firefox, you’d have –moz-user-drag and MozUserDrag, instead.
Next, you check for the existence of the draggable attribute. The draggable attribute is recom-
mended by the W3C HTML 5 drag-and-drop specifi cation as the offi cial way to enable drag and
drop. This attribute is supported in the latest versions of Safari, Chrome, Firefox, and Internet
Explorer. Like the CSS property, you must check to see if the typeof is not undefined to see if the
attribute is implemented in the browser.
if (typeof this.draggable != 'undefined')
{
this.draggable = true;
}
The draggable attribute is a boolean attribute. Setting it to true enables drag and drop of the ele-
ment, and setting it to false disables drag and drop. The behavior that you get by setting either the
WebkitUserDrag CSS property or draggable attribute is default behavior. Typically, you can move the
element around, but nothing happens when you drop it because that behavior has to be defi ned with
JavaScript.
The last method of enabling drag and drop is used for older versions of Internet Explorer. Internet
Explorer 9 and later implement the newer HTML 5 drag-and-drop specifi cation and require using
the draggable attribute instead of the legacy method used here. To enable drag and drop in IE8
and earlier, fi rst test for the existence of the dragDrop method. Test to see if the typeof the dragDrop
method is function to fi nd out whether you can use it. (You can also check to see if the typeof is not
undefined like the CSS property and the HTML attribute, if you like.)
if (typeof this.dragDrop == 'function')
{
this.dragDrop();
}
If the dragDrop method exists, simply calling it on the element enables drag and drop on that element
in IE8 and earlier.
http://www.it-ebooks.info

Free download pdf