Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 658
SOLDIER-OF-FORTUNE Avatar asked Jun 12 '26 04:06

SOLDIER-OF-FORTUNE


2 Answers

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

like image 164
Rory McCrossan Avatar answered Jun 14 '26 18:06

Rory McCrossan


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.

like image 25
Andreas Wong Avatar answered Jun 14 '26 18:06

Andreas Wong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!