Javascript get current page and add class to an element depending on the URL

I'm using a navigation bar, and I want to have an active class on elements when they're on the element's page.

For instance, I'd need jQuery to check the url of the current page, and if the url is http://supjamess.tumblr.com/, it'd add the class active to the a element .index, http://supjamess.tumblr.com/ask & it'd add the class active to the a element .ask, and so on.

If anyone could provide a code it'd be extremely helpful.

Upvotes: 0

Views: 2019

Answers (2)

Austin
Austin

Reputation: 6034

switch based off of location.pathname

 if (location.pathname == "/") {
      $("a.index").addClass("active");
 } else if (location.pathname == "ask") {
      $("a.ask").addClass("active");
 }
 ... and so on

additional pages are added with additional else if statements, so the code becomes:

 if (location.pathname == "/") {
      $("a.index").addClass("active");
 } else if (location.pathname == "/ask") {
      $("a.ask").addClass("active");
 } else if (location.pathname == "/tagged/layout") {
      $("a.layout").addClass("active");
 } else if (location.pathname == "/YOUR PATH") { // to add aditional pages, replace CAPS
      $("a.CLASS OF NAV LINK").addClass("active");
 }

You can try out and experiment with javascript on jsfiddle.net, or in your own console (f12 in most browsers)

Upvotes: 1

Brandon - Free Palestine
Brandon - Free Palestine

Reputation: 16656

My example requires jQuery:

if ( window.location.pathname == '/' ) {
    var url_class = 'index';
} else {
    // Very first part of the path, so /path/to/url returns 'path'
    var url_class = window.location.pathname.split('/');
    url_class = url_class[1];
}

$('a.' + url_class).addClass('active');

What this basically does, is get the pathname component of the URL (After the domain and before the query string, see here) and then checks to see if it is '/', aka index and manually sets the URL class to 'index'.

Otherwise, it gets the first component of the URL, so /ask returns ask, /questions/bar returns questions, /users/edit/5 returns users, /tagged/layouts returns tagged, etc.

Then jQuery adds the class active to any element with the given class.

Upvotes: 2

Related Questions