In my React app, I have a burger menu that runs as expected on Firefox, but it doesn't work the on Chrome, and I receive no console errors.
here the script that is responsible for handling the burger menu :
// Burger menus
document.addEventListener('DOMContentLoaded', function() {
// open
const burger = document.querySelectorAll('.navbar-burger');
const menu = document.querySelectorAll('.navbar-menu');
if (burger.length && menu.length) {
for (var i = 0; i < burger.length; i++) {
burger[i].addEventListener('click', function() {
for (var j = 0; j < menu.length; j++) {
menu[j].classList.toggle('hidden');
}
});
}
}
// close
const close = document.querySelectorAll('.navbar-close');
const backdrop = document.querySelectorAll('.navbar-backdrop');
if (close.length) {
for (var i = 0; i < close.length; i++) {
close[i].addEventListener('click', function() {
for (var j = 0; j < menu.length; j++) {
menu[j].classList.toggle('hidden');
}
});
}
}
if (backdrop.length) {
for (var i = 0; i < backdrop.length; i++) {
backdrop[i].addEventListener('click', function() {
for (var j = 0; j < menu.length; j++) {
menu[j].classList.toggle('hidden');
}
});
}
}
});
and here's the code showing how its placed inside my react component :
<nav className='lg:hidden flex items-center justify-between p-8 bg-gray-700 mb-3'>
<Link className='inline-flex items-center h-8' to='/'>
<img
src='images/l.png'
alt=''
/>
</Link>
<div className='w-full xl:w-auto px-2 xl:mr-12'>
<div className='flex items-center justify-between'>
<div className='xl:hidden' />
</div>
</div>
<button className='navbar-burger p-2 text-gray-400 hover:text-gray-300 focus:outline-none'>
<svg
width={20}
height={12}
viewBox='0 0 20 12'
fill='none'
xmlns='http://www.w3.org/2000/svg'
>
<title>Mobile menu</title>
<path
d='...removed...'
fill='currentColor'
/>
</svg>
</button>
</nav>
attaching a screen-shot of the expected behavior :
I suggest, try a simple logic and not a complex approach.
For example, when you click on the "navbar-burger" icon and then toggle the "open" class to its parent div "min-h-screen" and now you can control it from CSS.
Do this the simple approach after toggle the open class.
.min-h-screen.open .navbar-menu {
display: block;
/* You can also add css smooth transitions if you want */
}
This will work in any browser.