I’m currently learning JavaScript. I’ve been attempting to create a navbar button that opens the menu when clicked. After multiple attempts and changes to the code, I didn’t solve the problem.
HTML
<nav class="nav">
<div class="logo">AdoptaPet</div>
<button id="navBtn"><i class="bi bi-list abrirNav"></i></button>
<ul id="abrirMenu" class="nav-links">
<i class="bi bi-x fecharNav"></i>
<li><a href="">Home</a></li>
<li><a href="">Sobre Nós</a></li>
<li><a href="">Loja</a></li>
<li><a href="">Cães para Adoção</a></li>
<li><a href="">Detalhes do Cão</a></li>
<li><a href="">Adotar</a></li>
<li><a href="">Favoritos</a></li>
<li><a href="">Contactos</a></li>
</ul>
</nav>
CSS
.nav .nav-links{
display: none;
position: fixed;
top: 0;
left: 0;
background-color: #ffcc05;
flex-direction: column;
height: 100%;
max-width: 280px;
width: 100%;
padding-top: 100px;
row-gap: 25px;
transition: all 0.4s linear;
}
/* Mostra o menu ao clicar no botão */
.navAberta{
display: inherit;
}
JS
document.getElementById("navBtn").onclick = function() {abrirNav()};
function abrirNav() {
document.getElementByID("abrirMenu").classList.toggle("navAberta");
}
The objective would be to open the <ul>
when clicking the button at the top right of the image.
I appreciate anyone who tries to help,
Best regards.
2
Answers
Check for error messages in your console. When I run your code I get
That
D
shouldn’t be capitalized.The 2nd issue is that
.nav .nav-links
has higher precedence than.navAberta
so thatdisplay: inherit
is never applied. You can also see this in dev tools:It’s crossed out.
You can add a 2nd class to make them the same specificity, or remove one of the classes from the other element.
The javascript is incorrect. You would have to define the
onclick
attribute in html.Here is the updated code: