Mariana Stefani
Mariana Stefani

Reputation: 57

Dynamically change navbar color on scroll

I found this great solution here on stack:

const [red, green, blue] = [69, 111, 225]
const section1 = document.querySelector('.section1')

window.addEventListener('scroll', () => {
  let y = 1 + (window.scrollY || window.pageYOffset) / 150
  y = y < 1 ? 1 : y // ensure y is always >= 1 (due to Safari's elastic scroll)
  const [r, g, b] = [red/y, green/y, blue/y].map(Math.round)
  section1.style.backgroundColor = rgb(${r}, ${g}, ${b})
})

But I'd like to change my color from rgba(249, 82, 4, 1) to white. Any help is very much appreciated.

Upvotes: 1

Views: 507

Answers (1)

Kirill Simonov
Kirill Simonov

Reputation: 8491

Tweaking the computations a little, you could get something like this (instead of reducing the rgb values and fading to black, we are now increasing them and hence fading to white):

const [red, green, blue] = [249, 82, 4];
const section1 = document.querySelector('.navbar');

window.addEventListener('scroll', () => {
  let y = 1 + (window.scrollY || window.pageYOffset);
  y = y < 1 ? 1 : y;
  const [r, g, b] = [red + y, green + y, blue + y].map(Math.round);
  section1.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
})
body {
  height: 100vh;
  margin: 0;
  padding: 0;
}
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgb(249, 82, 4);
  height: 50px;
  width: 100%;
  transition: background-color 200ms ease;
}
.section {
  background: rgb(249, 82, 4);
  height: 300%;
 
}
<html>
<body>
  <section class="navbar">
  </section>
  <section class="section">
  </section>
</body>
</html>

Upvotes: 1

Related Questions