Damien Damien - 1 year ago 84
Javascript Question

JavaScript addEventListener 'click''

I struggling with very basic thing

I am trying to make this side-nav appear and disappear with JavaScript. The code below only activates the nav bar but doesn't deactivate it. Tried all options but I don't know how to call function to close nav-bar.

Thank you

HTML


<div id="mySidenav" class="sidenav">
<a href="#" class="closebtn">&times;</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>

<!-- Use any element to open the sidenav -->
<span id="MyElement">&times;</span>


JS


<script type="text/javascript">
function changeClass() {
document.getElementById("mySidenav").style.width = "250px";

}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',changeClass);
}
</script>


</body>

</html>

Answer Source

your else statement section seems to have the comparator (==) and assignment (=) the wrong way around :

   } else if (menu.style.width = "250px") {
        menu.style.width == "-250px";
   }

looks like it should be

   } else if (menu.style.width == "250px") {
        //setting a negative width will immediately break the toggle logic.
        //just set it to 0px.
        menu.style.width = "0px"; 
   }

Full example :

function changeClass() {
        var sidenavElement = document.getElementById("mySidenav");
        if(sidenavElement.style.width == "0px")
        {
           sidenavElement.style.width = "250px";
        }
        else
        {
          sidenavElement.style.width = "0px";
        }
    }
    window.onload = function() {
document.getElementById("MyElement").addEventListener('click',changeClass);
    }
#mySidenav
{
  overflow:hidden;
  height:100px;
  background:green;
}
<div id="mySidenav" style="width:0px">
  HELLO I AM SIDENAV
</div>

<button id="MyElement">toggle it</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download