Code

CSS drop-down menus: keeping the top level selected when hovering over a sub-menu, now in jQuery

Awhile back I wrote a JavaScript tutorial on how to keep the top level menu item selected when hovering over a drop down menu. Since then I’ve become a strong user and proponent of the JavaScript library jQuery. Not only is it easy to use, it also can help simplify your code-base very significantly. I’ve explained the updated code below. As you can see, it is much simpler.

How this works

There are two main components of the JavaScript, first the code for all browsers to keep the top level selected and a second code block to add the hover state for IE6 (since it only supports :hover pseudo-classes on anchors, not list elements as we use here).

First, you’ll need to add the jQuery equivalent of “onLoad”: $(function() {. Fortunately, the multiple onLoad and caching issues we addressed in the earlier tutorial are now handled in jQuery, so no need to use the “onEvent” function from the earlier tutorial. You’ll also sometimes see this as $(document).ready(function() {. The functionality is the same, so feel free to use either syntax.

Code for persistent top-level menu formatting

Next, the general code for maintaining the hover formatting on the top level. Basically, this function iterates through each of the drop-down <ul>s and adds a hover function to each. So, when a user hovers over a drop down menu, jQuery finds the parent of that drop down, finds all anchor tags, slices out all the anchors but the first and, finally, toggles the “active” class.

Internet Explorer 6 functionality

To make this work in IE6, we need to add some additional code. First, we use jQuery’s built in browser sniffer to only target MSIE versions below 7. It then works fundimentally like the code above and the Suckerfish drop downs from the earlier tutorial. JavaScript cycles through each drop-down <ul> and adds a function that tells the its parent anchor tag to take on a particular class when the browser detects a mouseover on the menu.

In closing

Be sure to add the closing parenthesize and bracket for the jQuery on ready state: });.

Complete Code

  • ehud

    look this

  • Joe

    How could you make this multi-level?

  • velu

    thanks

  • fahmi

    hi, your demo page is not found

  • http://www.darrenkrape.com Darren

    @fahmi Just updated the demo page. Looks like files didn’t make the latest migration.