lil lil - 1 year ago 84
Javascript Question

active menu and submenu on a navigation bar

I have a navigation menu as follows

<div id="nav">
<li><a href="<?php echo base_url(); ?>home">HOME</a></li>
<li><a href="#">Classes</a>
<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>
<li><a href="<?php echo base_url(); ?>results">Exams</a>
$(document).ready(function () {
$("[href]").each(function () {
if (this.href == window.location.href) {

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 Source


$(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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download