Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I wanted to make a color changing background. The script works fine and I'm happy with it. But now there is the error that background is null.



JavaScript
const scroll = ( color, selector, offset ) => {
  const [red, green, blue] = color;
  const background = document.querySelector( selector );
  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})`;
  });
};
scroll([255, 255, 255], '.background1', 250);
scroll([0, 208, 255], '.background2', 500);


What I have tried:

I tried a .ready function. I tried a document.addEventListener("DOMContentLoaded") but it still didn't work. So I came up with the idea asking for help.
Posted
Updated 25-Dec-22 16:51pm
Comments
0x01AA 25-Dec-22 13:16pm    
Yeah, what background should it be? mabye this?
weti09 25-Dec-22 13:30pm    
Hmm, isn't background = selector = '.background1/2'?

1 solution

const background = document.querySelector( selector );

As stated here: Document.querySelector() - Web APIs | MDN[^]

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

Since you know that background is null, you need to see what selector you are passing and if there is actually any element corresponding to it that can be returned.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900