Web Development with jQuery®

(Elliott) #1

(^324) ❘ CHAPTER 12 DRAGGABLE AND DROPPABLE
The Draggable and Droppable jQuery UI libraries provide similar functionality, but this function-
ality is limited to working within one browser window. Its functionality does not allow dragged
content to leave the boundaries of the browser window. Whichever you choose to use depends upon
what your project goals include for functionality.
The Draggable library gives you the ability to make any element on a page draggable. In the most
rudimentary sense, that means you can move elements around in a document with your mouse and
arrange those elements however you like. The next section introduces the Draggable jQuery UI API.


Making Elements Draggable


Making an element draggable is easy: First, you need to include the UI library that includes the
Draggable plugin; then, after you make a selection with jQuery, you simply chain the method
draggable() to the selection, like so:

$('div#anElementIdLikeToDrag').draggable();

The preceding code makes the <div> element with the id name anElementIdLikeToDrag, a draggable
element, which means that you can move the element anywhere in the document with your mouse.
The ability to make elements draggable gives you more options in terms of how your applications
function, giving you many of the same options that you have developing desktop applications.

The actual code behind the scenes, enabling the drag operation, isn’t complex, but it’s yet another
thing that jQuery allows you to take several lines of code and compress them into little code. In this
case, it’s a simple function call.

To show you just how easy it is to make an element draggable, the following presents an example
in which you create a fi le manager that looks somewhat like Mac OS X Finder. You begin with the
XHTML5 base, which is presented in the following markup (Example 12-1):

<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='content-type'
content='application/xhtml+xml; charset=utf-8' />
<meta http-equiv='content-language' content='en-us' />
<title>Finder</title>
<script src='../jQuery.js'></script>
<script src='../jQueryUI.js'></script>
<script src='Example 12-1.js'></script>
<link href='Example 12-1.css' rel='stylesheet' />
</head>
<body>
<div id='finderFiles'>
<div class='finderDirectory' data-path='/Applications'>
<div class='finderIcon'></div>
<div class='finderDirectoryName'>
<span>Applications</span>
</div>
</div>
<div class='finderDirectory' data-path='/Library'>

http://www.it-ebooks.info

Free download pdf