Use various colors to highlight links in the main menu depending on the current page

Is there a way to make each link in the main menu stand out by using a distinct color that matches its current page?

For instance, can we set the contact us link to red in the main menu when the current page is Contact Us?
Similarly, could we change the about us link to orange in the main menu if the current page is About Us, and so on?

Answer №1

To achieve this functionality, consider implementing the following JavaScript code:

Firstly, extract the current URL path:

let pathname = window.location.pathname;

For instance, if the returned value is "/about.html", you can utilize it to determine which element should be highlighted:

if(pathname === "/about.html"){
   document.getElementById("about").classList.add("highlighted");
}

Repeat the process for other URLs as needed.

Answer №2

a:active : triggered when a link is clicked and held down.
a:visited : indicates that the link has been visited before.

To highlight the link corresponding to the current page, you can define a specific style for that link -

.current {
   color: red;
   background-color: #000000;
}

Add the new class .current only to the relevant li (link), either on server-side or client-side using javascript/jquery.

You can utilize JQuery's .each function to iterate through the links with the code below:

$(document).ready(function() {
    $("[href]").each(function() {
    if (this.href == window.location.href) {
        $(this).addClass("current");
        }
    });
});

Depending on your website's structure and linked pages, you may need to narrow down the selectioon of links like this:

$("nav [href]").each ...

If you are using URL parameters, it might be necessary to remove these for comparison:

if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...

This method saves you from having to manually edit every page.

source

Answer №3

There are numerous methods to consider, determining the best one would require reviewing your specific code.

One option is to incorporate Javascript on each individual page in order to modify or insert classes for your links.

For example, on your contact us page you could implement a script similar to this:

var contactLink = document.getElementById("contactUs");
contactLink.classList.add("orangeLink");

Answer №4

You can dynamically add an active class to the menu item based on the current page being viewed.

For example, if you are on the contact page, you can add the active class to the "Contact Us" menu item. The same concept applies to the "About Us" page. To style these active classes, you can apply some CSS.

Here's an example for the contact-us page:

<ul>
    <li class="home"><a href="home.html">Home</a></li>
    <li class="contact active"><a href="contact-us.html">Contact Us</a></li>
    <li class="about"><a href="about.html">About Us</a></li>
</ul>

Now let's style it with some CSS:

.contact.active{
   color : red;
}
.about.active{
   color : orange; 
}

Implementing this will help you achieve the desired functionality.

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

Update the content of a bootstrap modal dialog following a successful upload

As part of a new service, I am modifying data in a database using a bootstrap modal dialog. However, I'm facing an issue where the name of a recently uploaded file is not appearing in the modal dialog body until I close and reopen it. Is there a way t ...

Issue when trying to populate an ASP.NET textbox control using the HTML5 "date" type

On my asp.net page, I have included an HTML5 TextBox control set to type "date." The code snippet for the control is as follows: <asp:TextBox ID="TextBoxMyDate" runat="server" type="date"/> Interacting with the control on the page works smoothly, a ...

Node JS confirmation dialog box

I need to incorporate a confirmation message in my application that will execute the action if the user clicks submit, but cancel the event if they don't. I have set up a route in Express for this purpose, however I want to prevent the backend code f ...

I am attempting to utilize a ref in React to access an element within a MUI modal, but I am encountering issues as the reference to the

I've been encountering an issue while trying to access the component did mount lifecycle method, as it's showing null. Interestingly, when I remove the modal, everything works as expected. However, inside the modal, the ref isn't functioning ...

Tips on accessing InnerText with VUEJS

I'm struggling with displaying the innerText generated by my generatePseudonym() function in a modal dialog. To better illustrate, here is a screenshot of what I mean: https://i.sstatic.net/pEl5P.png I am aiming to show the output Anastasia Shah as th ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...

What is the best way to deactivate multiple inputs using JavaScript?

I ran this code snippet: <body> <input placeholder="test1" class="input"/> <input placeholder="test2" class="input"/> </body> <script> document.querySelector(". ...

Employing jQuery to extract the text from the h4 class="ng-binding" element beyond the Angular scope

Is it possible to retrieve the current text content of <h4 class="ng-binding"></h4>? The text content is generated dynamically within the angular.js setup. I am interested in finding a way to extract this text using jQuery or JavaScript from ...

Show the form when the button is clicked

I want to create an application that allows users to click on a button in the top right corner (check image) to hide one div (topics) and show another div (a form for adding a new topic). Here is what it looks like: https://i.stack.imgur.com/YeRTw.png ...

Dynamic Button Creation with Ajax for Sending Post Requests

Looking for help in dynamically assigning an id to a specific element for a POST request and then applying a class to another element? I'm still learning JS, so I'm having trouble figuring it out... Essentially, my JSP page includes a forEach lo ...

Tips for targeting a specific box within a modal popup using jQuery

When using a modal popup, I have included the following code in jquery custombox to focus on a specific box when the popup opens: I am currently using version 1.1.3 of jquery custom box. $('.fadein').on('click', function ( e ){ ...

A guide to effectively displaying JavaScript variables within a jQuery function

Initially, I believed this was a problem specific to WordPress, but after spending hours attempting to resolve it, I suspect that it may actually be a broader JavaScript issue. I've been grappling with this challenge for a few hours now and I'm ...

Is there a way to bypass the default layout on app router in Next.js and implement our own custom page layout

Utilizing a default layout in layout.jsx, I passed all my other pages as children through props. In the page router, we typically configure the router path to specify which layout to use. However, in this new system, I am facing challenges with coding it. ...

Double Assignment in JavaScript

Can you explain the concept of double assignment in ExpressJS and its functionality? An illustration is provided below using a code snippet from an ExpressJS instance. var server = module.exports = express() ...

Issue with the Bootstrap carousel jQuery plugin

Hi everyone, I need some help with creating a multiple items bootstrap carousel. I keep getting an error message that says "#Carousel".carousel is not a function TypeError: "#Carousel".carousel is not a function. Can anyone guide me on how to fix this issu ...

Styling Material UI components with CSS is a great way to

I'm facing difficulties while working with Material UI components. Currently, I have a Material UI table and I want to center-align the text within it. The standard CSS of Material UI contains an element named MuiTableCell-root-60 which has a text-a ...

What is the best way to perfectly center my CSS menu in a fluid style layout?

Can you assist me with this issue? I am trying to center my CSS menu precisely in the middle of the user's screen, both vertically and horizontally. Since users have varying screen resolutions, I need a fluid example to achieve this. Below is the HT ...

Customizing the appearance of all anchor elements using vue/nuxt by adding a style property

I am currently working on a website where each category has its own color scheme applied to the anchor elements within it. Although I know I can use style binding like this: :style="{ color: theColor }" Manually attaching this to every link element seem ...

Error: The property "indexOf" cannot be accessed because n is not defined

After rendering a page and retrieving data from Firebase upon clicking a button, I encounter an error upon refreshing the page: Unhandled Runtime Error TypeError: can't access property "indexOf", n is undefined Source pages\[id].js (1 ...

Show the HTML code within the form with the identifier html-editor-form

I have four different sections which are displayed when the corresponding icon is clicked. The area labeled as visual-editor contains multiple HTML values. I am looking to showcase all the HTML values within the visual-editor class under the html-editor ...