Ways to emphasize the current page in a masterpage menu

In my ASP.NET Web site, I have a menu inside a masterpage and I am looking to highlight the active page in both the masterpage menu and submenus.

Here is the HTML structure:

<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">features</a></li>
          <li><a href="page-typography.html">typography</a></li>
       </ul>
    </li>
</ul>

And here is the corresponding CSS for highlighting the active item in the menu:

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

Thank you in advance for your help!

Answer №1

After some trial and error, I was able to resolve my issue using the power of 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");
        }
    });

Answer №2

There are numerous approaches to achieve this task, ranging from straightforward to more complicated methods:

Method 1: Utilize a Menu Control. The standard .NET Menu Control offers an easy solution for this issue, which I believe is the most efficient and cleanest approach. Refer to this post for more information.

Method 2: You can employ Javascript to highlight the current item on your menu. Using jQuery would simplify the process if you prefer not to code it from scratch. Check out this page for guidance, although it may be outdated but still effective.

Method 3: This method may seem less elegant but offers various options: Convert the <a> elements to HyperLink controls and establish a session or cookie whenever a link is clicked. Based on the value stored in the cookie, adjust the style accordingly.

While there are several other solutions available, I believe the first two methods provided will suffice for your needs.

Answer №3

Ensure to verify the URL and determine the HTML file name before comparing it and assigning your CSS class in the master page. Alternatively, you can create a separate menu UserControl and add it to the master page.

Remember to update your anchor tags 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, avoid switching for pageDirectory. If you're using querystrings, consider switching for category. I hope this information is helpful to you.

Answer №4

$(function () {
        $(".navbar‐btn a").each(function () {
            var links = this.href.trim().split("/").splice(3, 4);

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

            if (links[0] == window.location.pathname.split("/").splice(1, 1)[0])
                $(this).parent().addClass("active");
        });
    })

Answer №5

I have encountered an issue where the active highlighting on the menu does not work when I host my website on IIS, even though it works perfectly during development and in a local environment. Can anyone point out what might be missing here?

$(document).ready(function () {
        //This function can be named as desired
        function activePage() {
            var currentPage = location.pathname;
            var slicedCurrentPage = currentPage.slice(1);
            
            $('.nav-link').removeClass('active');
            $('a[href*="' + location.pathname + '"]').closest('li').addClass('active');
            
            if (location.pathname == "/") {
                $('a[href*="index"]').closest('li').addClass('active');
            }
        }
        
        activePage();
    });

Answer №6

Once the jQuery library is loaded and the document is ready, this script will check the current URL in lowercase and add an 'active' class to the matching link in the top navigation menu.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to determine which .js script is modifying a particular HTML element?

Let's take a look at a specific website as an example: This particular website calculates value using a .js script embedded in the HTML itself. Upon inspecting the source code by pressing F12, we can locate the element containing the calculated valu ...

What is the method for identifying if a user has logged into Facebook Connect within an ASP.NET User control?

Is there a way to detect if a user is logged into Facebook using an ASP.NET User control? One option is to check their login status using the Facebook Javascript SDK in a call made by JavaScript. (FB.getLoginStatus) But how can a server control determine ...

Adding text to the end of a web address through a submission form

Here is an example of a form: <form method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Engine"> <input type="submit"> I am looking t ...

What is the best way to slide a Bootstrap 4 modal dialog to the right when closing, utilizing CSS or JavaScript

I have successfully added a CSS animation to my Bootstrap modal that slides in from the right when opening, which looks great. However, I am looking for a way to slide it back to the right when a custom close button is clicked, instead of just hiding it wi ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

Triggering an event between 2 AngularJS controllers using bidirectional binding

This is a question specifically regarding Angular 1, not Angular 2. I have a unique setup where I have Controller A responsible for a specific page. On this page, there is a custom directive that takes input from Controller A but also has its own controll ...

Duplicate the form field and add a button beneath the newly generated elements

Clicking the "Add New" button below will add new fields to the form. While everything is functioning properly, I would like the newly created fields to appear above the button instead of below it. How can this be achieved? (function($) { "use strict" ...

Is there a way to create an input field that accepts only numbers and behaves like a password field simultaneously?

I am attempting to develop an input field for entering a PIN. I would like the PIN to be masked on mobile devices, similar to how passwords are obscured in password input fields. I came across a suggestion on stackoverflow regarding this, but unfortunately ...

"Streamlining data entry with an uncomplicated HTML form input that accepts multiple values from a

As I understand it, a barcode scanner functions as nothing more than a keyboard that transmits keycode 13 after each scan. My task is straightforward: I have a basic form with only one input field and I want the ability to scan numerous barcodes and then c ...

Fluid overlap of divs in Bootstrap framework

I am currently in the process of making style adjustments to a website at One specific change I've made is adding a top bar image. However, I've encountered an issue where the top bar graphic overlaps the navigation when the page is resized too ...

Strategies for styling the contents within <details> while excluding <summary> in CSS

I'm attempting to apply a 10px padding to the Story box using CSS, without introducing any additional HTML elements into the website code. Is there a way to include the padding in the Story box without incorporating a new HTML element? To clarify: H ...

CSS: Inaccurate positioning and border-radius causing gap between div and border-bottom

My goal was to create a card game with multicolored, double-sided borders, but I encountered issues when trying to implement this feature. Initially, I attempted to use an onclick event to change the border color, but it didn't work as expected. I fi ...

Update the text on the form submit button after it has been submitted

Is there a way to change the text on a submit button after it has been clicked? I have a form with a button and I want to switch the text from "click" to "Next" once the form has been submitted. <form> <div class="form-grou ...

How to access a webpage on your Android device without the address bar visible

My question relates to sending Push Notifications through OneSignal. Upon clicking a push notification, it automatically redirects the user to my website. Is there a way to hide the address bar on the browser when this happens? I attempted using the follo ...

What are the most effective strategies for incorporating Entity Framework in business logic?

As a beginner using the Entity framework for the first time, I am wondering if the approach I have taken is considered best practice. In my business logic, I have created a separate class to handle the entity context. However, I have noticed that in tutori ...

Seeking guidance on traversing a nested list with JQuery

I'm facing a rather simple issue, yet I've spent countless hours trying to resolve it without success. The goal is to show a nested list whenever a parent list item is clicked. Here's the jQuery code: <script type="text/javascript"> ...

Inquiry from a newcomer: ASP.NET with jQuery

I am working on a webform with a file upload button that has some specific requirements. Whenever the file is uploaded using the button, I need the C# code behind to execute first before any jquery functions are called. <script> $(document.read ...

Modify the web.config file using the get-content command and perform the replacement operation in powershell

As a beginner in Powershell commands, I have been using get-content followed by .replace to make edits to portions of the web.config file on my server. Can anyone confirm whether or not this method is considered safe for editing the web.config? Appreciate ...

The save feature becomes dysfunctional after switching to the Material-UI dependency in a React project

After integrating the Material-UI dependency into my ReactJS code, I encountered an issue where the "save" functionality no longer works properly. Previously, when editing a task in my simple Todo list app, the new name would be saved successfully. However ...

Obtain Insights into Community Tab Information on Youtube using Python

I have been attempting to retrieve information from the Community Tab of a YouTube channel, but it appears that this feature is not supported by the YouTube API that I've been utilizing. Despite my efforts, which include parsing the HTML, I have not b ...