开发者

jQuery Dropdown Menu Functionality based on Click Events (hiding help)

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开发者_JS百科 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.


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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