Is it possible to employ getBoundingClientRect() for several elements sharing the same class?

I'm in the process of implementing sticky navigation on my website that will dynamically change as users scroll through different sections. Specifically, when scrolling over a section marked with the class .dark, I want the logo and text color to switch to white, otherwise remain black.

The javascript snippet I've been utilizing is provided below. However, it seems to only affect the first element with the class .dark. How can I modify this code to target all elements with the same class?

window.addEventListener('scroll', function () {

        var sections = document.querySelectorAll('.dark'),
            logo = document.querySelector('#logo-container').getBoundingClientRect();

          sections.forEach(function(section) {
            if (section.top <= logo.top + logo.height && section.top + section.height > logo.top) {
              document.getElementById('logo-container').classList.add('white-logo');
              document.getElementById('navholder').style.color = "#fff";
            } else {
              document.getElementById('logo-container').classList.remove('white-logo');
              document.getElementById('navholder').style.color = "#111";
            }
          });

     });

Apologies if this question seems basic, as my knowledge regarding Javascript is limited. Despite attempting to find a solution on my own, I have not made much progress. Any assistance with this matter would be greatly appreciated.

Answer №1

Breaking this code into multiple functions can simplify your life. By determining if the logo is within any specific section, you can then adjust its class accordingly:

const setLogoColor = status => {
  if (status) {
    document.getElementById('logo-container').classList.add('black-logo');
    document.getElementById('logo-container').classList.remove('white-logo');
  } else {
    document.getElementById('logo-container').classList.add('white-logo');
    document.getElementById('logo-container').classList.remove('black-logo');
  }
}

const logoWithinSection = logo => sectionRect => sectionRect.top <= logo.top + logo.height &&
  sectionRect.top + sectionRect.height > logo.top

window.addEventListener('scroll', function() {

  var sectionRects = [...document.querySelectorAll('.dark')]
    .map(el => el.getBoundingClientRect());

  var logo = document.querySelector('#logo-container').getBoundingClientRect();

  var logoInAnySections = sectionRects
    .some(logoWithinSection(logo))

  setLogoColor(!logoInAnySections);
});
img {
  width: 50px;
  position: fixed;
  top: 20vw;
  left: 20vw;
  z-index: 1;
}

.white-logo {
  filter: invert(90%);
}

.section {
  width: 100%;
  height: 300px;
}

.dark {
  background-color: rgba(20, 20, 30);
}

.white {
  background-color: white;
}
<img src="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/cc.svg" id="logo-container"/>
<div class="section white"></div>
<div class="section dark"></div>
<div class="section white"></div>
<div class="section dark"></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

Managing unanticipated errors in Express while utilizing async/await mechanics

Consider this TypeScript code snippet: app.get('/test_feature', function (req: Request, res: Response) { throw new Error("This is the bug"); }); app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFun ...

Implementing translation functionality within an AngularJs controller

Utilizing angular translate for translating certain words in the controller, with translation stored in json files within the html. // LABELS var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "Septe ...

Aligment issues in columns on Bootstrap 5

I currently have a layout using Bootstrap 5 with multiple rows and columns. My goal is to have the columns aligned within each row, but I am experiencing issues where some borders are not lining up correctly with the columns. .VI-border { border-t ...

What is the significance of `()=>` in JavaScript when using Selenium?

What is the significance of () => in the following sentence? ()=>{Object.defineProperties(navigator,{webdriver:{get:()=>false}})} I have only seen this syntax in JavaScript and it seems to be used for configuring page evaluation with Selenium. T ...

Creating eight equal sections within HTML <div> elements using Bootstrap

I am brand new to Angular. I need to design something like this: https://i.sstatic.net/Zcb9i.png However, I'm struggling to find the right solution. Here is what I have so far: https://i.sstatic.net/7hsrk.png. Having been a backend developer, I&ap ...

Securing your Node.js connect-rest REST API with OAuth: A comprehensive guide

After conducting an extensive search on Google for examples related to my query, I was left empty-handed due to the generic name of the "connect-rest" package. My objective is to secure a server side API that I have built using the Node module "connect-re ...

Angular ng-bind-html directive allows you to bind HTML content to an

I am attempting to utilize $interpolate and ng-bind-html in order to bind the data from my scope variable to an html string as outlined in this solution. However, I have encountered an issue where the ng-bind-html result does not update when the value of m ...

HTML and CSS are distinct entities with their own individual purposes and

Can you create custom entities? For example: &longline; --> ----------------------------- and then incorporate it in HTML code: <div> &longline; bla bl bla </div> ...

SQL injection for storing hidden dates

When I submit a value using my form, I want the date to be saved in the MySQL database. The user does not need to see it, but I need the dates for a future function where I can loop through the registered dates in the database. Do I need to create a hidde ...

Improper Placement of CSS in Google Chrome

I'm facing an issue with my login form that displays perfectly fine in all browsers except Google Chrome. In Chrome, it tends to get distorted more often than not. CSS * { margin: 0; padding: 0; width: auto; } body { background: #E8 ...

Transferring application configurations across modules

Questioning my current approach, I am developing a model & collection package (which exposes mongodb results as a model) and aiming for a modular structure. However, within the models, there are hardcoded settings like host, port, password, etc., which ...

My browser isn't triggering the jQuery change event, although it does work in jsfiddle

Whenever a textbox is changed, I want a specific function to be executed automatically. The code snippet below demonstrates my approach: var div = document.getElementById("tree"); var input = document.createElement('input'); input.id = 123; i ...

What is the best way to develop a unique animation for every v-card?

Is there a way to customize each animation so that it is specific to the selected v-card? Right now, when one card is clicked, all of them play the same animation. data: () => ({ show: true, images: [ {url:require('@/assets/london. ...

The display: table attribute is proving to be ineffective in creating the desired table layout. I am seeking alternative ways to

Is there a way to create a table using the CSS property display: table without utilizing the table element? I've searched for examples, but haven't found anything that has been helpful. Can someone please provide a fiddle of a table with a minimu ...

In React development, a div (button) is visible, but in the production build, it becomes hidden from

I have been working on a website for my job, and I have added a "Gallery" button on top of two slideshows. Everything works perfectly fine on the development build, but when it comes to the production build, the button doesn't show up for some reason. ...

Having issues with jQuery's .text() method not functioning as expected on XML elements

Looking at the javascript code below: function getAdminMessageFromXML(xml) { alert('xml: ' + xml); alert("Text of admin message: " + $(xml).find('dataModelResponse').find('adminMessage').text()); return $(xml).fin ...

Display the initial JSON data object without the need to choose a link with the help of AngularJS

I have successfully built a webpage that displays JSON data based on the selected link. However, I am facing an issue where I need to show the first JSON data object before selecting any link (initially). Check out the Plunker demo here: http://embed.plnk ...

"Changing a Java script base addon file to a customized addon in Odoo 16: A step-by-step guide

Here is the JavaScript file located in the "documents" enterprise base addon: I want to include the field "document_type_id" in the export const inspectorFields = [] array through a custom addon. /** @odoo-module **/ import { device } from "web.confi ...

Error message: `$injector:modulerr - Angular JS` - Indicates an

Currently, I am trying to delve into the world of Angular JS by taking the codeschool course "Shaping up with angular js". The instructor in the videos emphasizes the importance of wrapping code in function(){}. However, upon attempting to do so, an error ...

Unable to insert text into JEditorPane using text/html format

In my class, I am using a JEditorPane to display text that needs to support HTML. When I try to add text to the pane by setting the content type to HTML and then using setText(), nothing appears on the pane. The issue seems to be with setting the content ...