Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Twenty Twenty: Adds aria-controls and aria-expanded attributes to primary menu #8272

Open
wants to merge 3 commits into
base: trunk
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/wp-content/themes/twentytwenty/assets/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,8 @@ twentytwenty.primaryMenu = {

init: function() {
this.focusMenuWithChildren();
this.addUniqueIDToSubMenus();
this.toggleAriaExpandedOnHover();
},

// The focusMenuWithChildren() function implements Keyboard Navigation in the Primary Menu
Expand Down Expand Up @@ -454,13 +456,56 @@ twentytwenty.primaryMenu = {
if ( 'li' === self.tagName.toLowerCase() ) {
if ( -1 !== self.className.indexOf( 'focus' ) ) {
self.className = self.className.replace( ' focus', '' );
// If there is an <a> tag with aria-expanded attribute set to true, toggle it to false
const link = self.querySelector('a[aria-expanded="true"]');
if (link) {
link.setAttribute('aria-expanded', 'false');
}
} else {
self.className += ' focus';
// If there is an <a> tag with aria-expanded attribute set to false, toggle it to true
const link = self.querySelector('a[aria-expanded="false"]');
if (link) {
link.setAttribute('aria-expanded', 'true');
}
}
}
self = self.parentElement;
}
}
},

// Add unique ID to each .sub-menu and aria-controls to parent links
addUniqueIDToSubMenus: function() {
var subMenus = document.querySelectorAll( '.primary-menu-wrapper .sub-menu' );
subMenus.forEach( function( subMenu, index ) {
var parentLi = subMenu.closest( 'li.menu-item-has-children' );
subMenu.id = 'sub-menu-' + (index + 1);
if ( parentLi ) {
var parentLink = parentLi.querySelector( 'a' );
if ( parentLink ) {
parentLink.setAttribute( 'aria-controls', subMenu.id );
parentLink.setAttribute( 'aria-expanded', 'false' );
}
}
} );
},

toggleAriaExpandedOnHover: function() {
document.querySelectorAll('.primary-menu-wrapper li.menu-item-has-children').forEach(function(li) {
li.addEventListener('mouseenter', function() {
var anchor = li.querySelector('a');
if (anchor) {
anchor.setAttribute('aria-expanded', 'true');
}
});
li.addEventListener('mouseleave', function() {
var anchor = li.querySelector('a');
if (anchor) {
anchor.setAttribute('aria-expanded', 'false');
}
});
});
}
}; // twentytwenty.primaryMenu

Expand Down
Loading