views:

190

answers:

3

I'm trying to apply a class to a link only if the current page equals that link.

I find the current page with:

var pathname = window.location.pathname.split("/")[window.location.pathname.split("/").length - 1];

This grabs the url of the page and saves whatever is after the last /, which in the case of my page is 'index.html'.

Now, I'm using links (anchor tags with display: block) that have a background color change when you mouse over them.

My goal is to have those links already colored, as if they were hovered, when you visit the page that the link links to.

So I used:

if (pathname == $(".linkclass").attr("href")){
    $(this).addClass("linkHover");
}

Now obviously the "this" modifier doesn't work, but how do I tell it to apply this class to only whichever instance of linkClass passes the if statement? (And not EVERY instance of .linkclass, of which there are multiple).

Thanks!

+1  A: 

Maybe try something like this:

$("#a.linkClass").each(
    function() {
        if (pathname == $(".linkclass").attr("href")) {
            $(this).addClass("linkHover");
        }
    }
);

Or similar. The idea is selecting all the menu link anchors, then cycle through them and perform your test using the each() function.

jeef3
Oh wow, I forgot about that you can call function() in jquery like that, thanks!
Chris Riley
np, looks like you found a quicker way though :)
jeef3
+5  A: 

I figured it out, but I'll answer it in case someone comes across a similar issue.

Instead of the if statement, I figured jquery could handle the comparison using it's own selection engine. At first I looked for .equals or something, but I figured it out with:

var pathname = window.location.pathname.split("/")[window.location.pathname.split("/").length - 1];
$(".linkClass[href='" +pathname+ "']").addClass("linkHover");

You can use variables in jquery selectors, and select against attributes, so this works perfectly.

Chris Riley
nice - you beat me by 10 seconds!
Andy Gaskell
+1  A: 
$("a.linkClass[href='" + pathname + "']").addClass("linkHover");

Edit: Chris beat me to it. Upvoting his.

Joe Chung
Meh...by like a minute. +1 to you too.
womp