2

I have a simple unordered list with links in it.

<body>
    <div id="topMenu">
        <ul>
            <li><a class="selected" href="../Default.aspx">Start</a></li>
            <li><a href="../Category/ShowAll.aspx">Categories</a></li>
            <li><a href="../Elements/ShowAll.aspx">Elements</a></li>
            <li><a href="../Articles/ShowAll.aspx">Articles</a></li>
        </ul>
    </div>
    <asp:ContentPlaceHolder ID="MainContentPlaceholder" runat="server">
    </asp:ContentPlaceHolder>
</body>

I want to change the class of the link i click to the "selected" class, which is the easiest way to do this. I thought about making it into linkbuttons and saving the info in the session, but that seems overkill, there has to be an easier approach?

Brian Hvarregaard
  • 4,081
  • 6
  • 41
  • 77

2 Answers2

0

Well, you can just put the <a> to be runat="server" and then access them from codebehind:

hyperLink.Attributes["class"] = "opened";

You can have this in your master page with the menu, and you can have your child pages send the id of the hyperlink they need selected, something like

In your master (the linkWrapper can be your <ul> as runat server):

(HyperLink)linkWrapper.FindControl(childPageMenuAnchorLinkId);

In your child:

masterPage.ChildPageMenuAnchorLinkId = "link_Customers";
Denis Biondic
  • 7,943
  • 5
  • 48
  • 79
  • Ask if you need more clarifications – Denis Biondic Jul 18 '11 at 20:13
  • How do i get that reference to the masterPage, in my child pages i have only a "Master" object, that refers to the masterpage. And how to make the public property? – Brian Hvarregaard Jul 18 '11 at 20:21
  • Cast the Master object to your master page type. For property you write it yourself, I've just named it ChildPageMenuAnchorLinkId for the sake of the example, you can't have it anyway you want... – Denis Biondic Jul 18 '11 at 20:22
0

If you are using jQuery, the link from this other SO question may help you out.

jQuery add class .active on menu

EDIT:
Corrected script to use the 'selected' class, not 'active' according to OP's use.

So, if I "borrow" the script from the other answer, I believe this will work, again, if you are using jQuery...

$(function(){
    var url = window.location.pathname, 
        urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
        // now grab every link from the navigation
        $('#topMenu ul li a').each(function(){
            // and test its normalized href against the url pathname regexp
            if(urlRegExp.test(this.href.replace(/\/$/,''))){
                $(this).addClass('selected');
            }
        });
});
Community
  • 1
  • 1
Alban
  • 704
  • 1
  • 6
  • 11