CHANGE ELEMENT BACKGROUND COLOR OVER DARK SECTION

by davidxmartins

HTML

<div class="white"></div>
<div class="green dark-section"></div>
<div class="grey"></div>
<div class="black dark-section"></div>
<div class="white"></div>
<div class=" blue dark-section"></div>
<div class="white"></div>
<div class="red dark-section"></div>

<div class="left colour-change"></div>
<div class="right colour-change"></div>
<div class="middle colour-change"></div>

CSS

body {
      margin: 0;
    }
    
/*  OBJECTS */

    .left {
      position: fixed;
      top: 20px;
      left: 20px;
      width: 100px;
      height: 100px;
      border-radius: 50px;
      background-color: green;
      /* Default color */
      transition: background-color 0.5s ease;
      /* Transition effect */
    }

    .right {
      position: fixed;
      top: 20px;
      right: 20px;
      width: 100px;
      height: 100px;
      border-radius: 50px;
      background-color: green;
      /* Default color */
      transition: background-color 0.5s ease;
      /* Transition effect */
    }

    .middle {
      position: fixed;
      bottom: 20px;
      right: 20px;

      width: 100px;
      height: 100px;
      border-radius: 50px;
      background-color: green;
      /* Default color */
      transition: background-color 0.5s ease;
      /* Transition effect */
    }

    /*  SECTIONS */

    .white {
      height: 100vh;
      background-color: #fff;/
    }

    .green {
      height: 100vh;
      background-color: green;/
    }

    .grey {
      height: 100vh;
      background-color: #ccc;/
    }

    .blue {
      height: 100vh;
      background-color: blue;/
    }

    .black {
      height: 100vh;
      background-color: #000;/
    }

    .red {
      height: 100vh;
      background-color: red;/
    }

JavaScript

//Get all the dark section elements
const darkSections = document.querySelectorAll('.dark-section');
// Get the fixed elements 
const fixedElements = document.querySelectorAll('.colour-change');

let handleScroll = () => {
    fixedElements.forEach(fixedElement => {
        fixedElement.style.backgroundColor = 'green';   // set default color to green
        darkSections.forEach((section) => {
            const darkSectionRect = section.getBoundingClientRect();
            const fixedElemRect = fixedElement.getBoundingClientRect();
            // condition to check the intersection
            if (darkSectionRect.top < fixedElemRect.bottom && darkSectionRect.bottom > fixedElemRect.top) {
                fixedElement.style.backgroundColor = 'white'; // Change color to white if intersect
            }
        });
    })
};

window.addEventListener('scroll', handleScroll);