Question

We want to add class on a link depending on window.location.pathname

our html is:

  <nav>
    <a href="index.php">Home</a>
    <a href="company.php">Company</a>
    <a href="products.php">Products</a>
    <a href="technical.php">Technical</a>
    <a href="services.php">Services</a>
    <a href="contactus.php">Contact Us</a>
  </nav>

and the document URL is www.nicadpower.com/index.php and so we did

var page_name = window.location.pathname.substring(1);

after getting/knowing the pathname to be 'index.php' we want jquery to do it's tricks comparing the 'page_name' to href and if it's equal would add a class="current"

making our html code to be like this

  <nav>
    <a href="index.php" class="current">Home</a>
    <a href="company.php">Company</a>
    <a href="products.php">Products</a>
    <a href="technical.php">Technical</a>
    <a href="services.php">Services</a>
    <a href="contactus.php">Contact Us</a>
  </nav>
Was it helpful?

Solution

$("a[href='" + page_name + "']").addClass("current");

That will select the a element with the required href attribute value, and add a class to it. See example fiddle here.

OTHER TIPS

You may not need JavaScript for this at all, see the example at the end.

You're looking for the "attribute equals selector", or possibly the "attribute ends with" selector nope, the equals selector works:

// The equals selector
$('nav a[href="' + page_name + '"]').addClass('current');

// The ends-with selector
$('nav a[href$="' + page_name + '"]').addClass('current');

The "attribute equals selector" is CSS 2.1 and broadly-supported, so you could probably do this without JavaScript at all, just using a stylesheet. The ends-with selector is CSS3 and probably not as well supported, certainly not if you need to support older browsers.

Here's an example page using both jQuery and CSS. The CSS version using the "attribute equals" selector works fine on IE7 and up, Firefox, Chrome, Opera, and Safari. (The CSS bit doesn't work on IE6, quelle shock.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top