Web Development with jQuery®

(Elliott) #1

Implementing Drag and Drop (^) ❘ 287
$.fn.extend({
outerHTML : function()
{
var temporary = $("

").append($(this).clone());
var html = temporary.html();
temporary.remove();
return html;
},
The block of code begins with $.fn.extend(), which as you learned in Chapter 9, “Plugins,” is used
to create jQuery plugins. outerHTML : function() begins the fi rst plugin, which implements out-
erHTML functionality. The block of markup that you want to retrieve the outerHTML from is cloned
using $(this).clone() and is inserted inside a temporary
element. The temporary
is
created using a string "
", which jQuery internally converts to a
element object. The
cloned object is inserted within the
element using the append() method. Then the newly
inserted object is retrieved from the newly created
element using the html() method and is
assigned to the variable named html. The html() method uses the innerHTML property internally,
which is implemented universally, in all browsers. Then the temporary
element is cleaned up
from memory with a call to remove(), which deletes it, and the html source is returned as a string.
The HTML snippet that is returned is now portable and can be transported to anywhere that
supports rendering HTML, or as plain text, using your operating system’s drag-and-drop clipboard.
You learn more about the drag-and-drop clipboard later in this section.
The second plugin that you create enables drag and drop using the three different methods that exist
for doing so since the drag and drop API was fi rst created by Microsoft with the release of IE5.
enableDragAndDrop : function()
{
return this.each(
function()
{
if (typeof this.style.WebkitUserDrag != 'undefined')
{
this.style.WebkitUserDrag = 'element';
}
if (typeof this.draggable != 'undefined')
{
this.draggable = true;
}
if (typeof this.dragDrop == 'function')
{
this.dragDrop();
}
}
);
}
This plugin does not assume that you are working with just one element. Because it may be desir-
able to enable drag and drop on many elements at once, it iterates over the potential collection of
http://www.it-ebooks.info