I have a nav bar in the form of a ul with several li elements and with the last li (named 'more') having its own sub-menu in the form of another ul. I was trying (and was successful) in making it so that the sub-menu's original state is visibility:visible; and then when the user clicks on li name 'more' it would toggle between visibility: visible; and visibility: hidden; I used JavaScript and a counter with an if statement. The reason why I used the counter was because when I tried:
if(document.querySelector('#subMenu').style.visibility == "hidden")...;
But it wouldn't toggle.
My questions are:
Would this method of creating the toggle function be deemed acceptable in a professional front end developer workplace?
Is there a better way to toggle between visible and hidden on clicking an element using JavaScript ONLY (trying to get better at JavaScript)?
The code is as follows(I have only included the relevant code):
HTML
<ol id = "leftNav" class = "bothNavs">
<li class = "navs" id = "more">More<div class = "arrow"></div>
<ul class = "subMenu">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</li>
</ol>
CSS
.subMenu {
width: 160%;
padding: 5px 0px;
padding-left: 7px;
margin-left: 6px;
position: absolute;
top: 100%;
left:0px;
visibility: hidden;
box-shadow: 0px 2px 3px rgba(0,0,0,0.2);
background: #2D2D2D;
list-style: outside none none;
z-index: 1001;
}
JavaScript
var more = document.querySelector('#more');
var subMenu = document.querySelector('.subMenu');
var counter =0;
more.addEventListener("click", toggle);
function toggle () {
if(counter === 0){
subMenu.style.visibility = "visible";
counter += 1;
} else {
subMenu.style.visibility = "hidden";
counter -= 1;
}
};
Thank you in advance for your answers.