Bel Bel - 1 month ago 9
Javascript Question

Javascript dropdown menu onclick, (close others, when one is open)

I have created a dropdown menu for a responsive website.
But I have a small problem. When I click the first menu tab, all tabs open.

DEMO:
https://jsfiddle.net/vth4gn6w/2/

What I want:


  1. When I click on the first tab, I want only that tab to open, without it activating the other tabs.

  2. When I click on the second tab, I want the first tab to close automatically.



Hope somebody can help me, and plz use fiddle to show me how it's done. Thanks

Answer

Which element is being clicked? Not the entire #nav-mobile, but the as inside. You want #nav-mobile a as your selector.

Now, where are the uls in relation to their corresponding a (referred to as $(this) inside the callback function)? They are immediate siblings, so $(this).next('ul') is your best bet.

To close all the other menu items, save the the ul in a variable and use .not() to select the other uls.

Your code should now look like this.

$(document).ready(function() {
    $('#nav-mobile ul').hide();
    $('#nav-mobile a').click(function(e) {
        e.preventDefault();
        var $menuItem = $(this).next('ul');
        $menuItem.slideToggle();
        $('#nav-mobile ul').not($menuItem).slideUp();
    });
});
#tab1, #tab2, #tab3{
  background-color:grey;
  color:white;
  padding:5px 10px;
  display:block;
  width:100px;
  border-bottom:1px solid;
}

#tab1:hover, #tab2:hover, #tab3:hover{
  background-color:darkgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav-mobile">
    <a href="#" id="tab1">Products</a>
    <ul style="display: none;">
        <li><a href="index.php">Home</a></li>
        <li><a href="#">Why Us</a></li>
        <li><a href="#">Our Work</a></li>
    </ul>
    <a href="#" id="tab2">About</a>
    <ul style="display: none;">
        <li><a href="#">Our Equipment</a></li>
        <li><a href="#">Video Production</a></li>
    </ul>
    <a href="#" id="tab3">Contact</a>
    <ul style="display: none;">
        <li id="last-child"><a href="#">Contact</a></li>
        <li id="last-child"><a href="#">Social Media</a></li>
    </ul>

</div>

Comments