Dre Loo Dre Loo - 18 days ago 5
Javascript Question

Javascript: Switch between 2 functions with 1 Click-Listener

I have a problem in that I want to code a Side bar with this cool animated Burger-Menu-Button("navicon1"). A cool animation effect for the Menu-Button is used the "open" class. I want to toggle the functions "openNav" and "closeNav" too if I click the menu button.

So this is what I want:


  • If I click the Menu Button(navicon1) the first Time -> Menu-Button
    changes to X (this works) and executing javascript function "openNav"

  • If I click the Menu Button(navicon1) the second Time -> Menu Button
    changes to normal (this works) and executing javascript function
    "closeNav"



Here is my code:

$(document).ready(function() {

$('#navicon1,#navicon2,#navicon3,#navicon4').click(function() {
$(this).toggleClass('open');

});
});
/* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */
function openNav() {

document.getElementById("mySidenav").style.width = "75%";
document.getElementById("main").style.marginLeft = "75%";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";

}

/* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */
function closeNav() {

document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
document.body.style.backgroundColor = "white";
check = 0;
}


You can ignore navicon2-3, they are only for the css...

Thank you for your Help :)

Answer

Use a variable to remember the state:

var navOpen = false;
$("#navicon1").click(function() {
    if (navOpen) {
        closeNav();
        navOpen = false;
    } else {
        openNav();
        navOpen = true;
    }
});
Comments