Recently, I had a navigation bar in the form of an unordered list (ul) with multiple list items (li), and the last li element was labeled 'more' which had its own sub-menu in the form of another ul. To toggle this sub-menu between visible and hidden states when clicking on the 'more' li, I utilized JavaScript along with a counter in an if statement. Despite my success in achieving the desired functionality, I found it necessary to use the counter as an intermediary step since directly checking for visibility didn't produce the toggle effect.
Here are the queries that arose from this implementation:
Would employing this toggle method be considered acceptable within a professional front-end developer workspace?
Is there a more efficient way to accomplish toggling between visible and hidden states solely using JavaScript? (I aim to enhance my JavaScript skills)
For reference, below is the relevant code snippets:
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: 0;
visibility: hidden;
box-shadow: 0 2px 3px rgba(0, 0, 0, 0.2);
background: #2D2D2D;
list-style: 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;
}
};
Awaiting your valuable insights and suggestions. Thank you.