Currently I use one button to display a side menu and another to close it
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%;
}
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 */
}
});
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);
});
});
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>