Highlight the active page or section dynamically using HTML and jQuery - How can it be achieved?

What am I trying to achieve? I am attempting to use jQuery to dynamically highlight the current page from the navigation bar.

Am I new to jQuery/HTML? Yes, please excuse my lack of experience in this area.

Have I exhausted all resources looking for a solution? Absolutely! I have searched through various StackOverflow posts but haven't been able to find a working solution for my specific issue.

  • Navbar highlight for current page
  • How to make css a:active work after the click?
  • jQuery current page highlight
  • highlighting the current page in a list of links using css / html

What's the issue at hand? My problem lies in trying to keep the selected section of my navigation bar highlighted in green once it has been clicked on by the user.

I have successfully implemented hover-over functionality, however, maintaining that color post-click seems to be elusive.

For your information, I am currently using #links and links.html in my "navigation menu" to cater to both scenarios, although ultimately I plan to have separate menus for .html pages and #sections within a page.

Did I provide a simple example to replicate the problem? Yes, see below

index.html:

<!DOCTYPE html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <link rel="stylesheet" href="test_main.css">
    
</head>

<body>

    <div class="navigation">
        <a href="test.html">Home</a>
        <a href="#section_a">Section A</a>
        <a href="#section_b">Section B</a>  
      </div>

      <script>
          $(function(){
              $('a').each(function(){
                  if ($(this).prop('href') == window.location.href) {
                      $(this).addClass('active'); $(this).parents('li').addClass('active');
                  }
              });
          });
      </script>
            
    <p>Example text</p>

</body>


main.css:


/* Add a white background color to the top navigation */
.navigation {
  background-color: #555555;
  color: #ffffff;
  overflow: hidden;
}

