I have the following front-end code for a responsive navigation menu which I thought using in my WordPress website.
Clicking the .burger
element should cause adjacent .menu
element to appear or disappear, in dropdown or dropup respectively, but without a breakpoint conflict such as this, which I suffer from:
- We open a browser window
<=959px
and open the menu. - We resize the window to
>=960px
and then we resize back to<=959px
. - We see that the menu is still open and isn't restarted.
Why I seek review
Many programmers advised me to take a pure CSS approach (no JavaScript) but in this case I create my markup with a WordPress page builder (Elementor) hence it feels inefficient to me. I also feel my JavaScript is too long and a bit confusing.
You might know a simpler and shorter (more methodal and more intuitive) pattern in vanilla JavaScript available in 2018 (ES6/ES7?) or in jQuery 3.x.x.
Code
document.addEventListener('DOMContentLoaded', ()=>{
let clicks = 0;
let menu = document.querySelector('#menu-primary');
let burger = document.querySelector('.burger');
let isMenuVisible = false;
burger.addEventListener('click', ()=>{
isMenuVisible = !isMenuVisible;
menu.style.display = isMenuVisible ? 'block' : 'none';
});
let mobileBehavior = ()=>{
menu.style.display = 'none';
};
if (window.innerWidth <= 959) {
mobileBehavior();
}
window.addEventListener('resize', ()=>{
if (window.innerWidth <= 959) {
clicks = 1;
} else if (window.innerWidth >= 960) {
menu.style.display = 'block';
}
});
});
.burger {display: block; text-align: center; color: var(--w); margin-bottom: 0 !important; font-weight: bold}
#menu-primary {display: none}
@media screen and (min-width: 960px) {
.burger {display: none}
#menu-primary {display: block}
}
<div class="burger">BARS</div>
<ul id="menu-primary">
<li>Homepage</li>
<li>Contact_us</li>
</ul>
Update
I reported a problem with the code in this StackOverflow session; the problem is that the code can conflict with some page builders and does conflict with Elementor WordPress-Drupal page builder, as described there.