-
markushasselryd
Hello!
I’ve created a mega menu using GeneratePress elements and placing that element in the menu using a shortcode. It works just fine but I want to toggle a body class when the mega menu (drop-down) is open to be able to add a background color to the transparent header. I’ve created at javascript which should work but somehow does not, looks like this:const megaMenuToggle = document.querySelectorAll('li.mega-menu > a'); megaMenuToggle.forEach(toggle => { toggle.addEventListener('click', function handleClick(event){ console.log(toggle); document.body.classList.toggle('megamenu-open'); }); });
Could you guys give me a hand or point me in the right direction? Thanks!
-
Fernando
Hi Mark,
Would something like this work?:
const megaMenuToggle = document.querySelectorAll('li.mega-menu > a'); megaMenuToggle.forEach(el => el.addEventListener('click', event => { document.body.classList.toggle('megamenu-open'); }));
-
markushasselryd
Hi Fernando, thanks for the quick response! Your solution doesn’t seem to work, could it be interfering with the dropdown-click.js?
-
David
Hi there,
GP adds the
sfhover
class to a menu , so instead of adding another click eventListener, you can observe the class change using mutationObserver instead. Heres a code i used for checking if any menu-item that has children is open, you can change the class to suit if needed :const body = document.querySelector('body'); const menuItems = document.querySelectorAll('.menu-item-has-children'); const observer = new MutationObserver(mutations => { mutations.forEach(mutation => { if (mutation.type === 'attributes' && mutation.attributeName === 'class') { const target = mutation.target; const hasHoverClass = target.classList.contains('sfHover'); if ( hasHoverClass ) { body.classList.add('submenu-open'); } else { body.classList.remove('submenu-open'); } } }); }); menuItems.forEach(item => observer.observe(item, { attributes: true }));
-
markushasselryd
Hi David, thanks for you solution, works great. I was thinking of a similar solution but wasn’t sure how I would go about it. Think it could be useful if the feature was added in GP as standard. Just toggling a body class when the sub-menu is open.
Thanks,
Markus -
David
Glad to hear that worked 🙂
- You must be logged in to reply to this topic.