1

I am making active link with jQuery like this

$(document).ready(function() {
    var url = window.location.href;

    $(".main-navigation ul li a").each(function() {
      var $this = $(this);

        var href = $this.attr("href");

        if (url === href) {

            $this.css({
                'color': '#666666',
                'font-weight': 'bold',
            }).addClass('active').removeAttr("href").removeAttr("onclick");         
        }           
    });

The only problem is here that my a href goes like this /Settings/File?id=333

And url wil be something like this

http://www.example.com/Settings/File?id=333

Then the a href and ulr does not match, how to delete http and example for url and check with a href?

tutankhamun
  • 880
  • 2
  • 11
  • 21
Schneider
  • 2,446
  • 6
  • 28
  • 38

4 Answers4

1

First: if you are going to give them a class anyway, don't put extra inline CSS there...

And here a snipper that should work...

var uri = window.location.href;
$(".main-navigation ul li a").filter(function() {
    return (this.href == uri || uri.substr(0,this.href.length + 1) == this.href + "?");
}).css({
    'color': '#666666',
    'font-weight': 'bold',
}).addClass('active').removeAttr("href").removeAttr("onclick");
DoXicK
  • 4,784
  • 24
  • 22
0

To get /Settings/File?id=333 use :

$this[0].pathname;

Get pathname from href in Javascript

Location pathname Property

Community
  • 1
  • 1
user2226755
  • 12,494
  • 5
  • 50
  • 73
0

You want to change http://www.example.com/Setting/File?id=333 into /Setting/File?id=333?

var url = window.location.href.split('.com').pop();

If you don't know if it's a .com website, try this:

function getLocation(url) {
    var el = document.createElement("a");
    el.href = url;
    return el.pathname;
}

var url = getLocation(window.location.href);
hansn
  • 1,936
  • 3
  • 19
  • 32
0

you could use the native a element DOM and its href it will give the full url:

$(function(){
  var url = window.location.href;

  $(".main-navigation ul li a").each(function() {
    if (url === this.href) {
      $(this).css({
        'color': '#666666',
        'font-weight': 'bold',
      }).addClass('active').removeAttr("href").removeAttr("onclick");
    }
  });
});

example on jsbin (first item in the list has the same url without the domain)

voigtan
  • 8,953
  • 2
  • 29
  • 30