February 5, 2024 at 7:36 pm
#1433037
Hi,
Sorry for the confusion, I removed the WPCode snippet and enabled the child theme function again.
This is the working solution:
function tab_though_menu_skipping_sub_menu_items_unless_down_or_up_arrow_keys_are_used() { ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
const menuItems = document.querySelectorAll('.menu-item-has-children'); // Adjust this selector to match your menu structure
// Initially set tabIndex to -1 for all sub-menu items to skip them in tab navigation
menuItems.forEach(item => {
let subMenuItems = item.querySelectorAll('.sub-menu a'); // Adjust this selector for your sub-menus
subMenuItems.forEach(subMenuItem => {
subMenuItem.tabIndex = -1;
});
item.addEventListener('keydown', function (e) {
// Only proceed if the event target is a menu item that contains a sub-menu
let subMenu;
if (e.target.classList.contains('menu-item-has-children')) {
subMenu = e.target.querySelector('.sub-menu'); // Adjust this selector for your sub-menus
} else {
// This ensures we get the sub-menu even if a child of the menu item was focused
subMenu = e.target.closest('.menu-item-has-children').querySelector('.sub-menu');
}
let subMenuItems = subMenu.querySelectorAll('a'); // Assumes sub-menu items are anchor tags
let focusedElement = document.activeElement;
let currentIndex = Array.from(subMenuItems).indexOf(focusedElement);
switch(e.key) {
case 'ArrowDown':
// Move focus to the next sub-menu item
if (currentIndex < subMenuItems.length - 1) {
subMenuItems[currentIndex + 1].tabIndex = 0;
subMenuItems[currentIndex + 1].focus();
e.preventDefault(); // Prevent scrolling the page
} else {
// Optionally wrap around to the first item
subMenuItems[0].tabIndex = 0;
subMenuItems[0].focus();
e.preventDefault(); // Prevent scrolling the page
}
break;
case 'ArrowUp':
// Move focus to the previous sub-menu item
if (currentIndex > 0) {
subMenuItems[currentIndex - 1].tabIndex = 0;
subMenuItems[currentIndex - 1].focus();
e.preventDefault(); // Prevent scrolling the page
} else {
// Optionally wrap around to the last item
subMenuItems[subMenuItems.length - 1].tabIndex = 0;
subMenuItems[subMenuItems.length - 1].focus();
e.preventDefault(); // Prevent scrolling the page
}
break;
}
// Reset tabIndex to -1 for items not focused to ensure they're skipped during tab navigation
subMenuItems.forEach(subMenuItem => {
if (subMenuItem !== document.activeElement) {
subMenuItem.tabIndex = -1;
}
});
});
});
});
</script>
<?php
}
add_action( 'wp_footer', 'tab_though_menu_skipping_sub_menu_items_unless_down_or_up_arrow_keys_are_used', 99 );
Best regards,
Mike