I’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: jquery, javascript, css, css selectors, dhtml
















1 response so far ↓
1 Jonah Dempcy // Apr 23, 2008 at 4:28 pm
Nice trick!
My colleague Alex posted an article on making tabs with jQuery (not using the jUI plugin). It’s online at this URL:
http://www.thetruetribe.com/2008/04/how-do-i-make-tabs-in-jquery-without-jq.html
Leave a Comment