azolotov
azolotov

Reputation: 203

Is there a way to simplify this jquery?

I wrote a dropdown menu with the following structure. It is supposed to drop down on click, and close on click.

Here's the HTML

<ul id="nav" class="nav">
    <li>
        <a id="menu1" class="menu">MENU 1</a> <!-- top menu -->
        <div id="submenu1" class="submenu"> <!-- hidden by default -->
            <a href="#">SUBMENU ITEM 1</a> <!-- submenu item -->
            <a href="#">SUBMENU ITEM 2</a>
        </div>
    </li>

    <li>
        <a id="menu2" class="menu">MENU 2</a>
        <div id="submenu2" class="submenu">
            <a href="#">SUBMENU ITEM 1</a>
            <a href="#">SUBMENU ITEM 2</a>
            <a href="#">SUBMENU ITEM 2</a>
        </div>
    </li>
</ul>

And that's the JavaScript (using jQuery)

$("#menu1").click(function() {
    $("div.submenu").hide(); // hide all menus
    $("#submenu1").toggle(); // open this menu
});
$("#menu2").click(function() {
    $("div.submenu").hide(); // hide all menus
    $("#submenu2").toggle(); // open this menu
});
$("#menu3").click(function() {
    $("div.submenu").hide(); // hide all menus
    $("#submenu3").toggle(); // open this menu
});
$("#menu4").click(function() {
    $("div.submenu").hide(); // hide all menus
    $("#submenu4").toggle(); // open this menu
});

$(document).bind('click', function(e) {
    var $clicked = $(e.target);
    if (! $clicked.parents().hasClass("nav"))
    $("div.submenu").hide();
});

There is a lot of repetition in the first part of the JS, is there a way to make this shorter, nicer, better?

Upvotes: 2

Views: 217

Answers (2)

Guffa
Guffa

Reputation: 700342

You should be able to reduce the script to:

$(".nav .menu").click(function() {
   $("div.submenu").hide(); // hide all menus
   $(this).next().toggle(); // open this menu
});
$(document).click(function(e) {
    if (! $(e.target).parents().hasClass("nav"))
    $("div.submenu").hide();
});

Upvotes: 7

Doug Neiner
Doug Neiner

Reputation: 66191

Yes:

var $submenus = $('.submenu');

$(".menu").click(function(e){
    var $menu = $(this).next('.submenu').toggle();
    $submenus.not('#' + $menu[0].id).hide();
    e.preventDefault();
});

$(document).click(function(e){
    if( !$(e.target).closest('.nav').length ) $submenus.hide();
});

Upvotes: 0

Related Questions