Adjust Menu Selection Color Based on the HTML Page Being Accessed

I am working on a project where I want to dynamically change the menu color based on the page being loaded. Since this is an HTML project, I cannot use server-side languages for this. Instead, I decided to retrieve the name of the HTML file being loaded and adjust the menu color accordingly. However, I encountered a strange issue with this approach. Let me elaborate.

My Menu :


      <nav>
            <ul>
                <li><a class="menu-option" id="about" href="about.html">About</a></li>
                <li><a class="menu-option" id="trainer" href="#">Trainer / Consultant</a></li>
                <li><a class="menu-option" id="testimonial" href="#">Testimonials</a></li>
                <li><a class="menu-option" id="programs" href="#">Programs</a></li>
                <li><a class="menu-option" id="contact" href="#">Contact us</a></li>
            </ul>
        </nav>

The JS


$(document).ready(function() {
    $("header").load("includes/header.html");
    $("footer").load("includes/footer.html");
    var page = location.pathname.split("/").slice(-1);
    switch (page[0])
    {
        case "about.html":
            $(".menu-option").css('color', 'white');
            $("#about").css('color', '#E45C02');
            break;
        case "trainer.html":
            $(".menu-option").css('color', 'white');
            $("#trainer").css('color', '#E45C02');
            break;
        case "programs.html":
            $(".menu-option").css('color', 'white');
            $("#programs").css('color', '#E45C02');
            break;
        case "testimonial.html":
            $(".menu-option").css('color', 'white');
            $("#testimonial").css('color', '#E45C02');
            break;
        case "contact.html":
            $(".menu-option").css('color', 'white');
            $("#contact").css('color', '#E45C02');
        default:
            $(".menu-option").css('color', 'white');
            break;
    }


});

While inspecting with Firebug, I noticed that the case was being invoked but the color of "About" was not changing. To troubleshoot, I added an alert in the "about" case:


case "about.html":
            alert("about");
            $(".menu-option").css('color', 'white');
            $("#about").css('color', '#E45C02');
            break;

Surprisingly, adding the alert made it work as expected. I am puzzled about why the code fails without the alert statement. What purpose does it serve? What am I overlooking here? Do I need to add a timeout function?

I also attempted enclosing the switch case inside a jQuery ready function for the header:


$("header").ready(function(){
// Switch case here
// Still no luck !
});

Answer №1

The reason behind needing to wait for the .load() function to complete is because it is asynchronous, meaning you must ensure that the data loading process is finished before performing any actions that depend on the loaded data.

One way to address this is by passing a callback function as the second argument to .load(), which will be executed once the data has been successfully loaded. This allows you to execute the switch statement within that callback function.

For example:

$(document).ready(function() {

    function onHeaderLoaded() {
        var page = location.pathname.split("/").slice(-1);
        switch (page[0]) {
            case "about.html":
                $(".menu-option").css('color', 'white');
                $("#about").css('color', '#E45C02');
                break;
            case "trainer.html":
                $(".menu-option").css('color', 'white');
                $("#trainer").css('color', '#E45C02');
                break;
            case "programs.html":
                $(".menu-option").css('color', 'white');
                $("#programs").css('color', '#E45C02');
                break;
            case "testimonial.html":
                $(".menu-option").css('color', 'white');
                $("#testimonial").css('color', '#E45C02');
                break;
            case "contact.html":
                $(".menu-option").css('color', 'white');
                $("#contact").css('color', '#E45C02');
                break;
            default:
                $(".menu-option").css('color', 'white');
                break;
        }
    }

    $("header").load("includes/header.html", onHeaderLoaded);
    $("footer").load("includes/footer.html");

});

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

"Using jQuery's animate() function to dynamically change text content

I'm currently venturing into the world of jQuery animate() and decided to create a presentation-style project for practice. However, I've hit a roadblock when attempting to alter the text within my div element in the midst of an animation utilizi ...

Tips for deleting an image file, or any file, from a Node.js Express server

Being a novice in the field of web development, I decided to embark on creating a basic E-commerce application as my first project. I managed to make good progress until I hit a roadblock while trying to remove an image file of a product: I utilized expres ...

Loading scripts dynamically with async/await in JavaScript

I may be committing a typical beginner error. Aim I have a script named loader.js, where I intend to provide a collection of JavaScript files that control the shape, size, and position of components. The structure of the file is as follows: const loadSc ...

