1

I'm using this code

$(document).ready(function () {
$(function () {
    $('li a[href^="../../' + location.pathname.split("/")[1] + '"]').addClass('active');
   });
});

to highlight my navigation, depending on which page I'am.

It works fine and highlights only one link from navigation if I'm on for example http://test.com/content, but when I get on home page aka http://test.com/ It highlights all of the li from navigations at once..

Tried to reproduce it in jsfiddle... but couldnt cause it would then redirect you to some other page or tell that page does not exists

Is there anything I can do?

Harugawa
  • 539
  • 5
  • 19
  • A good solution to this might be to use classes on the lis as opposed to their hrefs. – MCMXCII May 17 '16 at 15:42
  • 1
    You only need 1 onReady event. `$(document).ready(function() { ... });` is the same as `$(function() { ... });` so remove one or the other – johnniebenson May 17 '16 at 15:51

1 Answers1

1

How about using the "ends with" operator $= instead of "starts with" ^=

In this way you could just check for everything after the domain name. Just exclude the pathname that only contains the domain by using an "if":

$(document).ready(function () {
        if(location.pathname != "/") {
            $('li a[href$="' + location.pathname+ '"]').addClass('active');
        }
});

Also have a look at these two post:

Select <a> which href ends with some string

http://www.w3schools.com/jsref/prop_loc_pathname.asp

Community
  • 1
  • 1
Fuzzzzel
  • 1,733
  • 3
  • 23
  • 37
  • Actually you could use your example too and surround it with an if that excludes the case location.pathname points to your domain directly - didn't think about this before ... – Fuzzzzel May 17 '16 at 15:54
  • Hmm, interesting idea. Tho now it is not even adding class anywhere for some reason D: – Harugawa May 17 '16 at 15:56
  • ok, I fixed it by just adding a $ you suggested to my previous code : D – Harugawa May 17 '16 at 17:08