A menu bar featuring dual color schemes for visual differentiation

I am currently designing a navigation bar where one category stands out with a different color (blue) compared to the rest (green). The functionality I'm aiming for is that when the cursor moves away from the blue HOME category, it should change back to green. Conversely, when hovering over any category, including HOME, it should turn blue, and revert to green once not hovered over. Here are some visual references:

Default/Home state: Users begin on the Home page with the Home category highlighted in blue.

Employer state: Users have navigated to the Employer Page, causing the Home category to switch to green.

Since I am using SFMC, all HTML, CSS, and JavaScript code must be contained separately. Below is the code snippet that I've implemented:

function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}
.body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.topnav {
  overflow: hidden;
  background-color: #47a23f;
}
/* Rest of the CSS code remains unchanged */
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="topnav" id="myTopnav">
  <a href="#home" class="active">Home</a>
  <div class="dropdown">
    <button class="dropbtn">Workforce 
      <i class="fa fa-caret-down"></i>
    </button>
    /* Remaining HTML code untouched */
  </div>
  // Closing tags omitted for brevity

Answer №1

If you desire to revert active elements back to their normal color when hovering over other elements, simply include the following CSS code at the end of your stylesheet:

.topnav > .active {
  background-color: #005da6;
}

.topnav:hover > .active {
  background-color: inherit;
}

.topnav > .active:hover {
  background-color: #005da6;
}

.dropdown-content > .active {
  background-color: #003150;
}

.dropdown-content:hover > .active {
  background-color: inherit;
}

.dropdown-content > .active:hover {
  background-color: #003150;
}

For handling active elements in a more simplified manner, refer to the snippet below:

(Note: The navigation bar below operates using only HTML and CSS without any JavaScript. JS is solely utilized for automatically updating active elements according to changes in the browser URL.)

// * THIS IS ONLY A DEMONSTRATIVE EXAMPLE *

const links = Array.from(document.querySelectorAll('.topnav a'));

const addActive = (elem) => {
  let current = elem;
  
  while (current && !current.classList.contains('topnav')) {
    if (current.classList.contains('dropdown')) {
      current.classList.add('active');
      break;
    }
    current = current.parentElement;
  }
  
  elem.classList.add('active');
};

const handler = (e) => {
  const previousA = document.querySelector('.topnav .active');
  const previousB = document.querySelector('.dropdown-content .active');
  
  if (previousA) {
    previousA.classList.remove('active');
  }
  
  if (previousB) {
    previousB.classList.remove('active');
  }
  
  const next = links.find((link) => location.href === link.href) || links[0];
  
  if (next) {
    addActive(next);
  }
};

window.addEventListener('popstate', handler);
document.addEventListener('DOMContentLoaded', handler);
.body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

/* Rest of the CSS styles here */

.topnav > .active {
  background-color: #005da6;
}

.topnav:hover > .active {
  background-color: inherit;
}

.topnav > .active:hover {
  background-color: #005da6;
}

.dropdown-content > .active {
  background-color: #003150;
}

.dropdown-content:hover > .active {
  background-color: inherit;
}

