KSPR
KSPR

Reputation: 2375

How to add active class to menu (based on url hash)

I have a anchor link menu:

<ul>
  <li class="anchorX"><a href="#anchorX">Bla</a></li>
  <li class="anchorY"><a href="#anchorY">Bli</a></li>
  <li class="anchorZ"><a href="#anchorZ">Blu</a></li>
</ul>

now I want to add an active class to the li element based on the current hash in the url.

Since there will be no page reload I've tried to write a function which is listening to te url:

$(window).on('hashchange', function() {
    //get the hash
    var adressBarHash = window.location.hash.replace("#",".");

    //now apply the class active to the link which contains the same hash as a class
    $("ul").find(adressBarHash).addClass( "active" );
});

My idea is to match the hash in the url with the class. But I can't get it to work.

Even better would be to match the hash in the adress bar with the hash in the href tag but thats out of my league.

$(window).on('hashchange', function() {
    var adressBarHash = window.location.hash;
    $('[href*=' + adressBarHash + ']').addClass('active')

});

Upvotes: 1

Views: 3993

Answers (1)

Sean Gregory
Sean Gregory

Reputation: 621

Edit: oops, didn't see that you wanted it on the li

You almost have it.

$(window).on('hashchange', function() {
  let hash = window.location.hash;
  $('a').closest('li').removeClass('active');
  $('a[href="' + hash + '"]').closest('li').addClass('active');
});

https://jsfiddle.net/xpvt214o/47288/

Upvotes: 2

Related Questions