0

Anybody knows how that works? I want to change the background-color of a fixed header when the page is scrolled. One way to do that is to add a class after the page is scrolled (e.g. after 100px). But then the header will change the background exactly after scrolling 100px. What I want is a bit more tricky. On each pixel it should be e bit more or less of the change.

80px scrolled rgba(0, 0, 0, 0.10) 81px scrolled rgba(0, 0, 0, 0.11) 82px scrolled rgba(0, 0, 0, 0.12) ...

You can see an example for that here: http://demo.thememodern.com/architect/homepage-5/

Anybody knows how that works? Thanks for ideas!

1
  • Write with JS the background-color as inline-style, where the alpha value depend on the current scroll position. Commented May 31, 2021 at 18:19

2 Answers 2

2
<style>
body {
  height: 3000px;
  background: linear-gradient(141deg, #0fb8ad 0%, #1fc8db 51%, #2cb5e8 75%);
}
</style>
Sign up to request clarification or add additional context in comments.

Comments

0

I think here is the answer that you are looking for,

JS

// when the user start scrolling
window.addEventListener('scroll',()=>{

// now call the background
const myBackground = document.getElementById('myBG');

// now the condition when the user start scrolling then change the color
if(window.pageYOffset > 400){
   myBackground.classList.add("is-sticky");
   myBackground.classList.remove("is-sticky2");
}

else if(window.pageYOffset > 200){
    myBackground.classList.remove("is-sticky");
    myBackground.classList.add("is-sticky2");
} 

// when the header be in the top of the page that mean window.pageYOffset = 0 so
else{
    myBackground.classList.remove("is-sticky");
    myBackground.classList.remove("is-sticky2");
}
})

CSS you need to add those classes :

.is-sticky{ background-color: blue;}
.is-sticky2{ background-color: red; }

and ofc the header should have the Id that we used in js code

1 Comment

Thanks, looks like it is what I was searching for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.