Ad

Change Of State Based On Anchor Link - Works On Load, But Not If Anchor Changes?

I am working on a personal project for my own development and for the life of me I can't work how to resolve my issue.

My issue: If the #anchor variable in the address bar is 'this' add the class. This aspect works fine, but if a button is clicked and the anchor is changed the class doesn't apply itself. How can I amend by code for the change of state? Any thoughts or suggestions are appreciated.

I've tried a variety of combinations, but the one below is closest to the goal I feel?

jQuery(function($) {
  var path = location.href;
  $('li a').each(function() {
    if (this.href === path) {
      $(this).addClass('current-link');
    }
  });
});
Ad

Answer

Try,

jQuery(function($) {
  var path = location.href;
  $('li a').each(function() {
    if (this.href === path) {
      $(this).addClass('current-link');
    }
  });

  // Add this code
  $('li a').click( function() {
    $( this ).parents('ul').find('.current-link').removeClass('current-link');
    $( this ).addClass('current-link');
  } );
});
Ad
source: stackoverflow.com
Ad