Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Highlight All Links To Current Page

$(function(){
       $("a").each(function(){
               if ($(this).attr("href") == window.location.pathname){
                       $(this).addClass("selected");
               }
       });
});

This function will add the class "selected" to any links (even relative) that point to the current page.

Comments

  1. Steven
    Permalink to comment#

    I’m looking for a script that has a menu that shows what part of the page ur on. EX:

    LINK 1 LINK2 LINK3 (bold cause ur on that area)

    LINK 3 Area

  2. Nathanial

    This is exactly what I’m looking for, but I’m unsure how to deploy it…
    Does this need to go in Script tags in the Head section of my page?
    How do I define the “selected” class in my styles.css sheet?

  3. Ken-chan

    How can I edit this line:

    if ($(this).attr(“href”) == window.location.pathname){

    into something that may result to true as long as the pathname is found. I need an alternative for the == operators. Is there something in JS that emulates SQL’s “LIKE”?

    Thanks.

    • Cameron Spear
      Permalink to comment#

      You can use regular expressions to achieve functionality that emulates SQL’s “LIKE.” It’s much, much more powerful that “LIKE,” but also much, much more complicated to learn.

      Trying to explain it here is beyond the scope of this issue, but you can find more information about JavaScript’s .match() method at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match and all you could ever need to know about Regular Expressions at http://www.regular-expressions.info/javascript.html.

      While complicated to learn, Regular Expressions (often abbreviated RegEx or RegExp) are incredibly useful and while I still have a lot to learn about them, what I have learned has made a lot of complicated situations a lot simpler.

  4. Richard
    Permalink to comment#

    Thank you very much for this, there are hundreds of scripts about that do this , but this is the first one that actually works, does what it says on the tin. You are a genious, and have saved me a lot of pain, Thanks again!!!!!!!!!

  5. Edward Carlson
    Permalink to comment#

    Ah, this is so difficult! I don’t understand any of it :(

    I guess I’ll just have to pay someone to keep working on my site.

  6. Rai
    Permalink to comment#

    Mmm, don´t sure why but is not working for me.
    I think that wordpress make this automatically adding .current to the currents pages.

  7. Jason Paul
    Permalink to comment#

    This looks to be the most succinct code I’ve come across for this. But I still can’t get it to work. I’m working on a Childtheme of Twenty Ten. If you have any tips on why it’s not working would love to hear it.

  8. Chris Bowyer

    Above code didn’t work for me, but this code I found did…

    
    $(function() {
    	$("#menu a").each(function() {
    		if (this.href == window.location) {
    			$(this).css("color", "#FF0");
    		};
    	});
    });
    
    
    • Cameron Spear
      Permalink to comment#

      You can reference http://stackoverflow.com/questions/5874652/prop-vs-attr for more about prop vs attr.

    • Jesus
      Permalink to comment#

      This code worked for me as well.

    • Ubong
      Permalink to comment#

      Works like a charm> thank Chris

    • Maulik
      Permalink to comment#

      Thanks sir.. it is really working..! :-D
      thanks once again.

  9. Bryan

    for anyone having trouble implementing this, all you need to do is:

    1. place the code snipped inside in the head of your web document or external .js file

    2. create your selector class in your css file.
    .selected{color:#F00;} or whatever you like.

    • Bryan

      after further inspection. this didnt work…

    • Pete
      Permalink to comment#

      Really handy post – I love the web for this sort of help!

      @Bryan, your tip worked a treat for me :o)

  10. scooter29
    Permalink to comment#

    Thanks Chris Bowyer.

    • scooter29
      Permalink to comment#

      I just mix both

      $(function() {
      $(“body a”).each(function() {
      if (this.href == window.location) {
      $(this).addClass(“selected”);
      };
      });
      });

  11. ewroman
    Permalink to comment#

    sometimes (if both classes have same attribute, this case “background”) you should make your css code with !important.

    for example; link with class somelink

    css code;

    a.somelink {
    background:white;
    }

    .selected {
    background:red !important;
    }

    with “!important” , red bg will pass the white bg. and when selected you will see red. if important not given you will see white bg, that case you think code not works ;)

  12. Gab
    Permalink to comment#

    This worked like a charm in my custom Tumblr-theme, and the code is a lot sexier than the other snippets I found on the webz. Did not even break a sweat.

    Sweeet.

        $(function() {
            $("#mainNav a").each(function(){
                if ($(this).attr("href") == window.location.pathname) {
                    $(this).parent().addClass("current");
                }
            });
        });
    

    Used the parent-method to attach .current to ‘s parent .

  13. Gab
    Permalink to comment#

    This worked like a charm in my custom Tumblr-theme, and the code is a lot sexier than the other snippets I found on the webz. Did not even break a sweat.

    Sweeet.

        $(function() {
            $("#mainNav a").each(function(){
                if ($(this).attr("href") == window.location.pathname) {
                    $(this).parent().addClass("current");
                }
            });
        });
    

    Used the parent-method to attach .current to a’s parent li.

  14. David Thomas
    Permalink to comment#

    Why use each() when addClass() itself iterates over each of the selected elements:

    $('#mainNav a').addClass(function(){
        return this.href == window.location.href ? 'current' : '';
    });
    

    Admittedly the ternary/conditional-operator could be replaced by a simple if/else, for simplicity, but the above is a little more concise, and just as readable I think.

    • Wayne
      Permalink to comment#

      David, this works perfect for me! Verrrrrrry nice!

      For the benefit of others (newbies like me), this is what I did: Since I am using ‘thispage’ instead of ‘current’ for my class, I changed ‘current’ to ‘thispage’ in the code, like so:

      $(function() {
      $('#mainNav a').addClass(function(){
          return this.href == window.location.href ? 'thispage' : '';
      });
      });
      

      Then, I inserted it in my page just before the </header>, making sure I wrapped the thing in opening and closing script tags and added a CDN like Google’s (before the function), like so:

      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
      <script>
      $(function() {
      $('#mainNav a').addClass(function(){
          return this.href == window.location.href ? 'thispage' : '';
      });
      });
      </script>
      

      And then, in my main.css file, I added:

      #mainNav a:hover, #mainNav a:active, #mainNav a:focus, #mainNav a.thispage {
          color: #FF86FF;
          text-decoration: none;
      }
      

      And, PRESTO! it works like a champ!

    • Luis A Melendez
      Permalink to comment#

      Thank you David! I been looking for this solution for a long time without success, and now, I can finally say found it. Thanks again.

  15. Alexander
    Permalink to comment#

    Hello Chris!
    I’m using this snippet to control my custom sidebar menu in WordPress, which is simply a list with a number of links in it (html widget). The script seems to work fine, but i get weird result and i have no clue what exactly causes the problem

    The problem is:
    only the first link gets the necessary class. If i click other list items, nothing happens – the list item styled as usually, not as my .current-page class says.

    I’m probably doing something wrong, but none of the solutions seem to work for me.

    Here is my code:

    Could you please help?

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```