Adjust the background color dynamically as you scroll, given that I am using a linear-gradient

Is it possible to change the color background using JavaScript while scrolling, especially if I have a linear gradient like this:

  background: linear-gradient(115deg, #42c344 0%,#42c344 40%,#c4efc4 40%,#ffffff 40%,#ffffff 100%); background-attachment: fixed;

I came across these resources that demonstrate how to achieve this effect: http://jsfiddle.net/cgspicer/V4qh9/ and http://codepen.io/Funsella/pen/yLfAG/

Answer №1

To create a gradient effect, utilize RGB values and apply animation using Javascript.

Check out the randomized example below or in the linked pen. Trigger the updateGradient function with your 'on scroll'/'wheel' event:

var colors = new Array(
  [62,35,255],
  [60,255,60],
  [255,35,98],
  [45,175,230],
  [255,0,255],
  [255,128,0]);

var step = 0;
//color table indices for: 
// current color left
// next color left
// current color right
// next color right
var colorIndices = [0,1,2,3];

//transition speed
var gradientSpeed = 0.002;

function updateGradient()
{

  if ( $===undefined ) return;

var c0_0 = colors[colorIndices[0]];
var c0_1 = colors[colorIndices[1]];
var c1_0 = colors[colorIndices[2]];
var c1_1 = colors[colorIndices[3]];

var istep = 1 - step;
var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
var color1 = "rgb("+r1+","+g1+","+b1+")";

var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
var color2 = "rgb("+r2+","+g2+","+b2+")";
  
  $('#gradient').css({
    background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({
    background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

  step += gradientSpeed;
  if ( step >= 1 )
   {
    step %= 1;
    colorIndices[0] = colorIndices[1];
    colorIndices[2] = colorIndices[3];

    //pick two new target color indices
    //do not pick the same as the current one
    colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * 
(colors.length - 1))) % colors.length;
    colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * 
(colors.length - 1))) % colors.length;

  }
}

setInterval(updateGradient,10);

http://codepen.io/quasimondo/pen/lDdrF

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

Overlaying images responsively on top of each other

I have successfully achieved the result of displaying an image over another image using the following code: <div class="row"> <div class="col-lg-6 col-md-6 col-sm-12"> <div class="image-with-overlay"> <div clas ...

Update the Bootstrap CSS styling of a button element following a user's click action

I am currently working with Bootstrap and facing an issue where I am trying to change the button color, but after clicking it and moving the mouse away, the color reverts back to blue. Here is the color I initially selected: https://i.sstatic.net/DCMq5.p ...

Prevent overlapping of nodes and edges in a D3 force-directed layout

Check out this fascinating example at http://bl.ocks.org/mbostock/1747543: In the demonstration, Mike illustrates how to prevent nodes from colliding with each other in a graph. I'm curious if it's feasible to also prevent collisions between no ...

A guide on how to align Hamburger CSS in the center, center text, and include a

For a while now, I've been attempting to achieve three specific things with a Hamburger menu, but so far, I've had no luck. This Hamburger menu is responsive, transitioning into an X symbol upon clicking and moving to the right of the page with a ...

Is there an easy way to determine if an element inside a Vue component is overflowing?

I created a unique component called ResultPill which includes a tooltip feature (implemented using vuikit). The text displayed in the tooltip is determined by a getter function called tooltip, utilizing vue-property-decorator. Here are the relevant parts o ...

Tips for resolving the issue of "Warning: validateDOMNesting(...): <div> cannot be a child of <tbody>"

Users list is passed as a prop to the UserItem Component in order to iterate over the user list and display them on a table. The list is being displayed correctly, and there are no divs in the render return, but an error persists: tried many solutions fou ...

The Ray Intersect function in THREE.js encounters issues when a div element is introduced

I have encountered an issue with my Three.js script. It works perfectly fine when there is only one target div on the page holding renderer.domElement. However, when I add another div with fixed height and width above the target div, the ray.intersectObjec ...

Are JavaScript Object notation and proper JSON the same thing?

When I execute valid JSON in the Chrome console: {"aaa":"bbb"} I encounter this error: SyntaxError: Unexpected token : But if I try something like this instead: {aaa:"bbb"} No error is thrown. Additionally, when running the following code ...

Creating a stylish button using a combination of CSS and Javascript classes within a webpage layout

Is it feasible to include a button in the layout that has HTML, CSS styles, and JavaScript functionality? For instance: This button is designed with both CSS styling and JavaScript classes. How can one incorporate CSS and JavaScript along with HTML conte ...

Implement Material-UI's built-in validation for form submission

I'm in the process of setting up a form with validation: import React from 'react'; import { useForm } from "react-hook-form"; import axios, {AxiosResponse} from "axios"; import {Box, Button, Container, Grid, Typography} ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

Reactive JS memory leakage occurring from recurring calculations utilizing setInterval

I'm currently working on a task where I need to run a calculation every 5 seconds and update a component's state with the result using a setInterval timer. It seems that the updateCalculation() function is being called every 5 seconds, but I&apos ...

Is there a way to prevent Bootstrap offcanvas from causing the website to scroll?

Utilizing a Bootstrap offcanvas for a <nav> menu on a mobile site, I aim to navigate users to specific sections of the website when they click on a <li>. I've implemented a simple JavaScript script that triggers the offcanvas exit button a ...

In what ways can we utilize a consistent state across various tabs or pages?

One feature of my application is a dynamic chart with various settings such as filters and time ranges. I want to save these settings in the app's state so they can be shared with other components on different pages. However, when switching tabs and r ...

Ways to refresh a container

How do I update the box below... <div className="container team-member-tasks"> <header className="header-box"> <h1>Team Member Tasks</h1> ...after marking a task as complete using the script below. ...

Loading React Components dynamically depending on user input

Looking to dynamically render different Components based on checkbox selections without unnecessary component imports. Using an Array with Component names (using numbers for example) to import each component based on the array values. Considered the foll ...

The timeline aesthetic can be achieved solely through the use of HTML, CSS, and potentially some Bootstrap functionalities

https://i.sstatic.net/EsDAE.png Up to this point, I've only been able to make it this far. I'm using a sample code from w3school https://i.sstatic.net/G1FcQ.png I've been attempting to get the year in the same position as in the image, bu ...

Angular $watch not working as expected

I have a specific directive code: .directive('myDirective', function(){ 'use strict'; return { restrict: 'A' , link: function(scope, element, attrs) { var count = 0; function d ...

What is the best way to access the CSS resources within the designated Area section of an MVC project?

I am experiencing difficulties accessing a CSS file located within the MVC AREA section. Here is the direct path to the CSS file. After attempting to troubleshoot with firebug, I received the following error message: The stylesheet was not loaded ...

Switching between all tabs simultaneously in an MDX page (React + Gatsby + MDX) using @reach/tabs

Creating a Tab component for a Gatsby site has proved to be a bit tricky. Imagine having a page with multiple tabs all labeled the same: Heading 1 First tab block Tab 1 | Tab 2 Content Tab 1 Second tab block Tab 1 | Tab 2 Content Tab 1 for the second bl ...