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!
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:
You can use variables in jquery selectors, and select against attributes, so this works perfectly.