Tinku
Tinku

Reputation: 1

How to change background color on scroll in javascript

I am working on a wordpress website on localhost and using plugin script and style for custom javascript. I want to change the background color when scroll value changes e.g.

scroll value 0-100 then color red

scroll value 100-200 then color blue

scroll value 200-300 then color pink

scroll value 300-400 then color black

scroll value 400-500 then color orange

by this code i am able to add only one class in first condition of javascript.

.site-main{
background-color:green !important;
}
.scrolled1{
background-color:yellow !important;
}
.scrolled2{
background-color:pink !important;
}
.scrolled3{
background-color:black !important;
}
.scrolled4{
background-color:orange !important;
}
.scrolled5{
background-color:red !important;
}

<script>
alert("success");
window.onscroll = function() {myFunction()};

function myFunction() {
if((document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) && (document.body.scrollTop < 100 || document.documentElement.scrollTop < 100)){

document.getElementById("main").className = "scrolled2";
    }

else if((document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) && (document.body.scrollTop < 200 || document.documentElement.scrollTop < 200)){

document.getElementById("main").className = "scrolled3";
    } 
  else {
        document.getElementById("main").className = "site-main";
    }
}
</script>

Upvotes: 0

Views: 1090

Answers (1)

Irina Potapova
Irina Potapova

Reputation: 794

Please check it. If you need to have #main green when page loaded, just add .site-main class to your div in html.

window.onscroll = function() {myFunction()};

function myFunction() {
	var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
  var elem = document.getElementById("main");
  
  if (scrollTop > 0 && scrollTop < 101) {
  	elem.className = "scrolled5";
  } else if (scrollTop > 100 && scrollTop < 201) {
  	elem.className = "scrolled6";
  } else if (scrollTop > 200 && scrollTop < 301) {
  	elem.className = "scrolled2";
  } else if (scrollTop > 300 && scrollTop < 401) {
  	elem.className = "scrolled3";
  } else if (scrollTop > 400 && scrollTop < 501) {
  	elem.className = "scrolled4";
  } else {
  	elem.className = "site-main";
  }
}
.site-main{
background-color:green !important;
}
.scrolled1{
background-color:yellow !important;
}
.scrolled2{
background-color:pink !important;
}
.scrolled3{
background-color:black !important;
}
.scrolled4{
background-color:orange !important;
}
.scrolled5{
background-color:red !important;
}
.scrolled6 {
  background-color: blue !important;
}
<div id="main" style="height: 10000px;"></div> <!-- temporary height -->

Upvotes: 4

Related Questions