Implement an onscroll event that dynamically changes the background color to highlight each phase individually

I need help implementing an onscroll event that will change the background color of each phase. Can anyone provide suggestions on how to achieve this? Here is my HTML code:

I have experimented with a few listener options, but haven't been successful so far.

document.addEventListener("scroll", myFunction)

function myFunction() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.getElementById("phases2").className = "background-scroll";
  } else {
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
      document.getElementById("phases2").className = "nobackground";
    } else {
      document.getElementById("phases3").className = "background-scroll";
    }
  }
}
.background-scroll {
  background-color: rgb(0, 0, 0, 0.521);
  border-radius: 20px;
}

.nobackground {
  background-color: rgba(0, 0, 0, 0);
}
<section class="phases">
  <div class="row-padding">
    <div class="row">

      <div class="phases-col" id="phases2">
        <img class="phases1" src="/images/1645177223057.png" />

        <h3>Phase1</h3>

        <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Repellendus, minus eius earum necessitatibus reprehenderit, excepturi soluta, cumque sed maiores in doloremque assumenda? Eum, officia? Praesentium aspernatur neque atque numquam iste.</p>
        
      </div>
      <div class="phases-col">
        <img class="phases1" src="/images/1645177161131.png" />
        <h3>Phase2</h3>

        <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Repellendus, minus eius earum necessitatibus reprehenderit, excepturi soluta, cumque sed maiores in doloremque assumenda? Eum, officia? Praesentium aspernatur neque atque numquam iste.</p>

      </div>
      <div class="phases-col">
        <img class="phases1" src="/images/1645176961476.png" />
        <h3>Phase3</h3>

        <p>Lorem ipsum, dolor sit amet consectetur adipisicing elt. Repellendus, minus eius earum necessitatibus reprehenderit, excepturi soluta, cumque sed maiores in doloremque assumenda? Eum, officia? Praesentium aspernatur neque atque numquam iste.</p>


      </div>
    </div>
  </div>
</section>

Answer №1

Here is an effective solution I came across:

window.addEventListener("scroll", function(event){
 var scrollY = this.scrollY;
  if (scrollY > 190) {
   document.getElementById('phases2').style.backgroundColor = "rgba(5, 5, 5, 
   0.548)";
  } else { 
   document.getElementById('phases2').style.backgroundColor = "";      
  } if (scrollY > 650){
   document.getElementById('phases2').style.backgroundColor = "";
   document.getElementById('phases3').style.backgroundColor = "rgba(5, 5, 5, 
   0.548)";
   }else { 
   document.getElementById('phases3').style.backgroundColor = ""; }
   if (scrollY > 960){
    document.getElementById('phases3').style.backgroundColor = "";
    document.getElementById('phases4').style.backgroundColor = "rgba(5, 5, 5, 
     0.548)";
     }else { 
    document.getElementById('phases4').style.backgroundColor = ""; }
 })

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

Can JavaScript's Gamepad API be used to register a custom game controller?

Background Story Working on a virtual reality app with A-frame to showcase VR gadgets. Custom controllers connect via websocket/bluetooth and we want them compatible with tracked-controls. These components use Gamepad API for model positioning and are fri ...

JavaScript function not executing

Within a panel in an UpdatePanel, there is both a dropdown list and a file upload control. The goal is to enable the Upload button when a value is selected from the dropdown and a file is uploaded. This functionality is achieved through a JavaScript functi ...

Top recommendations for integrating a customized form in Vue

My objective is to develop a unique custom form component named app-form, which offers the capability of using v-model for validation access. The input will be utilizing another custom component called app-input. Here's the progress I've made s ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

A tool that enhances the visibility and readability of web languages such as HTML, PHP, and CSS

Looking to organize my own code examples, I need a way to display my code with syntax highlighting. Similar to how Symfony framework showcases it on their website: http://prntscr.com/bqrmzk. I'm wondering if there is a JavaScript framework that can a ...

Execute a function when the selected option changes

Now I have implemented a code that dynamically changes the foreign key based on user input and retrieves data accordingly. Here is how it all comes together: Starting with the HTML page: <div class="large-6 columns"> {% csrf_token %} <in ...

"Facing an issue with Google Chrome not refreshing the latest options in an HTML select dropdown list

Having trouble creating an offline HTML file that incorporates jQuery for the script. The page features a state select menu followed by a second menu for counties. When a state is selected, only the corresponding counties should display while others remai ...

The Bootstrap grid with 2x2 layout reaches a maximum size horizontally

I am facing an issue with my layout design. I am trying to create a menu that consists of a header and a 2x2 tile grid, which should transform into a 1x4 grid on smaller screens. Objective - Large screen (Red = Header, Green = Tile) On smaller screens, ...

Request successful but receiving no response text and content length is zero

let req = new XMLHttpRequest(); req.addEventListener('load', function (data) { console.log(data) }, false); req.open("get", "/bar.txt", true); req.send(); Feeling a bit perplexed at the moment, I can't seem to figure out what's going ...

Ensure that when a link <a> is clicked, the active class of a node in Dynatree is deselected or removed

Is there a way to unselect the current node in a dynatree? node.deactivate(); // not effective node.focus(false); // this method does not exist I attempted to eliminate the classes that indicate the focused/activated node : While this approach did work, ...

Choose options from the month dropdown menu using Selenium WebDriver

Presently focused on working with Selenium WebDriver and Java. I am attempting to pick an option from a date picker form. When trying to select the month from the dropdown of the date picker, an error is displayed stating Unable to locate element: {"method ...

Is there a way to use jQuery to animate scrolling on a mobile web browser?

I'm trying to make the page scroll to a specific position when a button is clicked. The code I currently have works fine on browsers like Chrome and IE, but doesn't seem to work on any mobile browser. Below is the code snippet I am using: $("#p ...

Tips for halting a MySQL database transaction within a NodeJS environment using expressJS

Recently, I encountered a coding challenge that involved managing a long database transaction initiated by a user. The scenario was such that the user inadvertently updated 20 million entries instead of the intended 2 million, causing a significant impact ...

When using a jQuery AJAX call, the special character % is sent to the server side as &#37;. This was successfully updated

I am working with a Java program that generates an HTML form populated with text from a database. The user can edit the text in the form, and upon submission, it is sent back to the Java backend using a jQuery AJAX call. The modified text is then saved in ...

Is it acceptable to initiate an import with a forward slash when importing from the root directory in Next.js?

I've noticed that this import works without any issues, but I couldn't find official documentation confirming its validity: // instead of using a complex nested import like this import { myUtil } from '../../../../../lib/utils' // this ...

What is the best way to create a responsive-friendly centered navbar?

I have successfully centered my navbar, but it doesn't appear to be very responsive-friendly. Additionally, the hamburger menu is not showing up when I collapse the menu. Any tips or suggestions would be greatly appreciated! .navbar-header { heig ...

The ng-repeat directive in a row is malfunctioning

Just starting out with angularjs and facing an issue with getting data using ng-repeat within a div that is part of a row. I have implemented filtering and pagination from a dropdown, but it doesn't seem to be working as expected. Any assistance would ...

Tips for responding to and disabling a specific button in Vuetify.js after clicking the follow or unfollow button

I have a situation where I need to implement a functionality for a series of buttons with follow and unfollow statuses. When a user clicks on any button, I want the status to change after a brief delay and deactivation, followed by reactivation. For instan ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

Tips on uploading information from a PDF document onto a website

My goal is to develop a program or script that can extract data from PDF form fields and automatically input it into the corresponding textfields on my website, all done through the front end. The problem I'm facing is not knowing where to begin with ...