Coder’s Eye

A site about one of the three passions in my life.

Coder’s Eye header image 2

jQuery Selector Magic

February 27th, 2007 · 1 Comment

jQuery makes me feel like I am playingI’ve been working on a Drupal module to automatically make CSS-styled drop-down menus from the built-in menuing system. That’s been going great, and I’m really enjoying Drupal’s modular architecture and theming abilities. However, I ran into a little problem which was solved just perfectly by an elegant bit of jQuery Javascript.

What I wanted to do was to mark a list active if any of its children were active. That’s a common design request. “Make this tab active if the current page is one of that tab’s children.” However, I’d written the menu routines recursively, and it just isn’t worth it to me to rewrite them to add this one little feature.

Yay jQuery

Here’s the structure. An outer div with class “sssmenu”. Inner “ul” comprising the top level, whose “li” elements all have the class=”menutitle”. Child li may have the class “active”. Like so, only skipping the angle brackets.

[div class="sssmenu"]
    [ul]
        [li class="menutitle"]Tab 1
          [ul]
              [li]sub 1[/li]
              [li]sub 2[/li]
              [li]sub 3[/li]
          [/ul]
        [/li]
        [li class="menutitle"]Tab 2
          [ul]
              [li]sub 1[/li]
              [li class="active"]sub 2[/li]
              [li]sub 3[/li]
          [/ul]
        [/li]
     [/ul]
[/div]

Now, with one clean looking jQuery statement, I can make Tab 2 “active”.

$('.sssmenu li.menutitle[li.active]').addClass('active');

Basically, that says “For every li.menutitle child of .sssmenu, if that li has an li descendant with class “active”, add “active” to your class. Resulting in something like this:

[div class="sssmenu"]
    [ul]
        [li class="menutitle"]Tab 1
          [ul]
              [li]sub 1[/li]
              [li]sub 2[/li]
              [li]sub 3[/li]
          [/ul]
        [/li]
        [li class="menutitle active"]Tab 2
          [ul]
              [li]sub 1[/li]
              [li class="active"]sub 2[/li]
              [li]sub 3[/li]
          [/ul]
        [/li]
     [/ul]
[/div]

Technorati Tags: , , , ,

Tags: CSS · Javascript

Bookmark this article

del.icio.us:jQuery Selector Magic digg:jQuery Selector Magic spurl:jQuery Selector Magic wists:jQuery Selector Magic simpy:jQuery Selector Magic newsvine:jQuery Selector Magic blinklist:jQuery Selector Magic furl:jQuery Selector Magic reddit:jQuery Selector Magic fark:jQuery Selector Magic blogmarks:jQuery Selector Magic Y!:jQuery Selector Magic smarking:jQuery Selector Magic magnolia:jQuery Selector Magic segnalo:jQuery Selector Magic gifttagging:jQuery Selector Magic

1 response so far ↓

Leave a Comment