1

I am trying to add a little animation with jQuery to my navigation bar. Right now I have the sub menus of the nav bar changing from display:none to display:block with the css :hover pseudo-class. As I said, I am trying to do this with jQuery, so I need to create a selector that was similar to the one I used in my css. The selector I was using that would only display it's child list is:

#nav ul li:hover > ul

And this worked perfectly, however I obviously can not use the :hover pseudo-class within a jQuery selector, I have tried to use the .hover() method like this (this is without any animations yet):

 $('#nav ul li').hover(function() {
 $('#nav ul li').children('ul').css('display','block');
 }, function() {
 $('#nav ul li').children('ul').css('display','none');
 });

However, this shows all the sub menus if I hover over any of the list items. Here are a couple of jsfiddle examples:

What it looks like with css (and what I want to recreate with jQuery):http://jsfiddle.net/FHdLC/

The result of the jQuery code above: http://jsfiddle.net/LBK3T/

Thanks very much for any help you can provide!

1 Answer 1

2

Use this to refer to the current element inside the .hover() handlers, like this:

$('#nav ul li').hover(function() {
   $(this).children('ul').css('display','block');
}, function() {
   $(this).children('ul').css('display','none');
});

Here's your example working with the code above :)

Also, you can shorten it down even further using just .toggle(), like this:

$('#nav ul li').hover(function() {
   $(this).children('ul').toggle();
});​

You can test the .toggle() version here

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Nick, seems like you always answer all my jQuery questions, and they always are great answers. Thanks so much, I'll mark this as the correct answer as soon as I am able.
This worked out even better with expected! I used the toggle method, but changed it to "slideToggle()" and achieved my animation effect super easily! Thanks again!
@Ben - Welcome :) if you get animation queue problems (build-up) from rapidly hovering in/out, add a .stop(true, true) just before the .sligeToggle() ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.