Darcy Darcy - 1 year ago 250
Javascript Question

JQuery add active class to parent class on reload

My "active" class does not work when i replace "#" from href to an URL. When i click on the link, the page refresh and the "active" class does not change.
This is the working code before i change # to URL.

<ul class="additional-menu">
<li class="active"><a href="#">Link1</a></li>
<li><a href="#" id="link2">Link2</a>
<li><a href="#" id="link2.1">Link2.1</a></li>
<li><a href="#" id="link3">Link3</a></li>


$('.additional-menu a').on('click', function() {
var t = $(this);
t.parentsUntil('.additional-menu', 'li').addClass('active');


after changing(not working):

<ul class="additional-menu">
<li class="active"><a href="link1.php">Link1</a></li>
<li><a href="link1.php" id="link2">Link2</a>
<li><a href="link2-1.php" id="link2.1">Link2.1</a></li>
<li><a href="link3.php" id="link3">Link3</a></li>

Answer Source

When you click on a URL link, the page is being refreshed and the current Jquery wont work anymore. You have to update your codes to determine the active menu according to the page URL on page load or on DOM ready not onClick.

The you have to set the active class to the menu which has the found filename as href attribute.

Here is full code using jquery selectors:

    var fullpath =window.location.pathname;
    var filename=fullpath.replace(/^.*[\\\/]/, '');
    var currentLink=$('a[href="' + filename + '"]'); //Selects the proper a tag
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download