SOLDIER-OF-FORTUNE
SOLDIER-OF-FORTUNE

Reputation: 1654

compare url string and menu string then add class using jquery

I have a URL which looks like this:

http://www.website.co.uk/en-us/aboutus/thegroup/test.aspx

I have a UL LI menu on the page:

<ul>
    <li><a href="/aboutus/thegroup/test.aspx">Test</a></li>
    <li>Hello</li>
    <li>Bye</li>
    <li>Something</li>
    <li>Cars</li>
</ul>

I am having the menu on every page and would like to use jquery to check that im on that page. If i am then make the A/li bold so the user knows they are on the page.

I have tried the following:

$(document).ready(function () {
  if(window.location.href.indexOf("test")) // 
     {
        alert("your url contains the name test");
     }
});

But id like something that doesnt involve hard coding the values of the URL string. As if the user decides to add more links to the UL/LI the jquery needs to check the link and the url automatically and add a class to the LI (so that i can style it).

Hopefully thats enough infomation.

Upvotes: 2

Views: 6726

Answers (4)

Rory McCrossan
Rory McCrossan

Reputation: 337570

The issue is because the indexOf() method returns -1 when the value is not found. You need to check for that value, not coerce the result to a boolean as you currently are. Try this:

$(document).ready(function () {
    var loc = window.location.href;
    $("ul a").each(function() {
        if (loc.indexOf($(this).attr("href")) != -1) {
            $(this).addClass("current");
        }
    });
});

You would need to make the selector a bit more specific, something like #menu a

Upvotes: 4

thecodeparadox
thecodeparadox

Reputation: 87073

$(document).ready(function () {
  var liTest = $('ul > li'); // ' was missing
  liTest.each(function() {
     if(window.location.href == $('a', this).attr('href')) // 
     {
        $(this).css('font-weight', 'bold');
        return;
     }
  });
});

Upvotes: 1

Alp
Alp

Reputation: 29739

indexOf returns -1 if the string is not contained:

(document).ready(function () {
  if(window.location.href.indexOf("test") != -1) // 
     {
        alert("your url contains the name test");
     }
});

Upvotes: 2

Andreas Wong
Andreas Wong

Reputation: 60526

This?

$('ul#menu a').each(function() {
   if(window.location.href.indexOf($(this).attr('href')) !== -1) {
      $(this).closest('li').addClass('yourClass');
   }
});

I added an id menu to your ul to basically differentiate your menubar with other uls that may be in the same page. also !== -1 as indexOf returns -1 if it can't find the string searched in the argument.

Upvotes: 2

Related Questions