0
votes

I know this is very basic, but i could not able to get it to work.

I have a main nav menu, when i click it displays the href and the class active is added to the menu (indicated * in the code below)

+--------------+---------+--------+
| * Students * | Courses | Batchs |
+--------------+---------+--------+

I have sub pages inside Students and if the subpages is selected (which has its own href) i want to keep the parent (Students) active all the time.

If i click Courses, the active class remove from Students and make the Courses active and its subpages (based on clicks).

NOTE: The children submenus are NOT a dropdown and NOT under the parent menu. They are different buttons of links in the page.

.------------------.
|   Add Student    |
:------------------:
| * Edit Student * |
:------------------:
| Delete Student   |
'------------------'

Here's the current code

HTML

<aside class="menu">
    <ul class="menu-list">
        <li><a href="students.php">Students</a> </li>
        <li><a href="courses.php">Courses</a> </li>
        <li><a href="batches.php">Batches</a> </li>
    </ul>
</aside>

jQuery

$(document).ready(function() {

    var url = window.location.href;
    url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
    url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
    url = url.substr(url.lastIndexOf("/") + 1);
    if(url == ''){
        url = 'index.php';
    }

    $('.menu li').each(function(){
        var href = $(this).find('a').attr('href');
        if(url == href){
            $(this).addClass('is-active');
        }
    });
});
1

1 Answers

0
votes

You can do one thing in all you submanu links give a data attribute with parent class like data-class="your parent class".

When a submenu is clicked you can use its data-class attribute to see which parent needs to activated.