Change the background color of the top element box when scrolling

The code I have implemented reflects my intentions.

html:

<div id="one" class="box"></div>
<div id="two" class="box"></div>
<div id="thr" class="box"></div>
<div id="fou" class="box"></div>
<div id="fiv" class="box"></div>
<div id="six" class="box"></div>

script:

$(document).ready(function(){
    $(window).scroll(function(){
        $('.box').each(functions(e){
            if($(this).offset().top <= 0) {
                $(this).css('background-color','green');
            }
        });
    });
});

css:

div {
    position:relative;
    width:100%;
    height:300px;
    background-color:orange;
    margin:10px;
}

fiddle: http://jsfiddle.net/VR4ca/

When scrolling, the box at the top should change its background color to green until the next box reaches the top of the window

Your assistance is appreciated.

Even after making changes, the code does not seem to work as expected http://jsfiddle.net/VR4ca/2/

Answer №1

$(window).scroll(function(){
    var pixelScrolled = $(window).scrollTop();
    $( ".box" ).each(function( index ) {
    var currentHeight = $(this).height();
        if (pixelScrolled >= index * currentHeight)
            $(this).addClass('active');
        else
            $(this).removeClass('active');
    });
});

For a more accurate measurement, consider using .outerHeight() or .outerHeight(true) instead of .height(). This will include the size of border, padding, and margin in the calculation.

Check out the demo to see it in action:

Answer №2

If you're looking to keep the top element green at all times, you can use a code snippet like the one below:

$(document).ready(function(){
    $(window).scroll(function(){
        num=Math.ceil($(window).scrollTop()/$('.box').height());
        $('.box').css('background-color','orange');
        $('.box:nth-child('+num+')').css('background-color','green');      
    });
});

Check out the demo here!

For a more streamlined solution, you can try this code:

$(document).ready(function(){
    $(window).scroll(function(){
        num=Math.trunc($(window).scrollTop()/$('.box').height());
        $('.box').css('background-color','').eq(num).css('background-color','green');      
    });
});

Here's the demo for this cleaner solution.

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

An abundance of AJAX requests inundating the server

While working on a straightforward AJAX request, I encountered an issue where the server is sending back 3 responses instead of just one (you can see the example in the attached image). Could someone provide insight into why this might be happening? var ...

Embed PHP PDO using AJAX

I've been stuck for days now, unable to solve what should be a simple problem. My goal is to perform a basic insert operation using ajax. Even though I am new to PHP, I have gone through numerous examples, studied POST requests in HTTP and PHP, revie ...

Make sure to save the data in a file correctly by utilizing JSON.stringify before storing

When I use this code snippet: function item(name, number){ this.name = name; this.number = number; } var item1 = new item('a',1); var item2 = new item('b',2); var box1 = [item1,item2]; console.log(box1); var box2 = JSON.strin ...

Typescript: The type 'X' does not correspond with the signature '(prevState: undefined): undefined' in any way

My React Native app, which is written in TypeScript, has been giving me a hard time with an error lately. The issue revolves around a Searchable List feature. This list starts off with an Array of values and gets updated when users type into a search bar. ...

Troubleshooting an expressjs server in parallel with electron

I have managed to successfully run an ExpressJS server alongside Electron by following the instructions provided in this post: Run Node.js server file automatically after launching Electron App However, I am facing an issue where there is no output from t ...

I am facing an issue where my AngularJS code is not executing properly on JSF

I'm trying to clear the text inside a textarea using AngularJS after typing and clicking on a button. Here's the link to the fiddle for reference: http://jsfiddle.net/aman2690/2Ljrp54q/10/ However, I keep encountering the following error messag ...

Unable to retrieve information using the post method in Express framework

After creating a basic code to fetch data from the client, I am facing an issue where req.body.firstname is showing as undefined. Here is the code snippet: const express = require('express'); const app = express(); const body ...

When utilizing the image upload AJAX feature, duplicates of the uploaded images may appear without reloading the page

Currently grappling with a peculiar issue involving an ajax upload script embedded in a form loaded within a modal. Let me break down the strange behavior: Upload image 1 No problems encountered here. Upload image 2 Encountering issues whereby two id ...

Extracting a nested property from a JSON object without relying on the lodash get method

We have a sample json data: { "name": "app", "version": "0.1.0", "description": "Sample description", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "so ...

The XMLHttpRequest is displaying additional characters within its response

Upon completing an XMLHttpRequest(), I am receiving the unexpected output of "true↵↵↵". In my php file, all I have is echo json_encode(true); Can anyone shed some light on why this strange behavior is occurring? Thank you ...

Error: 'require' is not recognized as a valid command - Node.js

I recently attempted to integrate the d3-gauge plugin into a basic node.js/express server. Following the default directory structure generated by Express, I organized the files from the 'example' folder as follows: . ├── app.js ├── b ...

Calculating the product of two input fields and storing the result in a third input field using a for loop

There's a small issue I'm facing. I have implemented a For Loop to generate multiple sets of 3 input fields - (Quantity, Rate, Price). Using a Javascript function, I aim to retrieve the Ids of 'Quantity' and 'Rate', and then d ...

Sharing data between app.js and client-side files in Node.js: How to do it effectively?

I have a question about passing a value from my Node.js app.js file to my client-side JavaScript file. Here is my app.js file: var express = require('express'); var app = express(); var port = process.en ...

find the next earliest date in the array after the specified date

How can I find the smallest date in an array of dates that comes after a specific date? var datesArray = ['2019, 10, 4', '2019, 10, 13', '2019, 10, 8', '2019, 10, 6']; ownDate = '2019, 10, 05'; I need to ...

"Encountering difficulties while trying to modify the QuillNoSSRWrapper value within a Reactjs

Currently, I am working on a project involving ReactJS and I have opted to use the Next.js framework. As of now, I am focused on implementing the "update module" (blog update) functionality with the editor component called QuillNoSSRWrapper. The issue I ...

I'm encountering an error when trying to return a value using the question mark operator in Vue.js - can someone explain why

When I attempted to retrieve the value using the question mark operator instead of using return twice, I encountered an error stating "Cannot read property 'omitDescription' of undefined." buttonText() { return this.omitDescription ? 'プ ...

What is the proper way to include a URL when submitting an AJAX form?

When I try to call a servlet using HTML, jQuery and Ajax by submitting a form, I keep getting a 404 error saying the resource cannot be found. My project is built with Maven. The Servlet is located in the src/main/java package under : com.mycompany.sample ...

The alignment of the table appears off on Internet Explorer, while it is perfectly centered on all other web

I'm encountering a strange issue with my table alignment on Internet Explorer. The table is offset to the right in IE, but perfectly centered in other browsers like Edge, Firefox, and mobile browsers. I am using Bootstrap for my design, but haven&apos ...

How can I simulate pressing the ENTER key in Selenium without selecting any element?

Having trouble using the firefox selenium plugin and sending the enter key after pasting text? The ENTER key press should not interact with any other element on the page, just a simple 'dumb' ENTER key press. error [error] Element name=code not ...

What techniques can be used to ensure an element remains visible within the viewport

I am currently working with an HTML element that is displayed when a button is clicked, similar to a popup. My goal is to determine if the element is within the browser's viewport and then position it accordingly inside the viewport. Is there a proper ...