chinloyal
chinloyal

Reputation: 1141

Match anchor tag with a specific href

I have a dashboard with a sidebar with navigation links where I highlight each link on the side once you go to the link. I match the link by doing this

$(function() {
    var item = $('.sidebar-menu a[href="' + location.href + '"]');

    item.parent().addClass('active');
});

But the problem is if you add an hash (#) to the address then it no longer matches the link. And I want it to match it regardless.

Currently it would match:

But it wouldn't match:

I want it to match anything that includes "mysite.com/students/companies"

Upvotes: 0

Views: 114

Answers (2)

mplungjan
mplungjan

Reputation: 177940

Have a try with

$('.sidebar-menu a').filter(function() {
  return location.href.indexOf(this.href)!=-1;
}).parent().addClass('active');

var item = $('.sidebar-menu a[href*="' + location.pathname + '"]');

Upvotes: 0

Piotr Mirosz
Piotr Mirosz

Reputation: 866

I think you got problem because your anchor tag look something like that:

<a href='somethingelse.php'>Something Else</a>

I notice that you call parent div so.. you wrap your anchor tag by div or ul,li or something else..

What you can do simple add some extra data like 'data-user='' so <div data-user='companies'><a href='somethingelse.php'>Something Else</a></div>

So now if somebody will be inside companies or something else just do the trick:

var url_string = window.location.href;
var url = url_string.split('/')
var item = $('div[data-user='+url[3]+']).addClass('active');

That will work for webpage look like: www.some.com/companies and www.some.com/companies/sometihng even www.some.com/companies/sometihng/more

Upvotes: 1

Related Questions