How to highlight active page in a masterpage menu?
Asked Answered
M

6

6

I have a menu inside a masterpage (in a ASP.NET Web site), and i want to highlight active page in masterpage menu and submenus.

HTML:

<ul id="nav" class="sf-menu">
    <li class="current-menu-item"><a href="index.html">Home</a></li>    
    <li><a href="page.html">menu-2</a>
       <ul>
          <li><a href="page-full.html">full</a></li>
          <li><a href="page-features.html">featurs</a></li>
          <li><a href="page-typography.html">typography</a></li>
       </ul>
    </li>
</ul>

CSS:

#nav>li.current-menu-item>a,
#nav>li.current_page_item>a{
    color: #fe8300;
}

thanks in advance.

Mawson answered 12/6, 2013 at 7:57 Comment(1)
Write a javascript function in the master page to highlight desired menu item. Now call that function from aspx pages (on document ready).Brambling
M
16

finally i solved my problem with using jQuery:

    var str=location.href.toLowerCase();
    $("#nav li a").each(function() {
        if (str.indexOf($(this).attr("href").toLowerCase()) > -1) {
            $("li.current-menu-item").removeClass("current-menu-item");
            $(this).parent().addClass("current-menu-item");
        }
    });
    $("li.current-menu-item").parents().each(function(){
        if ($(this).is("li")){
            $(this).addClass("current-menu-item");
        }
    });
Mawson answered 21/6, 2013 at 10:36 Comment(1)
Perfect. Thanks.Gerent
V
2

There are many ways to do this. There are some easy and some ugly hacky ones:

Solution 1: Use a Menu Control. The standard .NET Menu Control has an easy solution to do this. This is the cleanest and fastest solution in my opinion. Have a look at this post. Maby it'll help you if you choose this solution.

Solution 2: You coud use some sort of javascript to highlight the current item. jQuery would make that easier if you dont want to write everything by yourself. For this solution have a look at this page. It's outdated but still effective.

Solution 3: This is kinda ugly solution and you can do that in many different ways: You could change the <a> elements to HyperLink controls and set some sort of session or cookie when you click on them. When set you could change the style based on the value the cookie has.

There are even more ways you could solve this but I think the first two solutions will help you.

Video answered 12/6, 2013 at 9:6 Comment(0)
T
1

check your url and get the html file name then compare it and set your css class in master page or make a menu UserControl seperate and then put it on master page.

You have to change your anchor tag to Hyperlinks

asp.net markup :

<li><asp:HyperLink runat="server" ID="lnk_full" NavigateUrl="page-full.html" Text="full" /></li>
<li><asp:HyperLink runat="server" ID="lnk_features" NavigateUrl="page-features.html" Text="features" /></li>
<li><asp:HyperLink runat="server" ID="lnk_typography" NavigateUrl="page-typography.html" Text="typography" /></li>

Codebehind :

protected void SelectMenu()
    {
        try
        {
            string page = Path.GetFileNameWithoutExtension(Request.AppRelativeCurrentExecutionFilePath);
            string pageDirectory = Path.GetDirectoryName(Request.AppRelativeCurrentExecutionFilePath);

            string category = Request.QueryString.Count>0 ? Request.QueryString[0] : string.Empty;
            if (pageDirectory.Length > 3)
            {
                pageDirectory = pageDirectory.Substring(2, pageDirectory.Length - 2);
            }
            if (pageDirectory != null && pageDirectory.Length > 0 && page != null && page.Length > 0)
            {
                switch (pageDirectory)
                {
                    case "Secure\\Clients":
                        switch (page)
                        {
                            case "page-full":
                                lnk_full.CssClass = "current-menu-item";
                                break;
                            case "page-features":
                                lnk_features.CssClass = "current-menu-item";
                                break;
                            case "page-typography":
                                lnk_typography.CssClass = "current-menu-item";
                                break;
                        }
                        break;
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

If your webpages are in root directory then don't switch for pageDirectory. and if you are using querystrings then you can switch for category. Hope this is helps you.

Tamper answered 13/6, 2013 at 7:17 Comment(0)
A
0
$(function () {
        $(".navbar‐btn a").each(function () {
            var hreff = this.href.trim().split("/").splice(3, 4);

            if (hreff.length > 1)
                hreff.splice(0, 1);

            if (hreff[0] == window.location.pathname.split("/").splice(1, 1)[0])
                $(this).parent().addClass("active");
        });
    })
Allpowerful answered 14/12, 2015 at 15:31 Comment(0)
H
0

This works fine for me during development and in local, but when I host it on IIS the active highlighting on the menu does not work. What am I missing here? Masterpage code below

$(document).ready(function () {
        //You can name this function anything you like
        function activePage() {
            //When user lands on your website location.pathname is equal to "/" and in 
            //that case it will add "active" class to all links
            //Therefore we are going to remove first character "/" from the pathname
            var currentPage = location.pathname;
            var slicedCurrentPage = currentPage.slice(1);
            //This will add active class to link for current page
            $('.nav-link').removeClass('active');
            $('a[href*="' + location.pathname + '"]').closest('li').addClass('active');
            //This will add active class to link for index page when user lands on your website
            if (location.pathname == "/") {
                $('a[href*="index"]').closest('li').addClass('active');
            }
        }
        //Invoke function
        activePage();
    });
Hirza answered 9/9, 2019 at 7:0 Comment(0)
C
-1
jQuery(document).ready(function() {
  var str = location.href.toLowerCase();
  jQuery('#topnav li a[href=\'' + str + '\']').addClass('active');
});
Cholecyst answered 30/6, 2016 at 4:52 Comment(2)
Although this may answer the question, explain why your answer is better/ an improved version of the older (accepted) answer. This to help others stumbling onto this answer later on...Eldon
i'm sorry for this, just only to add option for writing of older answer,Cholecyst

© 2022 - 2024 — McMap. All rights reserved.