Bel Bel - 1 year ago 97
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.


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 Source

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) {
        var $menuItem = $(this).next('ul');
        $('#nav-mobile ul').not($menuItem).slideUp();
#tab1, #tab2, #tab3{
  padding:5px 10px;
  border-bottom:1px solid;

#tab1:hover, #tab2:hover, #tab3:hover{
<script src=""></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>
    <a href="#" id="tab2">About</a>
    <ul style="display: none;">
        <li><a href="#">Our Equipment</a></li>
        <li><a href="#">Video Production</a></li>
    <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>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download