I am using the _s theme from Wordpress (which I do often), but in my design, I want to move the menu toggle button to another div. I have modified the navigation.js file, but I can't seem to get it to display the menu.
The HTML (a little simplified to remove site-specific data):
<header id="masthead" class="site-header">
<div id="site-branding" class="site-branding">
<h1 class="site-title"><a href="#" rel="home">Site Title</a></h1>
<button id="open-menu" class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><span class="dashicons dashicons-menu-alt"></span></button>
</div><!-- .site-branding -->
<nav id="site-navigation" class="main-navigation">
<div id="primary-menu" class="menu">
<ul class="nav-menu">
<li class="page_item page-item-1"><a href="#">Item One</a></li>
<li class="page_item page-item-2"><a href="#">Item Two</a></li>
</ul>
</div>
</nav><!-- #site-navigation -->
</header>
The relevant javascript:
( function() {
const siteNavigation = document.getElementById( 'site-navigation' );
const container = document.getElementById('site-branding');
const button = container.getElementsByTagName( 'button' )[ 0 ];
button.addEventListener( 'click', function() {
siteNavigation.classList.toggle( 'toggled' );
if ( button.getAttribute( 'aria-expanded' ) === 'true' ) {
button.setAttribute( 'aria-expanded', 'false' );
} else {
button.setAttribute( 'aria-expanded', 'true' );
}
} );
}() );
I know that the event listener is working (if I add an alert or console.log item, it displays as expected), but the class list doesn't change, nor does the aria-expanded attribute.
Any thoughts?
I know this is an old question but I was struggeling with it today so I thought I help out anybody still struggeling with it.
In underscores original navigation.js file you can find another click event listener just below the code for the button:
so basically every time you click the button the next thing that happens is that you click outside the siteNavigation container (since you moved the button there) and it toggles the class again :)
hope this helps someone