transferring a variable between two Ajax functions

I'm a beginner in the world of php and ajax, and I'm curious to know if it's possible to pass a variable from one ajax success function to another ajax data field. Here are two ajax calls: $("#submit_btn").on("click",function(e) { $.aja ...

Leveraging JEST for Testing Document Object Model Components

I am diving into the world of JEST and trying to wrap my head around it, so I might be a little out of my depth here. But, I have a test in mind that checks the title of my Index page against a reference from this documentation: https://jestjs.io/docs/en/t ...

Executing a function stored in an array using JavaScript

While practicing JavaScript, I came across a sample code where I tried to call a function from an array. However, the output returned undefined along with the expected result from the function. I'm confused as to why this is happening, especially sinc ...

Keep only certain fields and eliminate the rest

Write a function that filters out all fields except 'firstName' and 'lastName' from the objects. Check out this code snippet I came up with. Any feedback? let people = [ { firstName: 'John', lastName: &apo ...

AJAX's PUT method encountering issues in Google Chrome

I have successfully implemented this in Mozilla and IE, but for some unknown reason, it is not working on Chrome. In Chrome, the error callback is triggered every time with an error code of zero. Numerous posts on Stackoverflow keep mentioning how all majo ...

Utilizing React with file system and path dependent packages

Is there a way to utilize the quick.db package in my ReactAPP with hooks, even though React does not allow the use of FS & Path which are required for this package? I am encountering the following errors: ERROR in ./node_modules/file-uri-to-path/index.js ...

Implementing PHP code to prevent the submission of forms with invalid inputs

When working on a form validation process in PHP, I encountered a challenge in preventing the form from being submitted to the database when there are errors in the input fields. While I was able to display error messages for invalid inputs upon submitti ...

I'm puzzled as to why a scroll bar materializes

I recently encountered an interesting issue while working on my responsive web design project. Upon resizing the browser to a width of 615px or less, a horizontal scroll bar unexpectedly appeared. It's puzzling as to which element is causing this prob ...

Guide on setting selected ngFor in Ionic2

I've been trying to set the selected option in my ngFor loop for Ionic2, but it doesn't seem to be working as expected. Here's what I've attempted: <ion-item> <ion-label>Source</ion-label> <ion-select [ ...

Navigating to a precise location on a webpage with React.js

I want to implement a straightforward action where the page automatically scrolls to a specific position upon loading. However, my attempts to execute this action have been unsuccessful so far. Is there an alternative method to achieve this in a React ap ...

Numbering Tables Effectively in ReactJS

Currently working on coding a table in ReactJS and MUI, my goal is to number the No. column from 1 to the length of the array. This snippet shows my code: <TableBody> {quizes.map((quiz, index) => ( <TableRow key={quiz._id}> ...

Issue with JSON or Jquery: Uncaught error message: Cannot access property 'error' as it is null

I am attempting to initiate an ajax call using the jQuery code provided below. However, when I try this in Chrome, I encounter an error that says 'uncaught typeerror cannot read property 'error' of null'. This prevents the preloader fr ...

Choosing an option from a dropdown menu does not trigger the execution of an AngularJS function through Selenium

Currently, I am attempting to create a Selenium test that involves selecting an item from 2 dropdown menus and then clicking a button. However, I have encountered an issue where the second dropdown menu is populated based on an angularjs call depending on ...

Create a dynamic HTML page using JavaScript

When I click on the following links: How can I create a new page using JavaScript? Create and dynamically append elements I'm looking to dynamically add HTML elements with JavaScript within a div, but I don't want my code to become overly comp ...

"Can you guide me on how to pick out one item before making my

Can someone please assist me with setting a default value for my input:hidden element before clicking on it? Here is the code I have: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> ...

Organize an array of objects based on another array in JavaScript

I have been working on sorting an array of objects by comparing it with another object. The goal is to display the selected objects at the top and the rest below them. While I am currently achieving the desired output, I am interested in exploring ways to ...

Errors of various kinds are occurring in Webpack during the npm install process

Whenever I execute npm install or npm ci, it triggers a webpack build that generates a plethora of incorrect errors. These errors allude to missing dependencies that are actually present. Interestingly, running npm ci seems to produce more errors than npm ...