In my website the main menu has two versions: desktop, and mobile (that includes tablets).
Changing a webpage from desktop menu prevents any toggling functionality In mobile menu after resizing the window. The mobile menu will appear opened, and the toggling will just be stuck.
A full refresh location.reload(true)
will fix this behavior until next time, but of course, that’s not a solution.
My code:
document.addEventListener('DOMContentLoaded', ()=>{
let clicks = 0;
let menu = document.querySelector('#menu-mainmenu'); // Menu identifier.
let mainmenuButton = document.querySelector('.mainmenuButton'); // Button class in pagebuilder.
document.addEventListener('DOMContentLoaded', ()=>{
let clicks = 0;
let menu = document.querySelector('#menu-mainmenu'); // Menu identifier.
let mainmenuButton = document.querySelector('.mainmenuButton'); // Button class in pagebuilder.
if (window.innerWidth <= 768) {
menu.style.display = 'none';
mainmenuButton.addEventListener('click', ()=>{
clicks++;
if (clicks % 2) {
menu.style.display = 'block';
} else {
menu.style.display = 'none';
}
});
}
// Cleanups:
window.addEventListener('resize', ()=>{
// Must be inside first AEL as well.
if (window.innerWidth >= 769) {
clicks = 1; // Prevent double clicking).
menu.style.display = 'block'; // Prevent display:none of mobile mode.
}
});
});
To solve it, I tried:
- Using returns in different versions of the code.
- Resetting the clicks counter on
resize
addEvenetListener
. - Creating another event listener with an opposite version of the code.
- Adding a
removeEvenetListener
(with named handler functions) - Using
else if
, with directions for desktop viewport (>=769
).
Yet, after resizing to desktop, using the menu, then resizing back to mobile, the mobile menu is stuck.
How could I make sure the mobile menu toggles freely, after I resize and load webpages from the desktop menu?
Please feel free to check my webpage’s code online.