Toggling menu button by Javascript

1.7k views Asked by At

I was trying to make a button (.menu-icon) to toggle the menu (#menu), but it failed. (I took "lorem menu text" as an example.) Please take a look at my code below.

I think there are some errors in Javascript code, but I'm not pretty sure. Also, if you have a better solution for this, either Javascript or HTML, please post it as an answer, I'll be grateful for that.

var click=0;

document.getElementsByClassName("menu-icon").onClick = function(){
 click += 1;
 if (click %2 === 1) {document.getElementById("menu").style.visibility = "visible";}
 else {document.getElementById("menu").style.visibility = "hidden";}
};
#menu {
 visibility: hidden;
}

.menu-icon {
  position: relative;
  padding-left: 1.25em;
}

.menu-icon:before {
  content: "";
  position: absolute;
  left: 0;
  top: 0.25em;
  width: 1em;
  height: 0.15em;
  background: black;
  box-shadow: 
    0 0.25em 0 0 black,
    0 0.5em 0 0 black;
}
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <meta charset="utf-8" />
</head>
<body>
  <main>
    <a href="#menu" class="menu-icon"></a>
    <section id="menu">lorem menu text</section>
  </main>
</body>
</html>

2

There are 2 answers

3
Walter Chapilliquen - wZVanG On BEST ANSWER

getElementsByClassName("menu-icon").onClick

should be

getElementsByClassName("menu-icon")[0].onclick

Because getElementsByClassName returns a list of elements NodeList. Events like onclick must be lowercase.

Also you could use a simple condition using Ternary operator, eg:

document.getElementsByClassName("menu-icon")[0].onclick = function(){
  var element = document.getElementById("menu");
  element.style.visibility = element.style.visibility == "visible" ? "hidden" : "visible";
};
0
i_like_robots On

To expand on the answer above, your code can also be simplified by testing the visibility property set in the current style declaration:

var toggle = document.getElementsByClassName("menu-icon")[0];
var menu = document.getElementById("menu");

toggle.onclick = function(){
    var hidden = menu.style.visibility === "hidden";
    menu.style.visibility = hidden ? "visible" : "hidden";
};

Demo: https://jsfiddle.net/z8zdgew7/