views:

159

answers:

2

I've been trying to practice making sliding menus with slidetoggle, slidedown/up...etc but I can't seem to get this right if I want to hover over the menu.

I've got this so far but it works only on click and it doesn't go away after moving away from the menu item. So I would like to just hover over the main menu item and then drop the dropdowns. Any help is appreciated!!

 <form id="form1" runat="server">


        <div id="multiDropMenu">
            <ul id="menu">
                <li><a href="#" id="places">Places</a>
                    <ul id="dropdown1">
                        <li><a href="http://google.com"&gt;To Go</a></li>
                        <li><a href="#">To See</a></li>
                    </ul>
                </li>
                <li><a href="#">Transportation</a></li>
            </ul>
        </div>

    </form>


    <script type="text/javascript">
        $(document).ready(function() {
            $("#places").toggle(function() { $("#dropdown1").slideDown("fast"); },

                                function() { $("#dropdown1").slideUp("fast"); });


        });

    </script>
A: 

Just change $("#places").toggle to $("#places").hover

See demo here: http://jsfiddle.net/mftWK/

Ender
That goes back to my old problem...the hover functions makes the dropdown1 disappear after you hover-out of the menu item.
Ehsan
oh, i see your problem. Check Nick Craver's answer above. You want to target the parent <li> because that encompasses the child <ul>. Thus, when you move your mouse down to the children, they will continue to be shown, as the targeted <li> is still being hovered over.
Ender
+1  A: 

You can use .hover() on the parent <li> and .slideToggle() since it's a child, like this:

$(function() {
   $("#places").parent().hover(function() { 
      $("#dropdown1").slideToggle("fast"); 
   });
});​

You can give it a try here, this lets you hover anywhere in the <li>, you could also make it much more generic, like this:

 $("#menu li").hover(function() { 
    $(this).find("ul").slideToggle("fast"); 
 });

You can try that version here, it works much better for any number of items, no need for IDs on each.

Nick Craver
Almost! the only problem is the dropdown stays down even when I move over to the next menu item (i.e transportation), it would be logical to have dropdowns slide up once you move out of them or to another menu item...it seems to this in the generic version only...Thanks Nick!
Ehsan
@Ehsan - Woops, I forgot to remove the `.parent()` on the second one, answer updated :)
Nick Craver
Actually I didn't know what parent did but I assumed it was some hierarchy problem so I changed the #menu li to #menu ul...it worked but is this the same thing? What does parent do? Thanks
Ehsan
.parent() selects the parent element of each of the elements in the current selection. In this case, it selects the parent of the #places element, which is the containing <li>. http://api.jquery.com/parent/
Ender