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>
getElementsByClassName("menu-icon").onClick
should be
getElementsByClassName("menu-icon")[0].onclick
Because
getElementsByClassName
returns a list of elements NodeList. Events likeonclick
must be lowercase.Also you could use a simple condition using Ternary operator, eg: