I tried to make a hamburger menu.
Here is my HTML :
<nav>
<h3>Life Below Water</h3>
<ul class="ul">
<li><a href="" class="nav">Donate</a></li>
<li><a href="https://sdgs.un.org/goals" class="nav">Visit SDG.UN</a></li>
</ul>
<a href="#" class="toggle" id="menuicon"><i class="fas fa-bars"></i></a>
</nav>
Here is my JS :
const toggle = document.getElementByClassName('menuicon')[0]
const navBar = document.getElementByClassName('ul')[0]
menuicon.addEventListener('click', () =>{
navBar.classList.toggle('active')
})
It doesn't expand the menu when I click the hamburger icon.
CodePudding user response:
getElementByClassName
should be getElementsByClassName
:
const toggle = document.getElementsByClassName('menuicon')[0]
const navBar = document.getElementsByClassName('ul')[0]
menuicon.addEventListener('click', () =>{
navBar.classList.toggle('active')
})
.ul{
display:none;
}
.active{
display:block;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<nav>
<h3>Life Below Water</h3>
<ul class="ul">
<li><a href="" class="nav">Donate</a></li>
<li><a href="https://sdgs.un.org/goals" class="nav">Visit SDG.UN</a></li>
</ul>
<a href="#" class="toggle" id="menuicon"><i class="fas fa-bars"></i></a>
</nav>