.dropdown-content > .active:hover {
  background-color: #003150;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="topnav">
  <a href="#home">Home</a>
  
  /* Sample HTML content structure here */
</div>

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

Received a syntax error from the DOM parser even after successfully downloading it through NPM

Seeking guidance as a beginner in this technology field. I have installed dom-parser from the NPM package. However, when I tried to declare it below, I encountered a syntax error. Although it seems like a minor issue, I am puzzled and unsure of where I am ...

When attempting to choose two dates within this application, an error is encountered stating that the datepicker function is not recognized

I am encountering an issue while trying to select two dates in this program. When I attempt to execute it, the error message "datepicker is not a function" appears. datepicker is not a function Here is the code snippet: var startDate; ...

Netbeans fails to detect Jquery

Looking for some assistance here. I'm in the process of setting up my computer for a new project and for some reason, Netbeans isn't recognizing any of the .js files. Any tips on how to enable it to start recognizing these files? ...

Reduce the line length for better readability

Looking for a way to make a button with flexible width while allowing text to wrap to 2 lines for minimum button size? Check out the examples below: To keep the button width small, even short words should wrap to 2 lines: My Button If there's a ...

Express receiving undefined data in Ajax POST request

I'm currently facing an issue with sending data to be parsed. The client-side script I have is as follows: function addURL(link) { console.log("Adding url..."); $.ajax({ type: "POST", url: location.protocol + "/ ...

Is it possible to have two unique keys in a single MongoDB schema?

Currently attempting to achieve this functionality using mongoose: const newContent = new Schema({ heading: { type: String, unique: true }, url: { type: String, unique: true }, //... }); However, an error is being thrown: MongoError: E11000 dupl ...

Firebase Storage Metadata Disappearing Act

Despite trying to add custom metadata to my image in Firebase, it doesn't seem to be accepting it. I expect to see my metadata listed under 'Other Metadata' after I upload the image. Currently, this is how it appears for me: https://i.sstat ...

Implementing an Ajax function for handling multiple button clicks

So, here's the situation - I've inherited a form with two buttons that inexplicably have the same name and id (seriously, don't ask me why, I didn't design this form haha). I'm attempting to utilize the Ajax .click function to trig ...

Executing Child Validators when moving to the next step in an Angular MatStepper from the Parent Component

I am looking to implement validation for my Mat-Stepper-Next function in the App Component using child component validators. I have 3 different form components, each with its own form group, validations, and next button within the component. I am includi ...

Having the same name for multiple query parameters does not result in an array being returned

Using the link http://example.com/users?test=1&test=2 router.route('/users/?').get((req, res) => { console.dir(req.query) //=> { test : 1 } }) The output is { test : 1 } instead of an expected array [ 1, 2 ]. Even ?test[]=1&test ...

Include an external JavaScript file within a component to display pictures in a web browser using Angular 2

I am developing a website using Angular 2 and need to incorporate a JavaScript file into a component. The goal is for this script to adjust the height of certain images to match the height of the browser window. What is the best way to integrate this scri ...

Tips for transforming a JSON response into an array with JavaScript

I received a JSON response from an API: [ { "obj_Id": 66, "obj_Nombre": "mnu_mantenimiento_de_unidades", "obj_Descripcion": "Menu de acceso a Mantenimiento de Unidades" }, { "obj_Id": 67, "ob ...

Experiencing difficulties with NPM installation

Screenshot of my terminal in VSCode Despite attempting to uninstall and reinstall node and clearing the cache, I am still unable to resolve this issue. Any suggestions? If it's relevant, I am using Windows 10. ...

Invoke an array in PHP

If I need to call an array from PHP into TypeScript in array format, how can I accomplish this? Below is my PHP code: $AccessQuery = "SELECT name, lastname, phone, email FROM user INNER JOIN access ON id ...

Issues arise when trying to render text within Javascript as "NOTICE", however PHP is able to display it seamlessly without any hiccups

PHP uses metadata from image files to create text and stores it in a variable with the same name as the IMG source. No issues there. JavaScript is responsible for displaying the gallery, allowing users to scroll and enlarge images. While enlarging an imag ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

Dealing with lag in Kendo Grid (Utilizing Kendo Grid, Angular JS, and Web API)

Query : I have integrated a Kendo Grid into my Angular JS HTML page. The data for the Kendo Grid is fetched from a remote service Web API. While paging through the Kendo Grid, it attempts to download a whopping 38 MB of content for every 10 records, taki ...

Error: A property called 'node' is undefined and cannot be read

Currently attempting to complete the NPM installation process. I initiated with the following command: brew install node followed by curl -O https://www.npmjs.org/install.sh and then ~ % sh install.sh The resultant output is as follows: tar=/usr/bi ...

JavaScript - Monitoring changes to a node before they occur

Using MutationObserver, I am able to detect node insertion in a tree, however, it runs after the node is inserted. If I need to trigger an event before the node is actually inserted, what steps should I take? For example: // create a new observer instan ...