O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.5. Borrowing Code from Other Libraries

Problem

You found a useful function in another JavaScript library and want to use the same technique in your jQuery code. In this case, it’s the .radioClass() method from the Ext Core library, which adds a class to the matching element(s) and removes the same class from all siblings of the matching element(s).

Note

The name .radioClass() comes from the behavior of radio buttons in both web applications and desktop apps, where clicking one button selects it and deselects the other buttons in the same radio button group.

The name radio button for those input elements comes from the station buttons in old car radios—the mechanical ones where pushing in one button caused all of the other buttons to pop out.

Given this HTML:

<div>
    <div id="one" class="hilite">One</div>
    <div id="two">Two</div>
    <div id="three">Three</div>
    <div id="four">Four</div>
</div>

you’d like to run code like this:

// Add the 'hilite' class to div#three, and
// remove the class from all of its siblings
// (e.g. div#one)

$('#three').radioClass('hilite');

You may even want to allow a “multiple-select” radio class:

// Add the 'hilite' class to div#two and
// div#four, and remove the class from the
// other siblings (div#one and div#three)

$('#two,#four').radioClass('hilite');

Solution

Write a simple plugin to add the .radioClass() method to jQuery:

// Remove the specified class from every sibling of the selected // element(s), then add that class to the selected element(s). // Doing it in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required