Web Development with jQuery®

(Elliott) #1

(^246) ❘ CHAPTER 9 PLUGINS
movies.ready();
}
);
The preceding code results in the screen shot that you see in Figure 9-1 when you click individual
movie titles.


FIGURE 9-1


In the preceding example, you see how jQuery plugins are written using the $.fn.extend()
method. In essence, a jQuery plugin extends what you can do with an object representing an HTML
element. In this case, you’re creating two jQuery plugins, one for selecting an element and one for
unselecting an element. The selection itself is by virtue of applying a class name to one of the <li>
elements. If the <li> element is selected, it has the class name movieSelected applied. If the <li>
element is not selected, then the class name movieSelected is withdrawn. And just so you can visu-
ally see that an item is selected, the movieSelected class name applies a forestgreen background and
makes the text white. This is a really simple example of what can be done using a jQuery plugin;
you take one or more HTML elements and do something directly to those elements. In this example,
you’re doing selection, but you can do much more complicated things with jQuery plugins. You can
have a plugin that adds a calendar to an input element; you can have a plugin that makes an element
a drop zone for drag and drop actions. You’ll see many more examples of jQuery plugins through-
out this book; some are plugins developed by the jQuery Foundation, such as jQuery UI, and others
are great third-party plugins that add useful functionality, such as the ability to sort a table, which
you’ll take a look at in Chapter 20, “Creating an Interactive Slideshow.”

The Anatomy of a jQuery Plugin


A jQuery plugin’s primary purpose is to do something to an element in the DOM. Within a plugin,
the special keyword this represents the element or elements that you are working with. In Example
9-1, you had two plugins, select() and unselect(). These jQuery plugins can be called on any
HTML element in the DOM through jQuery. The plugin works on one element or many elements.

http://www.it-ebooks.info

Free download pdf