user1431398
user1431398

Reputation:

Change CSS background gradient via Javascript on scroll

I'm trying to change one of two background colours of a gradient via Javascript. The color is scroll dependent. Somehow a single color works but not a gradient.

const [red, green, blue] = [0, 200, 0];
const hasGradient = document.querySelector('.has-gradient');

window.addEventListener('scroll', () => {
  let y = 1 + (window.scrollY || window.pageYOffset) / 150;
  y = y < 1 ? 1 : y
  const [r, g, b] = [red/y, green/y, blue/y].map(Math.round);
  hasGradient.style.background = `linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0));`;
  console.log(`linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0))`)
});

Thx for any input!

Upvotes: 2

Views: 709

Answers (2)

dommilosz
dommilosz

Reputation: 127

Y is often <0. You need to make it always positive with y = y < 0 ? -y : y.

const [red, green, blue] = [0, 255, 0];
const hasGradient = document.querySelector('.has-gradient');
hasGradient.style.background = `rgb(${red},${green},${blue})`

window.addEventListener('scroll', () => {
  let y = 1 - (window.scrollY || window.pageYOffset) / 150;
  y = y < 0 ? -y : y
  const [r, g, b] = [red/y, green/y, blue/y].map(Math.round);
  hasGradient.style.background = `linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0))`;
  console.log(y)
  console.log(`linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0))`)
});
div {
  height: 7000px;
  width: 500px;
}
<div class="has-gradient">

</div>

Upvotes: 1

S.Visser
S.Visser

Reputation: 4725

You using a ; in your string.

  hasGradient.style.background = `linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0));`;

Should be:

  hasGradient.style.background = `linear-gradient(rgb(${r}, ${g}, ${b}), rgb(255,0,0))`;

Note: It is not possible to set styles by assigning a string to the style property, e.g. element.style = "color: red;". To set the style of an element, append a "CSS" property to style and specify a value

Reference: https://www.w3schools.com/jsref/prop_html_style.asp

Demo: https://jsfiddle.net/faod18mL/

Upvotes: 1

Related Questions