Animating background color change with scroll in React using fade effect

Can someone help me with implementing a fading animation for changing the background color on scroll in React? I have successfully achieved the background change effect, but I'm struggling to incorporate the fading effect.

import React from "react";

export default class ScrollBackground extends React.Component {
  state = {
    bgcolor: "black",
    color: "white",
  };

  listenScrollEvent = (e) => {
    if (window.scrollY < 5300) {
      return this.setState({
        bgcolor: "black",
        color: "white",
        opacity: 1 - window.scrollY / 5300,
      });
    } else {
      return this.setState({ bgcolor: "white", color: "black", opacity: 0 });
    }
  };

  componentDidMount() {
    window.addEventListener("scroll", this.listenScrollEvent);
  }
  render() {
    return (
      <div
        style={{
          background: this.state.bgcolor,
          color: this.state.color,
          height: "800px",
        }}
      >
        <div id="header">
          <h1>fsefd</h1>
        </div>
        <div id="section_1" className="section">
          This is section 1
        </div>

        <div id="section_2" className="section">
          This is section 2
        </div>
        <div id="section_5" className="section">
          This is section 5
        </div>
      </div>
    );
  }
}

Answer №1

To achieve a fading effect, utilize CSS transition by adding the following code:

transition: "background-color 0.5s ease"
.

CSS transitions offer control over the animation speed for CSS property changes. Rather than immediate effects, these changes occur gradually over time.

For instance, when changing an element's color from white to black, CSS transitions enable this change to happen gradually with customizable timing and acceleration curves.

Furthermore, remember to implement debounce. Check out the Demo:

const { debounce } = _;
const { Component } = React;

class App extends Component {
  state = {
    bgcolor: "black",
    color: "white",
  };

  listenScrollEvent = debounce((e) => {
    if (window.scrollY < 400) {
      return this.setState({
        bgcolor: "black",
        color: "white",
        opacity: 1 - window.scrollY / 5300,
      });
    } else {
      return this.setState({ bgcolor: "white", color: "black", opacity: 0 });
    }
  }, 50);

  componentDidMount() {
    window.addEventListener("scroll", this.listenScrollEvent);
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.listenScrollEvent);
  }

  render() {
    return (
      <div
        style={{
          background: this.state.bgcolor,
          transition: "background-color 0.5s ease",
          color: this.state.color,
          height: 1000,
        }}
      >
        <div id="header">
          <h1>fsefd</h1>
        </div>
        <div id="section_1" className="section">
          This is section 1
        </div>

        <div id="section_2" className="section">
          This is section 2
        </div>
        <div id="section_5" className="section">
          This is section 5
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.body)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

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

Is it possible to incorporate HTML and CSS into Kivy and Python 3 development?

Currently in the process of creating a multi-touch kivy program using Python 3.52 on Linux. While Kivy is effective, I've encountered challenges with GUI development and experienced laggy animations. I've noticed that my program tends to slow do ...

Steps for saving both checked and unchecked checkbox values in Firebase

I have a set of objects that I am using as initial data in my Ionic 3 application: public interests = [ { name: 'Travel', checked: false }, { name: 'Animals', checked: false }, { name: 'Theatre', checked: false ...

Count the number of URL segments using JavaScript and jQuery

Can anyone suggest an efficient method to count the number of segments in a URL using JavaScript/jQuery? For instance: www.myexampleurl.com/section1/section2/section3 should output 3 ...

Import the CSV file and store it in a designated directory using JQuery

My goal is to enable users to upload a CSV file from an HTML page and have it saved to a specified local directory upon upload. Two possible scenarios could unfold: if the uploaded file already exists, it should be overwritten; otherwise, a new file shoul ...

Exploring the Use of 7BitEncodedInt in JavaScript

Currently, I am trying to read a binary file using JavaScript. It appears that this file may have been written in C#, which handles strings differently from how it's done in the source mentioned at https://learn.microsoft.com/en-us/dotnet/api/system. ...

Utilizing the Bootstrap grid system for responsiveness is optimized for a first word that is precisely 15 characters

Trying to achieve responsiveness using basic Bootstrap. The layout becomes responsive only when the initial word in a sentence contains more than 15 characters, as illustrated below. https://i.stack.imgur.com/wyErA.png <!-- Headers --> <div clas ...

What kind of function am I using and passing as props in React when working with TypeScript?

I recently developed a customized Checkbox component. The TypeScript setup in my project doesn't allow the use of any type, so I'm struggling to define the specific type for the handleCheckbox() function (found within the FilterBox component) th ...

Combining LESS with cultural designations

Currently working on a multi-lingual website project and facing the challenge of switching out CSS based on different languages. I am passing the culture code into the page and exploring ways to use it to reference specific selectors for each language. H ...

The function GetURLParameter(sParam) is displaying %20 as blank space in the webpage

I am facing an issue with a code that pulls URL parameters into the landing page. The problem is that it is including white spaces as %20. For example, if my URL parameter is: example.com/?title=my website, it would display my%20website on the page inste ...

Encountered a challenge when attempting to substitute styles using classes in material-ui

While working on implementing a table using the TableRow component from material-ui, I encountered an issue with customizing the background color when the "selected" property is true. The default theme applies a pink background-color in such cases, but I w ...

What is the best way to turn off the legends in chart.js?

I'm having trouble customizing a chart using chart.js because I can't seem to disable the legends within the canvas element. However, I still want to style the legends elsewhere on the page using generateLegend(). Can anyone provide assistance wi ...

Creating a sticky horizontal menu with material-ui stepper: A step-by-step guide

I'm currently working with Material-UI stepper and I'm wondering if it's possible to keep the stepper fixed at the top of the page, just below the AppBar, as the user scrolls down. Here is the styling and code for the stepper that I have tr ...

Error encountered in the face api.js source map while executing a React application to identify and track faces through a webcam

I have been attempting to develop a facial recognition application using face-api.js in react js for one of my clients. Despite trying various solutions, I consistently encounter the same error. Here is the code snippet from App.js: insert your modified c ...

The nodes.attr() function is invalid within the D3 Force Layout Tick Fn

I'm currently experimenting with the D3 Force Layout, and I've hit a roadblock when it comes to adding elements and restarting the calculation. Every time I try, I keep encountering this error: Uncaught TypeError: network.nodes.attr is not a fun ...

Include a scroll bar for menu items that contain submenus, while ensuring that the submenu items remain visible

Looking for a way to add a scrollbar to the courses menu list due to its excessive length (refer to the image below). The fixed top navbar prevents scrolling, making it necessary to implement a scrollbar within the menu itself. After applying the followin ...

The elements within the HTML, CSS, and Bootstrap are all clashing and

Website Output https://i.sstatic.net/5JVyg.jpg I've been working on a small website with a bootstrap carousel, and in this specific section of the program, the Bootstrap and HTML/CSS elements overlap by default. I'm not sure how to separate the ...

What could be causing the background image on my element to not update?

I'm attempting to utilize a single background image that is 3 pixels wide and 89 pixels tall. Each vertical stripe of 1 pixel will serve as the background for a different div. I had presumed that adjusting the background-position by -1px 0 and specif ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...

Disable the button until all input fields contain text in ASP

Curious if anyone knows how to disable a button until all text boxes have input in ASP.NET and C#. Here is an image showing the scenario I'm referring to - wanting to gray out the commit button. Thanks, Chris! ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...