skip to Main Content

So I want a changing background on my website. I’m now on my second page and wanted to do a different background color. I copied the javascript from my first page (because it was working good) and just wanted to change the querySelectors. But then the red waves popped up. I cannot change the [red, green, blue]. Or I can but just don’t know how. How can I change the const [red, green, blue] so it works like before?

Here is a picture from my VSCode:
enter image description here

So here you got the working background.

const [red, green, blue] = [255, 255, 255];
const background1 = document.querySelector('.background1');
window.addEventListener('scroll', () => {
  const y = 1 + (window.scrollY || window.pageYOffset) / 250
  const [r, g, b] = [red/y, green/y, blue/y].map(Math.round)
  background1.style.backgroundColor = `rgb(${r}, ${g}, ${b})`
});
.background1 {
        background-color: rgb(255,255,255);
        height: 7000px;
    }
<p>scroll</p>
<div class="background1"></div>

2

Answers


  1. You can try doing something like this:

    const scrollListener74903087 = ( color, selector, offset ) => {
        const [red, green, blue] = color;
        const background = document.querySelector(selector);
    
        if (! background){
            return;
        }
    
        window.addEventListener('scroll', () => {
            const y = 1 + (window.scrollY || window.pageYOffset) / offset
            const [r, g, b] = [red/y, green/y, blue/y].map(Math.round)
            background.style.backgroundColor = `rgb(${r}, ${g}, ${b})`
        });
    }
    
    scrollListener74903087([255, 255, 255], '.background1', 250);
    scrollListener74903087([0, 208, 255], '.background2', 500);
    
    Login or Signup to reply.
  2. Try to use the keyword var instead of const.

    var red, green, blue;
    
    [red, green, blue] = [255, 255, 255];
    // your first background codes
    
    [...]
    
    [red, green, blue] = [0, 208, 255];
    // your second background codes
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search