Open and close side menu with same button

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

<script>
$('#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");
});
</script>

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)

Answers:

Answer

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

Javascript:

$('#toggle-menu').click(function() {
  $("#mySidenav").toggleClass("open");
  $("#l_m").toggleClass("open");
});

CSS:

#mySidenav {
  width: 0;
}

#mySidenav.open {
  width: 250px;
}

#l_m {
  margin-left: 0;
}

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

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

$('#open-menu').click(function() {
  $("#mySidenav").toggleClass('show')
});
#mySidenav {background: red; height: 100px; display: none;}
.show {display: block !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mySidenav"></div>
<button id="open-menu">Menu</button>

Answer

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

$(document).ready(function(){
  $(/*selector for the button*/)
    .click(function(){
      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);
    });
});
Answer

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 */

    }
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.