/* Style the links inside the navigation bar */
.navigation a {
  float: left;
  background-color: #555555;
  color: #ffffff;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Change the color of links on hover */
.navigation a:hover {
  background-color: #000000;
  color: #ffffff;
}

.active {
  background-color: #00ff00;
  color: #00000
}

I am aware that a static solution involving setting class="active" within the navigation class could work, but I find this to be cumbersome and less maintainable in the long run.

Answer №1

Your code is functioning correctly, however it may not be applying the style to replace ".navigation a" due to priority reasons. You could try adding "!important" to override other styles.

.active {
  background-color: #00ff00 !important;
  color: #000000 !important;
}

If you want this to activate on a menu with a URI fragment/hash, you may need to apply a "click" event.

Answer №2

Summary: To highlight the top-navigation menu based on the page, add navigation a:not(.active) to the main.css file.

Detailed explanation:

index.html:

<!DOCTYPE html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <link rel="stylesheet" href="test_main.css">
    
</head>

<body>

    <div class="navigation">
        <a href="test.html">Home</a>
        <a href="#section_a">Section A</a>
        <a href="#section_b">Section B</a>  
      </div>

      <script>
          $(function(){
              $('a').each(function(){
                  if ($(this).prop('href') == window.location.href) {
                      $(this).addClass('active'); $(this).parents('li').addClass('active');
                  }
              });
          });
      </script>
            
    <p>Example text</p>

</body>

main.css:


/* Customize top navigation bar */
.navigation {
  background-color: #555555;
  color: #ffffff;
  overflow: hidden;
}

/* Styling links in navigation bar */
.navigation a:not(.active) {
  float: left;
  background-color: #555555;
  color: #ffffff;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

/* Link hover effects */
.navigation a:hover {
  background-color: #000000;
  color: #ffffff;
}

.active {
  color: #00000;
  float: left;
  background-color: #00ff00;
  color: #00000;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

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

What is the best way to manipulate and update individual counters in React components?

I developed a ticket ordering system for a project, but encountered an issue where increasing the quantity of one ticket also resulted in the incrementation of the other ticket's counter. I suspect this occurs because only one value is stored in the s ...

What steps should I take to complete the Counting Cards challenge on freecodecamp using my own code?

Here is the issue at hand: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/counting-cards I'm facing a problem while attempting to achieve 0 Hold in the return by using the Cards Sequence 7, 8, 9. I am aw ...

Guide on keeping a footer anchored at the bottom of a webpage

I have gone through numerous tutorials on how to position the footer at the bottom of my webpage, but I'm still struggling to accomplish it for my own site. Some of the resources I've consulted include: Understanding techniques to keep the fo ...

Tips for structuring a news thread with a staggered approach

On my Drupal 8 website, I have set up a newsfeed. How can I display the news items in staggered rows? I would like the first item to align on the left and the second item to be on the right, repeating this pattern for all subsequent items. Currently, I am ...

Deciphering the intricacies of VUEX-STORE modules

Consider this scenario: I have two separate lists - one for income and one for outcome. Each list has its own storage, and I am adding these storages as modules in index.js. While I could create a single repository for both income and outcome, displaying ...

The form submits automatically upon loading the page with empty input fields

I recently created a form on my website located at . Initially, the form functioned correctly and the PHP script executed as expected. However, I am now encountering an issue where every time I load the page, a popup message appears indicating that the for ...

Jquery spinner overlay for enhanced loading experience

Currently, I am incorporating jQuery/Ajax in my project and wanted to include a spinner when an ajax request is made. The specific scenario involves two tabs on the UI: Home and Activities. When the user clicks on the Activities tab, an ajax request is sen ...

What is the best way to pinpoint particular text within a paragraph that includes numerous line breaks?

So here is the puzzling situation I'm grappling with. Here's a peek at the HTML snippet: <p>This paragraph has <br><br> two unusual line breaks <br><br> and it happens TWICE!</p> The problem arises when tryi ...

Guide on making a Vue.js show/hide button for each element on a webpage

There is a feature to toggle between displaying "more" or "less" text, but currently the @click event affects all elements causing them to show all the text at once. I realize that I need to pass a unique value to distinguish each element, but I am curren ...

Implementing Ajax functionality in MVC 3 to return a partial view

I wanted to express my gratitude for this invaluable site that has taught me so much. Currently, I am working on an MVC3 component where I need to populate a selectlist and upon user selection, load a partial view with the relevant data displayed. Everythi ...

Creating form elements in ReactJS dynamically and storing their values in an array

I need to render 3 materialUI TextFields multiple times, depending on the integer input by the user before rendering the form fields (the integer is stored in a variable called groupMembersCount). I am using a functional component in ReactJS with an array ...

Override CSS properties / prevent inheritance

I'm currently facing a challenge in Wordpress where I need to insert a link quickly, but there are intricate styles applied to all the anchor links within a specific section. Here is a snippet of the CSS selector and styles being used: div.content-ro ...

Guide on leveraging a private GitHub repository as a yarn dependency without installing internal dependencies

Recently, I have been attempting to incorporate a private GitHub repository as a dependency within multiple repositories at my workplace. Within the primary package.json file, our dependency is outlined as follows: "mycompany-models": "https://github.com ...

Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve ...

Selection tool for Material UI Fields

Is there a way to design something similar to this layout using Material UI? I'm looking to create a selection between fields. Any advice on how to achieve this in Material UI? ...

Solving synchronization issues when updating and selecting MySql data in a Node.js environment with concurrent multiple requests

Currently, I'm using expressJS with an endpoint that connects to a MYSQL database. This endpoint executes a query to retrieve data and assigns the first result to a user by updating a specific field with the user ID. The rule is that each row can onl ...

Unexpected Error Causing Failure in jQuery Ajax Call

My jQuery ajax call is encountering an undefined error. Here is my JavaScript code snippet: $.ajax({ type: "POST", url: "Data/RealTime.ashx", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", timeout: 15000, ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

handling component interaction with react-redux store

Currently, I am in the process of developing my first significant project using react-redux. While trying to establish state mapping between components in react-redux, I seem to have missed a crucial step. Almost everything is functioning smoothly except ...

Guide to establishing a primary filter for my Json information with Angular.js?

After spending multiple days searching and reading, I am struggling to set an initial value for the data from a Rails JSON file in my application. The app focuses on incident tickets, and although I am able to retrieve all entries from the database using d ...