A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Code Snippets > jQuery > Highlight All Links To Current Page Submit one!

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.

Subscribe to The Thread

  1. Steven says:

    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 says:

    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 says:

    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.

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---