Incorporating a splash of color while changing the background color on scroll

Is it possible to include more colors between the "beginning-color" and the "ending-color" in this code that changes the background color on scroll?

example

    $(document).ready(function(){  

    var scroll_pos = 0;
    var animation_begin_pos = 0;
    var animation_end_pos = $(document).height();
    var beginning_color = new $.Color( 'rgb(140,212,208)' ); 
    var ending_color = new $.Color( 'rgb(145,216,247)' ); ;//what color we want to use in the end
    $(document).scroll(function() {
        scroll_pos = $(this).scrollTop(); 
        if(scroll_pos >= animation_begin_pos && scroll_pos <= animation_end_pos ) { 
           // console.log( 'scrolling and animating' );
            //we want to calculate the relevant transitional rgb value
            var percentScrolled = scroll_pos / ( animation_end_pos - animation_begin_pos );
            var newRed = beginning_color.red() + ( ( ending_color.red() - beginning_color.red() ) * percentScrolled );
            var newGreen = beginning_color.green() + ( ( ending_color.green() - beginning_color.green() ) * percentScrolled );
            var newBlue = beginning_color.blue() + ( ( ending_color.blue() - beginning_color.blue() ) * percentScrolled );
            var newColor = new $.Color( newRed, newGreen, newBlue );
            //console.log( newColor.red(), newColor.green(), newColor.blue() );
            $('body').animate({ backgroundColor: newColor }, 0);
        } else if ( scroll_pos > animation_end_pos ) {
             $('body').animate({ backgroundColor: ending_color }, 0);
        } else if ( scroll_pos < animation_begin_pos ) {
             $('body').animate({ backgroundColor: beginning_color }, 0);
        } else { }
    });
});

Answer №1

Latest Update: featuring a variety of background colors.

To implement this, simply follow these steps:

$(document).ready(function(){ 
    var colorArray = ['purple', 'teal', 'pink', 'grey', 'brown'];
    $(window).on('scroll',function(){
        var index = $('body').scrollTop()%5;
        $('body').animate({
            backgroundColor: colorArray[index]
        }, 100);
    });
});

Adjust the color codes according to scrollTop() value.

Create your own array of color codes and assign them based on the scrollTop().

Check out Live Demo

Answer №2

Generate a unique color code with the help of this script:

const generateColorCode = () => {
    return 'rgb('
           + (Math.floor(Math.random() * 256)) + ','
           + (Math.floor(Math.random() * 256)) + ','
           + (Math.floor(Math.random() * 256)) + ')';
}
var colorcode = generateColorCode();

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

Using jQuery to show text upon hover using a `for` loop

I'm currently working on a webpage and incorporating a feature where hovering over specific div elements triggers the display of certain text in another div. There are 5 elements that I want to make hoverable and show text upon interaction. After imp ...

Tips for maintaining consistent image dimensions while resizing your browser window

I'm having trouble preventing an image from resizing when I adjust the browser size. If you click on this link and try resizing your browser, you'll see what I mean - the image stays the same. I've attempted various methods but haven't ...

Having issues with the functionality of Bootstrap 4 popover?

In my Spring MVC web project, a Bootstrap popover appears when the help icon is clicked. However, on the first click, the popover opens and moves away from the icon. After closing it and clicking again, the popover correctly positions itself. When I chan ...

Generating dynamic content in a text field based on user selection from a dropdown menu using PHP

