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
  • 874
  • 2
  • 11
  • 20
Schneider
  • 2,306
  • 6
  • 27
  • 37

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,644
  • 23
  • 21
0

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

$this[0].pathname;

Get pathname from href in Javascript

Location pathname Property

Community
  • 1
  • 1
Sky Voyager
  • 11,413
  • 4
  • 45
  • 70
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,816
  • 1
  • 15
  • 31
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,813
  • 2
  • 27
  • 30