views:

38

answers:

2

Hey,

I have an ASP.NET website, on the masterpage I have a basic navigation menu:

<ul id="menu">
    <li><a href="Default.aspx"><span>Home</span></a></li>
    <li><a href="Services.aspx"><span>Services</span></a></li>                       
    <li><a href="HowItWorks.aspx"><span>How It Works</span></a></li>
    <li><a href="ContactUs.aspx"><span>Contact Us</span></a></li>
</ul>

My goal is to add a JavaScript function on the masterpage that will dynamically add the "active" class to the tag that represents the page the user is on. For example, if the user is on www.mywebsite.com/default.aspx, than the attribute [class='active'] should be added to the first link in the navbar. The active class basically just highlights the link so the user knows which page they are currently on.

Here is my JavaScript code:

<script type="text/javascript">
    $(document).ready(selectMenuItem);

    function selectMenuItem() {
        var name = getPageName();
        if (name)
            $('#menu a[href="' + name + '"]').addClass("active");
    }

    function getPageName() {
        var path = window.location.href.split('?')[0];
        var name = path.substring(path.lastIndexOf('/') + 1, path.length);
        return name;
    }
    </script>

Here is what happens, when the user visits any page on the site, the selectMenuItem() function executes. The function makes a call to getPageName() which returns the name of the page file that the user is viewing (ex: "default.aspx"). The function uses this name string to find which tag links to the page the user is currently on, when found the class is correctly added.

This code works great, however the process is case sensitive. Basically I'm at the mercy of the user. If they manually type in "mywebsite.com/DefUlT.aspx" than my code will fail because the casing in the substring "default.aspx" does not match the one in the tag. I could solve this problem by telling the JavaScript function to force the name string to be lower case, however this would mean that whenever I add new menu item I need to be sure I write the href attribute all in lower case, which isn't a big deal but it's not elegant enough for me. It wouldn't be a problem if I was the only one working on this site, but I will hand the work of to a number of other professionals and I feel stupid telling everyone, "be sure the href values are all lowercase or the code will break!"

Can someone interested in a challenge maybe tell me how to work around this? I'm extremely new to jQuery (started last night) so I'm sure there's an elegant solution that involes changing this line of code:

$('#menu a[href="' + name + '"]').addClass("active");

My problem is that I need the "href" attribute to be turned to lower case before the comparison is made to the name variable, I would then just perform "name.toLowerCase()" so that I know the case differences between the href attribute and name variable are irrelevant. Is there an equivalent jQuery selector which allows me to specify an expression perhaps?

Thanks,

-Andrew C.

+1  A: 

try this with .filter()

function selectMenuItem() {
    var name = getPageName();
    if (name)
        $('#menu a').filter(function(){
            return this.href.toUpperCase() == name.toUpperCase();
        }).addClass("active");
}
Reigel
Thanks for this method, I can see the logic behind it. I did have a few problems though, when I first ran it every navbar link ended up highlighted, I'm assuming this was because the brackets were left off on the href.toUpperCase == name.toUpperCase, both statements evaluated to null which made the == statement evaluate to true every time. However that was an easy fix :PThe bigger problem I had was for some reason the segment "this.href" returns the absolute path to the filename in the href attribute. It's easy to work around that but I thought that was odd.
no, I have forgotten `()` in `toUpperCase` haha my bad... :) well, I'm glad you solved it..
Reigel
A: 

I don't know of a way to do it with a selector, but looping through all your menu links as in the following, you could apply the toLowerCase() method to both the href and name, so you'd know the match would work, no matter what the user entered in the URL:

function selectMenuItem() {
    var name = getPageName();
    if (name){
        $('#menu a').each(function(){
            if($(this).attr('href').toLowerCase() == name.toLowerCase()){
                $(this).addClass('active');
                return;
            }
        });
     }
 }
Pat
Thanks, this worked like a charm! I should have thought about the logic of looping through each element at a time. Can't believe I missed that :D
You want the attribute selector.$("menu a[href='"+window.location+"']").addClass('active');
Keyo
Key, that code has a potential to fail because it depends on what the programmer typed in the href attribute being compared. The point is there has got to be a way to minimize this risk by forceing the data in the href attribute and the window.location value to the same case (upper or lower) so that the value will match correctly 100% of the time.