Search code examples
javascriptjquerytoggleclass

JQuery responsive menu won't work


I'm a novice web developer with no real jquery knowledge, so please bear with me. I'm trying to make a simple mobile responsive dropdown menu (ideally I'd like a slide down, but baby steps first). For the most part, I figured it out. However, I assigned my "Unordered List" an ID selector and it doesn't seem to function anymore. What am I overlooking? Thanks in advance!

This is my code: JSFiddle

$(document).ready(function(){
  $('#toggle-button').click(function(){
     
      $('#menu').toggleClass('show');
      
      
      
  });
    
});
.show {
    display: block;
}

nav {
    background: black;
    width: 100%;
}

.menu-bar {
    width: 100%;
    background: black;
    height: 50px;
}

#toggle-button {
    position: absolute;
    top: 15px;
    right: 60px;
    height: 35px;
    width: 35px;
    background: red;
    cursor: pointer;
    display: block;
}

#menu {
    list-style: none;
    width: 100%;
    display: none;
    margin: 0px;
    padding: 0px;
}

#menu li {
    height: 50px;
    background: #535252;
}

#menu li a {
    display: block;
    width: 100%;
    height: 50px;
    text-align: center;
    line-height: 50px;
    color: white;
    text-decoration: none;
    cursor: pointer;
}

#menu li:hover {
    background: gray;   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <div class="menu-bar"></div>

    <nav>
        
        <ul id="menu">
            <li><a href="#">Profile</a></li>
            
            <li><a href="#">Profile</a></li>
            
            <li><a href="#">Profile</a></li>
        </ul>
    </nav>

<a id="toggle-button" href="#"></a>
    


Solution

  • Use:

    #menu.show {
        display: block;
    }
    

    after! you defined your defaults for #menu {
    https://jsfiddle.net/nw2wf3uh/6/


    or use the not-so-nice !important:
    https://jsfiddle.net/nw2wf3uh/7/

    .show {
        display: block !important; /* if .show is placed before #menu styles in CSS */
    }
    

    You can also go the other way around, setting to your #menu a .hide by default:

     <ul id="menu" class="hide">
    

    CSS:

    .hide {
        display: none;    /* but remove display:none; from #menu now! */
    }
    

    and toggle that .hide class:

    $('#toggle-button').click(function(){
      $('#menu').toggleClass('hide');
      // or simply: $('#menu').toggle();
    });
    

    Here you'll not run into overriding styles cause of priority and you'll not have to use the !important fix (but you might have issues with JS-disabled users if that's of any concern (you should not care much but it always depends.)).