I am currently working on a menu with submenus. I am facing an issue where when I click on a top-level menu item, I need to use prevent default because they are anchor tags. However, for the submenu items, I do not want to prevent default behavior. I am struggling to find a solution that allows me to differentiate between the two levels of the menu.
<div id="block-menu-block-2">
<ul class="menu">
<li>
<a href="#">1</a>
</li>
<li>
<a href="#">2</a>
<ul class="menu">
<li><a href="#">2.1</a></li>
<li><a href="#">2.2</a></li>
<li><a href="#">2.3</a></li>
<li><a href="#">2.4</a></li>
</ul>
</li>
<li>
<a href="#">3</a>
<ul class="menu">
<li><a href="#">3.1</a></li>
<li><a href="#">3.2</a></li>
<li><a href="#">3.3</a></li>
<li><a href="#">3.4</a></li>
</ul>
</li>
<li>
<a href="#">4</a>
</li>
<li>
<a href="#">5</a>
</li>
<li>
<a href="#">6</a>
<ul class="menu">
<li><a href="#">6.1</a></li>
</ul>
</li>
</ul>
</div>
Below is the jQuery code:
$('#block-menu-block-2 ul li').on("click", function() {
if ($(this).children().is('ul')) {
if ($(this).find('ul').is(':visible')) {
$(this).find('ul').hide("blind");
$(this).removeClass('menuItemSelected');
$(this).find('ul').removeClass('menuItemSelected');
} else {
$(this).parent().find('li ul').hide("blind");
$(this).parent().find('.menuItemSelected').removeClass('menuItemSelected');
$(this).find('ul').show("blind");
$(this).addClass('menuItemSelected');
$(this).find('ul').addClass('menuItemSelected');
};
event.preventDefault()
}
});
For a live example, check out this CodePen link.