views:

678

answers:

2

I'm having some trouble with the jQuery hover method.

Here's the relevant JavaScript code:

$("#navigation > li > ul").hide();
$("#navigation > li").hover(
    function() {
        $(this).children("ul").slideDown(125);
    },
    function() {
        $(this).children("ul").slideUp(125);
    }
);

Here's the corresponding HTML:

<ul id="navigation">
    <li><a href="#">Top Level Item #1</a></li>
    <li>
        <a href="#">Top Level Item #2</a>
        <ul>
            <li><a href="#">Sub-Menu Item #2-1</a></li>
            <li><a href="#">Sub-Menu Item #2-2</a></li>
            <li><a href="#">Sub-Menu Item #2-3</a></li>
        </ul>
    </li>
</ul>

Whenever you mouseover a top-level item, the submenu in it (if any) will drop down with a nice, quick slide effect. The problem is when you mouseover "into" the menu quickly and keep your mouse where the menu would be but hasn't reached yet: the menu will then hit the "end" of the mouseover animation and bounce back up to the hidden state, and repeat until you remove the mouse from where the dropdown menu would be.

+2  A: 

Maybe adding a check in the mouseout function could help:

if( !$(this).children("ul").is(":animated") ){
  $(this).children("ul").slideUp(125);
}
Seb
You da man! This worked, thanks a ton!
Zack
Glad I could help :)
Seb
A: 

You could try using hoventIntent, a jQuery plugin that helps with detecting the intent of a user hovering over elements.

http://cherne.net/brian/resources/jquery.hoverIntent.html

I modified your example with it and it seems to behave much nicer. I added:

<script type="text/javascript" language="JavaScript" src="jquery.hoverIntent.minified.js"></script>

and modified the single line with hover() to:

$("#navigation > li").hoverIntent(

I couldn't get it to bounce, and it felt more like a popout menu with the hoverIntent behavior applied.

Lastly, you could try using one of the pre-built jQuery menu plugins as they did all this hard work for you already :)

wojo
I'll have to look into plug-ins more once I get a good handle on jQuery, I'm still reinventing the wheel a lot so I can understand the how and why of it a bit better. Thanks for the suggestion, I've already bookmarked it :>
Zack
Good method of learning!
wojo