views:

808

answers:

2

I have two jQuery menu's that properly show when clicking on "show".

For example let's say you have two links:

"Show 1", "Show 2"

You click on "Show 1" and then a div appears with "show 1 content"

You click on "Show 2" and then a div appears with "show 2 content"

I have it working to that point.

Obviously there is a couple usability things I need to tackle. If I click on "Show 1" and then click on "Show 2" I want "Show 1's Content" to disappear (hide the "show 1 content" div)

One other thing, if I click anywhere on the page, whichever dropdown is active I want it to hide if I click outside the content box.

My dom structure:

ul
 li.menu
  span= link_to 'Show 1'
  ul.dropdown.hidden
   li= link_to 'show 1 content'
 li.menu
  span= link_to 'Show 2'
  ul.dropdown.hidden
   li= link_to 'show 2 content'

My js:

  $("#search li.menu span a").click(function(event) {
    event.preventDefault();
    $(this).parent().siblings("ul.dropdown").toggleClass("hidden");
  });

So basically I just need to understand how to apply hidden when clicking outside of the ul.dropdown box and how to apply hidden when clicking an OTHER ul.dropdown box

Thanks.

A: 

Add a class to all the elements that need to be hidden. When clicking outside the dropdown box or when clicking on a "Show" link, first hide everything. If it is a "Show" link, then show what needs to be shown.

kgiannakakis
That's what I"m trying to learn. How do you specify "when clicking outside the dropdown box?"
DFischer
I already have a "hidden" class on all elements that need to be hidden. I don't know how to tell jQuery to hide it if clicked outside the ul. If you could specify further that would be great.
DFischer
+2  A: 

You need to bind the click event to the document and check the target (event delegation). If the target is outside the nav, hide the dropdowns and return.

Example:

<ul id="nav">
    <li class="menu">
        <span><a href="#">Show 1</a></span>
        <ul class="dropdown">
            <li><a href="#">Show 1 content</a></li>
        </ul>
    </li>
    <li class="menu">
        <span><a href="#">Show 2</a></span>
        <ul class="dropdown">
            <li><a href="#">Show 2 content</a></li>
        </ul>
    </li>
</ul>
<script>

var nav = $('#nav');
nav.find('ul.dropdown').hide();

$(document).bind('click', function(e) {
    var target = $( e.target );
    if ( target.closest('#nav').length < 1 ) {
        nav.find('ul.dropdown').hide();
        return;
    }
    if ( target.parent().is('span') ) {
        var li = target.closest('li.menu');
        li.siblings().find('ul.dropdown').hide();
        li.find('ul.dropdown').toggle();
        e.preventDefault();
    }
})

</script>
David