I have minimal to no experience with HTML/CSS/JS so most of this is copy and pasted. I am using a website building service called cargo. I am trying to change the background color based on the scroll position of the user. Everything works perfectly when starting at the top and scrolling down. But scrolling up does not allow the colors to change at all (except for the "body" color once you reach the top).
HTML/JS:
<script>
function changeBackground(){
if(scrollY >= 300 && scrollY < 900) {
document.body.classList.add('bg-color');
}
else if(scrollY >= 900 && scrollY < 1900){
document.body.classList.add('bg-color-orangeyellow');
}
else if(scrollY >=1900 && scrollY < 2700){
document.body.classList.add('bg-color-white');
}
else{
document.body.classList.remove('bg-color');
document.body.classList.remove('bg-color-orangeyellow');
document.body.classList.remove('bg-color-white');
}
}
addEventListener('scroll', changeBackground);
</script>
CSS:
body {
background-color:rgb(166, 199, 255);
transition: all 0.5s ease;
}
.bg-color{
background-color: #11923d;
}
.bg-color-orangeyellow{
background-color: #ffb217;
}
.bg-color-white{
background-color: white;
CodePudding user response:
The problem is that in each if statement you're adding classes but not removing them.
One option would be to remove the other classes in each if statement, you could also just set the background color with inline style instead to avoid having to toggle these classes on and off like so:
function changeBackground(){
const bodStyle = document.body.style;
if(scrollY >= 300 && scrollY < 900) {
bodStyle.backgroundColor = '#11923d';
}
else if(scrollY >= 900 && scrollY < 1900){
bodStyle.backgroundColor = '#ffb217';
}
else if(scrollY >=1900 && scrollY < 2700){
bodStyle.backgroundColor = '#ffffff'
}
else{
bodStyle.backgroundColor = 'rgb(166, 199, 255)';
}
}
document.addEventListener('scroll', changeBackground);
body {
background-color: rgb(166, 199, 255);
transition: all 0.5s ease;
height: 5000px;
}
Note: I only added the height to the CSS so you could scroll in the code snippet.
CodePudding user response:
Basically your code exists on the first conditional block that is matched and else
is not called, so those classes are not removed as you go back up. You could make your code a bit more dynamic like this.
function changeBackground() {
const positions = [{
dist: (scrollY >= 300) && (scrollY < 900),
cls: 'bg-color'
},
{
dist: (scrollY >= 900) && (scrollY < 1900),
cls: 'bg-color-orangeyellow'
},
{
dist: (scrollY >= 1900) && (scrollY < 2700),
cls: 'bg-color-white'
}
]
positions.forEach(({
dist,
cls
}) => {
const action = dist ? 'add' : 'remove'
document.body.classList[action](cls)
})
}
addEventListener('scroll', changeBackground);
body {
background-color: rgb(166, 199, 255);
transition: all 0.5s ease;
height: 2700px;
}
.bg-color {
background-color: #11923d;
}
.bg-color-orangeyellow {
background-color: #ffb217;
}
.bg-color-white {
background-color: white;
}