Web Development with jQuery®

(Elliott) #1

Writing a Plugin (^) ❘ 247
$.fn.extend({
select : function()
{
// In a jQuery plugin; 'this' is already a jQuery ready object
// Performing an operation like addClass() works on one
// or more items, depending on the selection.
return this.addClass('movieSelected');
},
unselect : function()
{
return this.removeClass('movieSelected');
}
});
As you’ve been learning throughout the fi rst part of this book, if you have the following jQuery
selection
$('ul.movieList li')
what follows that expression can be any method that jQuery supports. You could call addClass(),
for example, and add a class name to every

  • element that selection matches. With jQuery
    plugins, in addition to all the methods that jQuery supports, such as find(), addClass(), each(),
    and so on, you can also extend jQuery any way that you see fi t with your own custom plugin. In
    Example 9-1, you saw a remedial example, where you’re just adding a class name to every element
    in a selection. The keyword this represents an array, and that array contains every element in the
    selection. In the example of John Candy movies, this contained an array of seven
  • elements, so
    when the following plugin executed
    select : function()
    {
    // In a jQuery plugin; 'this' is already a jQuery ready object
    // Performing an operation like addClass() works on one
    // or more items, depending on the selection.
    return this.addClass('movieSelected');
    }
    it did so on this collection of
  • elements:


  • The Great Outdoors

  • Uncle Buck

  • Who’s Harry Crumb?

  • Canadian Bacon

  • Home Alone

  • Spaceballs

  • Planes, Trains, and Automobiles

  • And it added the movieSelected class name to those elements, depending on whether you clicked a
  • element directly, or selected them all using the element beneath the list.
    [http://www.it-ebooks.info](http://www.it-ebooks.info)
  • ← Previous
    Free download pdf