0

I am trying to add active class in navigation. I used this article. Add Active Navigation Class Based on URL

$(function(){
    var current = location.pathname;
    $('#nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

It worked well. But my issue is in this case.

/blog, /blogAds

If url is /blog, active class added to both nav items. Is there any solution for it?

LoveCoding
  • 1,121
  • 2
  • 12
  • 33

1 Answers1

1

Try this

if( new RegExp(location.pathname + "$").test( $this.attr('href') ) ) {
    $this.addClass('active');
}

Tested with:

new RegExp('\/blog$').test('/blogAds'); // returns false
new RegExp('\/blog$').test('/blog'); // returns true

Reference

linktoahref
  • 7,812
  • 3
  • 29
  • 51