Open and close side menu with same button

Currently I use one button to display a side menu and another to close it

$('#open-menu').click(function() {
  $("#mySidenav").css("width" , "250px");
  $("#l_m").css({"marginLeft": "250px", "position" : "absolute", "width" : "100%"});
  // $(this).attr('id','close-menu');

$('#close-menu').click(function() {
  $("#mySidenav").css("width" , "0");
  $("#l_m").css("marginLeft" , "0");

But I want the same button opens and closes my menu How to do ? Knowing that I use Jquery 1.11.3

Thank you

(I tried to add the line that is commented but when I click on it, nothing happens)



Move the open styles into separate css classes. Then toggle these classes on button click using the jQuery toggleClass() function.


$('#toggle-menu').click(function() {


#mySidenav {
  width: 0;
} {
  width: 250px;

#l_m {
  margin-left: 0;
} {
  position: absolute;
  margin-left: 250px;
  width: 100%;

Just make a class to show the menu and toggle this class on button click...!

$('#open-menu').click(function() {
#mySidenav {background: red; height: 100px; display: none;}
.show {display: block !important;}
<script src=""></script>
<div id="mySidenav"></div>
<button id="open-menu">Menu</button>


Here's what you can do, I call this "trick" a custom toggle :

  $(/*selector for the button*/)
      const $this = $(this);
      let prop = $this.prop("opened");

      if(prop === undefined){
        $this.prop("opened", false);
        prop = $this.prop("opened");

      if(prop === false){
        /*handle opening here*/

      if(prop === true){
        /*handle closing here*/

      $this.prop("opened", !prop);

You can use this simple approach using jQuery data attribute.

<a id="menu" data-stat="close">Menu Button</a>

$('#menu').on('click', function(){
    if($(this).data('stat') == "close"){
        $(this).data('stat', 'open');

        /* open Menu code */

    }else if($(this).data('stat') == "open"){
        $(this).data('stat', 'close');

        /* close Menu code */



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.