Darcy Darcy - 6 months ago 140
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>
<ul>
<li><a href="#" id="link2.1">Link2.1</a></li>
</ul>
</li>
<li><a href="#" id="link3">Link3</a></li>




Jquery:

$('.additional-menu a').on('click', function() {
var t = $(this);
t.parents('.additional-menu').find('li').removeClass('active');
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>
<ul>
<li><a href="link2-1.php" id="link2.1">Link2.1</a></li>
</ul>
</li>
<li><a href="link3.php" id="link3">Link3</a></li>
</ul>

Answer

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:

 $(document).ready(function(){
    var fullpath =window.location.pathname;
    var filename=fullpath.replace(/^.*[\\\/]/, '');
    //alert(filename);
    var currentLink=$('a[href="' + filename + '"]'); //Selects the proper a tag
    currentLink.parent().addClass("active");
    }))
Comments