How to prevent sub-menu items from closing sub-menu?

jquery

#1

I have a seemingly simple dropdown menu with some sub-menus. My problem is that I can open the dropdown submenu (the "my dropdown li"'s) but when I got to click on any of them it hides the submenu and goes back to the main menu (home, about, contact). How to I allow the submenu to be closed when clicking on "home" again (which is working), but NOT when I click on the sub-menu items???

I am by all means the most newest of javascript users so I don't really know where to start. :frowning:

HTML

<ul id="nav">
    <li class="dropdown"><a href="#">Home</a>
    <ul>
    <li><a href="#">My Dropdown li</a></li>
    <li><a href="#">My Dropdown li 2</a></li>
    <li><a href="#">My Dropdown li 3</a></li>
    </ul>
    </li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
</ul>

JAVASCRIPT

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
   $('li.dropdown').click(function() {
   $('li.dropdown').not(this).find('ul').hide();
   $(this).find('ul').toggle();
});
</script>

#2

i put your code in a bin, i added document ready function, which you need when coding jquery

i used a shorthand for find ($("ul", this).toggle();), and then a simply toggle to display/hide the menu


#3

When this is clicked, the default behavior is to follow the link (request the home page resource). This only gets confusing if there is a second behavior. The user is not expecting it.

The real cure for this is an expand/collapse button.

<li class="dropdown"><a href="#">Home</a> <span class="droptoggle">►</span>

$('.droptoggle').click(function() {
    $(this).next().slideToggle();
});

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.