I'm new to JavaScript and I've ran into a problem: I've built a dropdown menu/navbar in my HTML page. When you click a button, it opens up like it should, but I'm struggling with closing it. It's supposed to close when you click the button again, but I can't do that for some reason.
My method was to assign a class btn
and id disabled-btn
to a div. After clicking and opening the dropdown, button is supposed to have a new id of enabled-btn
, which is should be selected so I could reverse the process.
I understood via debugging that you can't query select an element if it's not on the page yet, but I haven't managed to bypass it anyhow.
This is one of the variants of code that I tried.
const disabledButton = document.querySelector('#disabled-btn')
const navbar = document.querySelector('.my_navbar')
const enabledButton = document.querySelector('#enabled-btn')
const button = document.querySelector('.btn')
disabledButton.onclick = () => {
navbar.style.transform = 'translate(0%, 0%)'
disabledButton.style.rotate = '90deg'
disabledButton.setAttribute('id', 'enabled-btn')
if (button === enabledButton) {
enabledButton.onclick = () => {
navbar.style.transform = 'translate (-100%, 0%)'
enabledButton.style.rotate = '0deg'
enabledButton.setAttribute('id', 'disabled-btn')
}
}
}
<div class="open-btn" id="disabled-btn">
<svg ...some svg here...></svg>
</div>
<nav class="my_navbar">
<div class="my_navbar-nav"><a href="#">GALLERY</a></div>
<div class="my_navbar-nav"><a href="#">PRESETS</a></div>
<div class="my_navbar-nav"><a href="#">ABOUT</a></div>
<div class="my_navbar-nav"><a href="#">BOOKING</a></div>
</nav>