0 Replies - 6070 Views - Last Post: 07 May 2009 - 09:30 AM

#1 Ironwil   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 05-May 09

Using jQuery to set active page

Posted 07 May 2009 - 09:30 AM

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://somewhere.com/). Once I clicked on an internal link, it returned one of the page urls (http://somewhere.com/Default.aspx). 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://somewhere.com/")

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.

This post has been edited by Ironwil: 07 May 2009 - 09:36 AM

Is This A Good Question/Topic? 0
  • +

Page 1 of 1