I have a database with two fields: package_title and package_cost. I am currently displaying the package_title in a dropdown menu using a while loop. When a customer selects a package_title from the dropdown, I would like to show the corresponding cost (pa ...

Overriding the w-4xl with sm:text-2xl in Tailwind CSS

Struggling to achieve responsive design on my Pages, especially with changing text size when the screen is small. I've been following all the correct steps and maintaining the right order. However, whenever I set 'sm', it seems to override a ...

Initiating a animation prior to the execution of JQuery's load() function

I'm currently exploring the functionalities of JQuery's load() function and I am puzzled as to why a particular animation does not occur prior to the load request. For instance, when I include a script like this: $('#clickme').click(f ...

When making an Ajax request, the response is received successfully, however, the success, complete, and error

I am attempting to retrieve SQL results from a database using an AJAX call and display them on another PHP page. Here is my AJAX call code: function newfunc(){ start += 10; var params = parseURLParams(document.URL); var datastring = "nextStart="+start+"&a ...

Inquiring about CSS classes for numerous elements

table.rightlist td { text-align:right; } table.rightlist th { text-align:right; } This code snippet is intended to align both the table cells (td) and headers (th) to the right within a table with the "rightlist" class. However, upon testing the ...

I'm facing an issue where TailwindCSS fails to stretch my VueJS application to full screen width

My components are all contained within a div with classes flex-row, w-screen, and content-center. However, when I switch to reactive/mobile mode on the browser, it only takes up about 2/3 of the screen and doesn't fill up the remaining space. Below i ...

The JSON.stringify function was successfully sent to my PHP file, but upon attempting to decode it with json_decode, an error occurred which

Using jQuery to send data: jsonString = JSON.stringify(arrReturn); $.ajax({ url: 'add-performa-invoice.php', method: 'post', data: {'pro_table': jsonString}, success: function(data, status, j ...

Implement jquery styling to ajax response

Incorporating a jquery carousel to showcase images within a dynamically updated list has proven fruitful initially. However, once the content within the carousel container is replaced via ajax, all formatting seems to vanish. The root cause of this issue ...

Transform spaces into %20 from an HTML input field by utilizing JavaScript or jQuery

Hi there, I'm encountering an issue with the input field on my website where users can enter search terms. I am currently extracting the user's input value and adding it to a URL string. jQuery("#searchButton").click(function(){ var simpl ...

Once the record has been successfully inserted on the index.aspx page, the function will redirect to the Ajax success method in Asp

When I insert a record on the index.aspx page and redirect to the ajax success function, the message should display alert("success"). I created the function addProject() to handle this task. Surprisingly, there were no errors during the process of adding t ...

Alter the background color of a div contingent on the checkbox being checked within

I am in search of a solution to modify the background color of a parent div that contains a checkbox. The condition is that the background color should only change when the 'checked' attribute is present within the tag. HTML <div class="comp ...

How to achieve a seamless iframe effect using CSS

With the introduction of new HTML5 iframe attributes, there are now more options available. One such attribute is the seamless attribute, which has the ability to: Create an iframe that appears to be seamlessly integrated into the containing document. ...

Troubleshooting: Unable to fetch CSS file in Node.js Express framework

I'm trying to access my .html file with localhost using node.js, but I'm facing an issue with loading the CSS that is included in the file. I am using the express framework for this purpose. Code: var express = require('express'); var ...

I am facing an issue where the text I included is not appearing on the website that

While developing a React version of my online portfolio, I encountered an issue. Once deployed on GitHub pages, the text on my landing and contact pages disappeared. Despite removing the background image thinking it might be hiding the text, the issue pers ...

Flashing images with jQuery Flickrush - Encasing the image within <li> tags

I have a div with an unordered list inside: <div id="flickr"> <ul></ul> </div> Currently, I am utilizing a plugin found at this link. To make it functional, I've included the following Javascript code: $(function() { $( ...

Trouble with the Ngx-Captcha feature

I am currently utilizing https://www.npmjs.com/package/ngx-captcha/v/11.0.0. <ngx-recaptcha2 #captchaElem [siteKey]="'6Leh1ZIjAAAAAG8g0BuncTRT-VMjh3Y7HblZ9XSZ'" (success)="handleSuccess($event)" [useGlobalDomain]="fals ...

Verify the presence of values in several textarea fields with jQuery before executing a specified action

My main goal is to validate multiple dynamic forms on a single page. If all textareas are either empty or contain default values, I need a specific function to be executed. However, if any of the textareas have content that deviates from the default value, ...