Learning jQuery - Fourth Edition by Jonathan Chaffer & Karl Swedberg

Learning jQuery - Fourth Edition by Jonathan Chaffer & Karl Swedberg

Author:Jonathan Chaffer & Karl Swedberg
Language: eng
Format: azw3, epub
ISBN: 9781782163145
Publisher: Packt Publishing
Published: 2013-06-24T21:00:00+00:00


Tip

The jQuery.fn object is an alias to jQuery.prototype, provided for conciseness.

We can then call this new method from our code after using any selector expression:

$('div').myMethod();

Our alert is displayed (once for each <div> in the document) when we invoke the method. We might as well have written a global function, though, as we haven't used the matched DOM nodes in any way. A reasonable method implementation acts on its context.

Object method context

Within any plugin method, the keyword this is set to the current jQuery object. Therefore, we can call any built-in jQuery method on this or extract its DOM nodes and work on them. To examine what we can do with object context, we'll write a small plugin to manipulate the classes on the matched elements.

Our new method will take two class names and swap which class is applied to each element with every invocation. While jQuery UI has a robust .switchClass() method that even permits animating the class change, we'll provide a simple implementation for demonstration purposes:

// Unfinished code (function($) { $.fn.swapClass = function(class1, class2) { if (this.hasClass(class1)) { this.removeClass(class1).addClass(class2); } else if (this.hasClass(class2)) { this.removeClass(class2).addClass(class1); } }; })(jQuery); $(document).ready(function() { $('table').click(function() { $('tr').swapClass('one', 'two'); }); });



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.