I'm trying to create a hamburger menu, and the hamburger icon is supposed to change to an 'x' icon when the menu is open. I'm using Tailwind in Astro JS and this is my html:
<div id='hamburger-container' class="flex justify-center w-full sm:hidden">
<button id='hamburger'><i class="fa-solid fa-bars text-4xl py-4"></i></button>
</div>
<div id='x-container' class="hidden justify-center w-full sm:hidden">
<button id="x"><i class="fa-solid fa-xmark text-4xl py-4"></i></button>
</div>
and this is my javascript:
const hamburger = document.getElementById('hamburger');
const x = document.getElementById('x');
const hamburgerContainer = document.getElementById('hamburger-container');
const xContainer = document.getElementById('x-container');
const btnClick = () => {
var xIsHidden = xContainer!.classList.contains('hidden');
if (xIsHidden) {
hamburgerContainer!.classList.replace('flex', 'hidden');
xContainer!.classList.replace('hidden', 'flex');
} else {
xContainer!.classList.replace('flex', 'hidden');
hamburgerContainer!.classList.replace('hidden', 'flex');
}
}
hamburger!.addEventListener('click', btnClick);
x!.addEventListener('click', btnClick);
The issue is that the hamburger buttons remains visible on the screen when I press it. I can see the x disappear and reappear when I toggle it, but the hamburger doesn't.
I can see the classes toggle between hidden
and flex
for both the #hamburger
and the #x
elements in the chrome developer window, and the css display
property for both elements toggle between flex
and none
when I click the button, so the problem isn't the styling, it's purely visual.
I also tried swapping them around, by giving the x
element the flex
class to start off with and the hamburger
the hidden
class to start with, and the problem switched; the hamburger
element would appear and disappear, but the x
element would remain on the screen when I made that change.
To note, I have tested this on both Chrome and Edge, so I don't think the problem is browser-specific.