I am currently facing an issue with a menu structure, where parent menu items have submenus that need to toggle on click.
However, I am encountering a problem where, upon placing the code inside a forEach loop, both submenus toggle instead of only toggling the submenu of the clicked parent item.
Is there a way to instruct JavaScript to toggle only the submenu related to the clicked element?
Implementing PHP in WordPress:
<?php
function main_navigation() {
$menu_name = 'main_menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'ASC' ) );
$count = 0;
$sub_menu = false;
?>
<ul class="header__list">
<?php
foreach( $menu_items as $item ):
$link = $item->url;
$title = $item->title;
$class = $item->classes[0];
// Check if item has no parent (menu_item_parent equals 0)
if ( !$item->menu_item_parent ):
// Save this id for comparison with sub-menu items
$parent_id = $item->ID;
?>
<li class="header__item">
<a href="<?php echo $link; ?>" class="header__link <?php echo $class ?>"><?php echo $title; ?></a>
<?php endif; ?>
<?php if ( $parent_id == $item->menu_item_parent ): ?>
<?php if ( !$sub_menu ): $sub_menu = true; ?>
<ul class="header__sub-list" aria-role="header-sublist">
<?php endif; ?>
<li class="header__sub-item">
<a href="<?php echo $link; ?>" class="header__sub-link"><?php echo $title; ?></a>
</li>
<?php if ( $menu_items[ $count + 1 ]->menu_item_parent != $parent_id && $sub_menu ): ?>
</ul>
<?php $sub_menu = false; endif; ?>
<?php endif; ?>
</li>
<?php
$count++;
endforeach;
?>
</ul>
<?php
}
Implementing JavaScript functionality:
const headerSubLists = document.querySelectorAll('.header__link-sub');
headerSubLists.forEach((headerSubList) => {
const headerSubMenu = document.querySelectorAll(
'[aria-role="header-sublist"]'
);
const openSubMenu = (e) => {
e.preventDefault();
headerSubMenu.forEach((menu) => {
menu.classList.toggle('is-open');
});
};
headerSubList.addEventListener('click', openSubMenu);
});