To set active page with playing jQuery

Posted: March 6, 2011 in jQuery
Tags:

I was struggling with this for a few, and finally solved it, so I thought I would share with everyone. I wanted to use a jQuery function to set the font color of the link representing the active page on a web site. After messing around with some different options, I came up with this:

$("#menu a").each(function() {
if(this.href == window.location) $(this).addClass("active-page");
}); 

Note: this is not something I ‘came up with’ exactly – I found it listed in a tutorial. I placed it in my javascript, and hurray! It worked. At least until I uploaded the code to my hosted site. When the site first loaded, none of the menu items were assigned the ‘active-page’ class. After clicking on any of them, however, it worked as expected. After being stumped for a few, I found a solution online that allowed setting the CSS for a menu link by assigning ID properties to the <body> tag in each web page. This worked, but was not desirable for a few reasons. The first is that it’s cumbersome, having to make changes to each file. Also, since I was using ASP.NET’s Master Page for my site template, I only had one body tag.

After fighting with it for 20 minutes or so, an alert statement showed me the error of my ways. On first load, ‘window.location’ was returning the base url of the web site (http://abc.com/). Once I clicked on an internal link, it returned one of the page urls (http://abc.com/home.php). So the script was running correctly, I just didn’t account for the different url on the site’s first load from an external link. I added a ‘homelink’ id to the home page’s menu item, and added this:

if(this.href == "http://abc.com/")
{
$('#homelink').addClass("active-page");
}

This way, on first load you’ll get the home page’s link set to the CSS you want to specify the active page. All other page loads are handled in jQuery’s each() function.

Advertisements
Comments
  1. parash says:

    how i can SEO my site ?

  2. codehunterbd says:

    Hi,
    Increase your backlinks and use proper keywords and also add fresh contents.I think these are main tricks for SEO also have a lot of tricks but you must study more from various blog sites for that.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s