Change classes of individual divs as one scrolls, with each div having its own distinctive class

I came across this article: Add/remove class with jquery based on vertical scroll? However, I am struggling to implement it for multiple divs, each with their own unique classes that require adding and removing 1 class at different distances from the top. Here is what I aim to achieve:

<div class="div-01">Add 1 class and remove 1 class when user scrolls down 500px from the top, and reverse the process when scrolling up.</div>
<div class="div-02">Add 1 class and remove 1 class when user scrolls down 1000px from the top, and reverse the process when scrolling up.</div> 
<div class="div-03">Add 1 class and remove 1 class when user scrolls down 1500px from the top, and reverse the process when scrolling up.</div>

Answer №1

Have you given this approach a try? It may seem lengthy and messy, but it's been a while since I dabbled in jQuery and I'm just borrowing part of the solution that you provided.

Edit

I've made some improvements to the fiddle you shared. You can consolidate the "greater than" and "less than" conditions into a single line for efficiency.

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 200 && scroll < 800) {
        $(".div-01").addClass("darkHeader");
    } else {
        $(".div-01").removeClass("darkHeader");
    }
    if (scroll >= 1000 && scroll < 1800) {
        $(".div-02").addClass("darkHeader");
    } else {
        $(".div-02").removeClass("darkHeader");
    }
    if (scroll >= 2000 && scroll < 2400) {
        $(".div-03").addClass("darkHeader");
    } else {
        $(".div-03").removeClass("darkHeader");
    }
});
.div-01, .div-02, .div-03 {
  background: red;
  height: 1000px;
  width: 500px;
  margin-bottom: 10px;
} 

.darkHeader {
  background: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="div-01"></div>
<div class="div-02"></div>
<div class="div-03"></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

Initiate keyframe animation after completion of the transition (CSS)

Can someone assist me with implementing my idea? I want the "anim" animation to start as soon as image1 finishes its transition. My attempted solution: I tried using "animation-delay," but that didn't work for me. The issue is that "animation-delay" ...

Invoke the function of a React component prior to its rendering

When attempting to load an article from the database and set it as a component's state, I encounter an issue where the value of the loaded article's state is undefined. It seems like this problem arises because the function for loading data is be ...

divide a lengthy string into several dynamic divisions

I am attempting to divide a lengthy string into multiple dynamic divs once the height of the div reaches a certain limit. Below is the code that I believed would achieve this: $(document).ready(function () { var arr = longishstring.split(' ' ...

Mist Conceals Celestial View (THREE.JS R76)

I have a cylindrical camera setup with fog to hide the end of the tube. However, I am trying to make the skybox visible through the alpha map sides of the cylinder. The current issue is that the fog is blocking the visibility and I'm looking for a sol ...

Understanding the Parameters for discord.js Slash Commands

I am currently working on a calculation that involves using parameters input through a slash command. While entering the parameters works without any issues, I am facing difficulty in retrieving them. The current code is resulting in an error TypeError: ...

Sending a java array to javascript

Within my application, I am working with an array that is generated after parsing information from JSON. I now need to pass this array to a JavaScript script in order to display an HTML list. On iOS, I have been using the stringByEvaluatingJavaScriptFrom ...

How can we send a JSONArray through a dynamically generated button event and then retrieve the elements of the JSONArray?

In the following SCRIPT code snippet: var jsonArr = [ { " name": "John", "age": 31, "city": "New York" }, { "name": "Smith", "age": 25, "city": "Dubai" } ]; function create() { createButton(jsonArr); } function cre ...

Prevent elements from moving when resizing the window

I have designed a header bar for my webpage that includes elements like , and . The layout looks nice until I resize the browser window, causing everything to move and overlap within the header. Applying a fixed width like "width: 1000px" to the header or ...

What are the steps to crafting a basic JavaScript or jQuery function within CodeIgniter?

I'm currently working on creating a basic JavaScript function within CodeIgniter that is triggered when a radio button is clicked. <input type="radio" name="amount" value="<?php echo $plan['amount']; ?>" onclick="fn()" /> The J ...

What is the best way to add a CSS link if a request is not made using AJAX?

My webpage, 'foo.html', retrieves data from a database using AJAX ('ajax.html?options=option1') to populate a table. The table is styled nicely with CSS that is linked to 'foo.html'. However, I also want the ajax.html page to ...

How can I choose specific options by clicking based on the select name's value with web scraping?

I'm attempting to scrape the select dropdown menu below in order to retrieve its text content. Unfortunately, I can't rely on the name attribute as "P889O1" varies for each product from which I need to extract data. I considered using 'cont ...

Tips on simulating the Q functions during unit testing in node.js using mocha and rewire!

Struggling with an issue while writing unit tests for node.js. The original code in my file is: var Q=require('q') . . . return Q.all(promises).then(function(data) { _.each(data, function(data) { checking.pu ...

Backbone.js: Navigating the Default Path Issue

I've embarked on creating my very first BB app. Progress is decent, but I've hit a roadblock. My router implementation appears as follows: var PlayersAppRouter = Backbone.Router.extend({ routes: { '': 'index', ...

Is it possible to execute custom JavaScript code in an R Jupyter notebook?

Within my Jupyter Notebook, I am working with the R programming language and would like to integrate javascript functions into it. I'm aware that there are libraries in javascript that can be called from R, but I haven't been able to find any ex ...

Arrange the table by adding and editing before and after appending

I have a table data that needs to be dynamically appended. But I want to allow users to add new data using text input and also edit the existing data before and after it's appended. The problem is that when I append new data, it overwrites the previo ...

Raycaster is unable to manipulate BoxMesh objects in any way

I've been working with the Physijs script for simulating physics, such as gravitation. I'm trying to use Raycaster from the THREE.js script to move objects within my scene. The issue I'm facing is that the Raycaster only moves objects (sim ...

Issue with error handling while using HTML5 geolocation in Chrome browser

I have a basic map that is supposed to load centered on the user's current location if they allow HTML5 geolocation. There is a fallback function in place for users who choose not to share their location, but it seems to be malfunctioning. Here is th ...

How to retrieve an array from an object using React

In the context of my React application, I have a function called Query2 within a file named service.ts. The structure of this function is as follows: interface Result { products: number[]; } export async function Query2(molsSdf: string): Promise<Res ...

What is the best way to showcase validation errors based on required fields in PHP?

When dealing with a form, the challenge arises when there are multiple validation errors to display. The dilemma is whether to show all errors at once or individually as per each field requirement. For instance, consider having fields like Name, Email, an ...

Tips for customizing standard data types in TypeScript

Currently facing a challenge where I need to update a global type. Specifically, I am looking to modify the signature of the Element.prototype.animate function to make it optional. This is the approach I attempted: declare global { interface Element { ...