jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
jQuery Cookbook - Cdn.oreilly.com - O'Reilly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
other siblings (div#one and div#three)<br />
$('#two,#four').radioClass('hilite');<br />
Solution<br />
Write a simple plugin to add the .radioClass() method to <strong>jQuery</strong>:<br />
// Remove the specified class from every sibling of the selected<br />
// element(s), then add that class to the selected element(s).<br />
// Doing it in that order allows multiple siblings to be selected.<br />
//<br />
// Thanks to Ext Core for the idea.<br />
<strong>jQuery</strong>.fn.radioClass = function( cls ) {<br />
return this.siblings().removeClass(cls).end().addClass(cls);<br />
};<br />
This is a short enough function that it’s not too hard to follow as a one-liner, but<br />
indenting the code as described in Recipe 5.4 makes it <strong>com</strong>pletely clear how it works:<br />
<strong>jQuery</strong>.fn.radioClass = function( cls ) {<br />
return this // Start chain, will return its result<br />
.siblings() // Select all siblings of selected elements<br />
.removeClass(cls) // Remove class from those siblings<br />
.end() // Go back to original selection<br />
.addClass(cls); // Add class to selected elements<br />
};<br />
Discussion<br />
The <strong>com</strong>poser Igor Stravinsky is reported to have said, “Good <strong>com</strong>posers borrow; great<br />
<strong>com</strong>posers steal.” He apparently stole the quote from T.S. Eliot, who wrote, “Immature<br />
poets imitate; mature poets steal.”<br />
Good ideas <strong>com</strong>e from many places, and other JavaScript libraries are chock-full of<br />
good code and ideas. If there is code in another open source library that you can use<br />
or that you can translate to work with <strong>jQuery</strong>, you’re free to do that—if you respect<br />
the other author’s copyright and license.<br />
For information on open source and free software, see the following<br />
sites:<br />
• http://www.opensource.org/<br />
• http://www.fsf.org/<br />
You may not even need the actual code in a case like this one, where the implementation<br />
is very simple and just the idea of having a “radio class” method is the missing link.<br />
While not required, it’s a good courtesy to give credit to the source of the idea.<br />
5.5 Borrowing Code from Other Libraries | 95