lil lil - 4 months ago 7
Javascript Question

active menu and submenu on a navigation bar

I have a navigation menu as follows

<div id="nav">
<ul>
<li><a href="<?php echo base_url(); ?>home">HOME</a></li>
<li><a href="#">Classes</a>
<ul>
<li><a href="<?php echo base_url(); ?>class_one">class One</a></li>
<li><a href="<?php echo base_url(); ?>class_two">Class Two</a></li>
<li><a href="<?php echo base_url(); ?>class_three">Class Three</a></li>
<li><a href="<?php echo base_url(); ?>class_four">Class Four</a></li>
</ul>
</li>
<li><a href="<?php echo base_url(); ?>results">Exams</a>
</li>
</ul>
</div>
<script>
$(document).ready(function () {
$("[href]").each(function () {
if (this.href == window.location.href) {
$(this).addClass("active");
}
});
});
</script>


Apart from the navigation menu I have a script that would show the page on which the user is by changing the color of menu using active class in my css file. So all the main menus except 'Classes' are working fine but what I want is when the user is on any submenu under 'classes' menu to show 'classes' as the active menu instead of its submenus. How can accomplish that?

Answer

Add

$(this).parents('li').find('> a').addClass("active");

in the if statement.

This code finds all the parents of the matched element which are li tags, and then finds the direct children of the matched parents which are a tags, and adds the active class to them too