Modify the text color of the fixed navigation when hovering over specific divs

Sorry if this question has already been asked. I've searched online but haven't come across a satisfactory solution. On my website, I have different background colors - blue and white. The text color in my navigation is mostly white, but I want it to change to black when hovering over a div with a white background.

Initially, I tried using this JavaScript code:

$(document).ready(function(){
     $(window).scroll(function(){
     var lightPos = $('#light').offset().top;
     var lightHeight = $('#light').height();
     var menuPos = $('.desktop-menu').offset().top;
     var menuHeight = $('.desktop-menu').height();
     var scroll = $(window).scrollTop();

     if(menuPos > lightPos && menuPos < (lightPos + lightHeight)) {
         $('.desktop-menu').addClass('menu-secondary');
         $('.desktop-menu').removeClass('menu-primary');
     }

     else {
         $('.desktop-menu').removeClass('menu-secondary');
         $('.desktop-menu').addClass('menu-primary');
     }  
     })
})

However, it seems to stop working after 3 containers. If I keep scrolling to other divs, regardless of the id I assign to a div (#light or #dark), the text no longer changes after the first 3 div containers on the page.

Appreciate any assistance!

EDIT: Struggled to get CodePen to function properly, so here's an example below.

Example HTML:

<div class="container">
   <header>
      <nav>
         <ul class="menu">
            <li><a href="#" class="menu-btn light-color">Page 1</a></li>
            <li><a href="#" class="menu-btn light-color">Page 2</a></li>
            <li><a href="#" class="menu-btn light-color">Page 3</a></li>
         </ul>
      </nav>
   </header>

   <div class="hero-container dark-background">
   </div>

   <div class="content-container light-background" id="light">
   </div>
   
   <div class="content-container dark-background">
   </div>

   <div class="content-container light-background" id="light">
   </div>

   <div class="content-container dark-background">
   </div>
   
   <div class="content-container light-background" id="light">
   </div>

   <div class="content-container dark-background">
   </div>
</div>

Example CSS:

body {
   margin: 0;
   font-family: 'Poppins', sans-serif;
}
ul {
   list-style-type: none;
   margin: 0;
   padding: 0;
}
header {
   display: flex;
}
.container {
   text-align: center;
}

/*-------------------- COLORS */
.dark-background {
   background: #313747;
}
.light-background {
   background: #f4f4f4;
}
.dark-color {
   color: #303030;
}
.light-color {
   color: #f4f4f4;
}

/*-------------------- NAVIGATION */
nav {
   position: fixed;
   height: auto;
   width: 100%;
   margin: auto;
   z-index: 10;
}
.menu {
   display: flex;
   padding: 2em 0 2em 3em;
   text-align: left;
   float: left;
}
.menu li a {
   margin-right: 2em;
   font-size: 1.2em;
   font-weight: 700;
   text-decoration: none;
}

/*-------------------- HERO CONTAINER */
.hero-container {
   position: relative;
   height: 100vh;
   width: 100%;
}

/*-------------------- CONTENT CONTAINER */
.content-container {
   position: relative;
   display: flex;
   width: 100%;
   height: 100vh;
   margin: auto;
}

Example JS:

$(document).ready(function(){
   $(window).scroll(function(){
   var lightPos = $('#light').offset().top;
   var lightHeight = $('#light').height();
   var menuPos = $('.menu-btn').offset().top;
   var menuHeight = $('.menu-btn').height();
   var scroll = $(window).scrollTop();

   if(menuPos > lightPos && menuPos < (lightPos + lightHeight)) {
      $('.menu-btn').addClass('dark-color');
      $('.menu-btn').removeClass('light-color');
   }

   else {
      $('.menu-btn').removeClass('dark-color');
      $('.menu-btn').addClass('light-color');
   }
   })
})

Answer №1

After reviewing your code, I made some adjustments to address the issue of checking on multiple elements with the same ID. Here's the revised code tailored to your specific case:

To solve this, I created an array of light sections and then implemented a scroll position check within each section.

var $ = jQuery;
$(document).ready(function () {
  var lightPos = [];
  $(".light-background").each(function () {
    lightPos.push({
      start: $(this).offset().top,
      end: $(this).offset().top + $(this).height()
    });
  });
  $(window).scroll(function () {
    var menuPos = $(".menu-btn").offset().top;
    var isInLight = !!lightPos.some((light) => {
      return light.start < menuPos && light.end > menuPos;
    });

    if (isInLight) {
      $(".menu-btn").addClass("dark-color");
      $(".menu-btn").removeClass("light-color");
    } else {
      $(".menu-btn").removeClass("dark-color");
      $(".menu-btn").addClass("light-color");
    }
  });
});
body {
  margin: 0;
  font-family: "Poppins", sans-serif;
}
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
header {
  display: flex;
}
.container {
  text-align: center;
}

/*-------------------- COLORS */
.dark-background {
  background: #313747;
}
.light-background {
  background: #f4f4f4;
}
.dark-color {
  color: #303030;
}
.light-color {
  color: #f4f4f4;
}

/*-------------------- NAVIGATION */
nav {
  position: fixed;
  height: auto;
  width: 100%;
  margin: auto;
  z-index: 10;
}
.menu {
  display: flex;
  padding: 2em 0 2em 3em;
  text-align: left;
  float: left;
}
.menu li a {
  margin-right: 2em;
  font-size: 1.2em;
  font-weight: 700;
  text-decoration: none;
}

/*-------------------- HERO CONTAINER */
.hero-container {
  position: relative;
  height: 100vh;
  width: 100%;
}

/*-------------------- CONTENT CONTAINER */
.content-container {
  position: relative;
  display: flex;
  width: 100%;
  height: 100vh;
  margin: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
      <header>
        <nav>
          <ul class="menu">
            <li><a href="#" class="menu-btn light-color">Page 1</a></li>
            <li><a href="#" class="menu-btn light-color">Page 2</a></li>
            <li><a href="#" class="menu-btn light-color">Page 3</a></li>
          </ul>
        </nav>
      </header>

      <div class="hero-container dark-background"></div>

      <div class="content-container light-background"></div>

      <div class="content-container dark-background"></div>

      <div class="content-container light-background"></div>

      <div class="content-container dark-background"></div>

      <div class="content-container light-background"></div>

      <div class="content-container dark-background"></div>
    </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

Having trouble with setting image source using Jquery?

The functionality of my razor in setting an image source is functioning properly. However, when I use my jQuery method to retrieve data, it returns a garbled URL: ���� Refreshing the page does not affect the HTML code, as it continues to work as e ...

Numerous text boxes sharing identical IDs

Here is the code snippet that I am working with: <%for (int index = 1; index < 7; ++index) {%> <tr> <td> <div class="indicacao_gdp"> ...

React: Issue with function not recognizing changes in global variable

When the run button is clicked, it triggers an event. However, clicking on the skip button does not take me to Switch Case 2 as expected. Even though the skip state updates, the function still outputs the old value of skip. const CustomComponent = () => ...

Guide to presenting fields on a distinct line or section in Angular 7 forms

I would like to arrange the username area and password area on separate lines with spaces in between. Here is the HTML code snippet: This HTML code is for a login angular GUI. <mat-card class="card"> <mat-card-content> <!-- CONT ...

Implementing JSON web tokens on the client side using Node.jsHere are the steps to implement

I have been developing a Node.js express application with JWT for authentication to secure access to my admin page. While testing my routes using Postman, everything works smoothly on the server side. However, I am facing a challenge on the client side in ...

I am eager to design a form input field within the vuetify framework

https://i.sstatic.net/zbCfI.png I'm having trouble creating a text field in Vuetify where the button and height are not behaving as expected. I've attempted to adjust the height multiple times without success. Although I have the necessary CSS, ...

position text to the right side of a slider gallery created with JavaScript

I'm currently utilizing a WordPress plugin known as Slideshow Gallery and I want to position the text below it to float next to the gallery on the right side. I've attempted the following: .bioText{ font-size: 14px; font-size: 1.428571429rem; ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

In a React/Redux component, there is a requirement to automatically fill a specified number of fields based on the selection made

Although this question is reminiscent of a previous one I asked, I have since restructured my project to incorporate Redux. Currently, I have a component that dynamically generates dropdown contents based on a data response from the app. One of the dropd ...

Is there a way to turn off the auto-complete feature for JavaScript keywords in HTML within JSX in WebStorm?

While using WebStorm, I've noticed that it automatically completes JavaScript keywords as I type regular text in JSX. This behavior is starting to frustrate me because I have to constantly press ESC or click elsewhere to hide the auto-complete popup. ...

The canvas appears blank when using Firefox version 36

The application is made up of an interface (html) and workspace (canvas). We utilize three.js to create elements on the canvas. So far, it's been functioning perfectly on Chrome, Opera, and Firefox 35. You can see it in action here: However, in Firef ...

Storing and retrieving text in a file using JavaScript: A step-by-step guide

I have a command set up where if a user is mentioned, the discord bot will save the mentioned user's name in a file (I'm utilizing discord.js and node.js). Below is my code snippet: const prv = require('C:/Users/Kikkiu/Desktop/prova.txt&apo ...

Place a small image within a list item to ensure it matches the height of the list element

I need help aligning images to the right within list elements. The images are squares with equal height and width, and I want them to fit snugly within the height of the list element on the right side. My HTML code is quite simple for now (see example bel ...

A React component utilizing dangerouslySetInnerHTML and including CSS styles

One of my React components displays the following element: <div dangerouslySetInnerHTML={{__html: this.props.htmlString}}/> While the html renders correctly, I am facing a challenge with my client-side CSS code affecting the component I am renderin ...

Issue with FullPageJS: scrollOverflow feature not functioning upon click event

I am currently working on a Fullpage.js instance that needs to be initialized with a click event and then destroyed when switching to another page, and vice versa. The scrollOverflow feature works perfectly as long as the #fullpage element is not hidden up ...

Methods to modify the state of a Modal component beyond the boundaries of a React class

I am attempting to trigger my modal by modifying the state from outside of the react class. Unfortunately, I have had no success thus far. I have experimented with the following approach: In my code, I have a method named "Portfolio" that is responsible f ...

The functionality of changing the checkbox to "checked" by clicking on the span is not

How can I create a toggle button with a checkbox using css and jquery? Clicking on the span representing the toggle button should change the checked property of the checkbox. Currently, the span does not change the property, even though it triggers the c ...

full width css slider

I am currently working on a website project for a friend of mine. She requested to have a slider for the header images. I attempted to make it full width, but it seems to be displaying differently in Firefox and Chrome, and I'm not sure why. The webs ...

Discover the step-by-step process of attaching middleware to events within socket.io

Is there a way to intercept middleware in Socket.io before passing it to an event handler similar to how it's done in expressjs? In other words.... In express.js you can use: app.get('/', middleware1, middleware2, function(req, res){ ...

How can I modify the value of a CSS animation rule in AngularJS?

I am looking to dynamically change the value assigned to stroke-dashoffset based on a custom input. @-webkit-keyframes donut-chart-1 { to { stroke-dashoffset: 100; } } @keyframes donut-chart-1 { to { stroke-d ...