I have a ul with the id of "menu-list". I have set the display property to "none" in my CSS file, but I would like it to change to "flex" when clicking on a link.
I am using the click event on the link to trigger the change of the display property, but nothing happens when I click on it.
When logging the value of the display property to the console inside myFunction(), I just get a blank log in the console, with no value displayed.
What am I doing wrong?
let menuList = document.getElementById("menu-list");
function myFunction() {
console.log(menuList.style.display);
if (menuList.style.display === "none") {
menuList.style.display = "flex";
} else {
menuList.style.display = "none";
}
}
#menu-list {
display: none;
}
<div class="container">
<div class="inner">
<nav id='menu'>
<div class="logo">
<img src="src/assets/images/hp-logos_white.png" alt="logo" class="fluid">
</div>
<ul id="menu-list">
<li class="menu-list-item"><a href="">Home</a></li>
<li class="menu-list-item"><a href="">Home</a></li>
<li class="menu-list-item"><a href="">Home</a></li>
</ul>
<a href="" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</nav>
</div>
</div>
2
Answers
Switch the order of your comparison since initially no inline style is set on the element.
Few issues here:
You use an anchor instead of a button and as such it will redirect you to a new site.
Then the answer explains why your toggle is not working. However, the modern solution is to simply toggle a CSS class: