Dave Dave - 2 months ago 15
CSS Question

open/close sidenav bar same button

I have a button that I'm hoping will open and close a side nav. My button code is:

<button class="myBtn" id="myBtn"><i class="glyphicon glyphicon-info-sign"></i></button>


I'm trying to use addEventListener and think i may be missing an if statement in this, but can't be sure:

document.getElementById("myBtn").addEventListener("click", open);
function open() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
document.getElementById("myBtn").addEventListener("click", close);
function close() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
document.body.style.backgroundColor = "white";
}


any suggestions? thanks!

Answer

You can create a toogleFunction

document.getElementById("myBtn").addEventListener("click", toggleNav);

function toggleNav(){
    navSize = document.getElementById("mySidenav").style.width;
    if (navSize == 250) {
        return close();
    }
    return open();
}
function open() {
        document.getElementById("mySidenav").style.width = "250px";
        document.getElementById("main").style.marginLeft = "250px";
        document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
function close() {
         document.getElementById("mySidenav").style.width = "0";
        document.getElementById("main").style.marginLeft = "0";
        document.body.style.backgroundColor = "white";
}