-2

i need a way to add a class when the document scrolled to top and remove it when document scrolled to bottom with only Javascript no jquery or any other plugin.

rateb
  • 31
  • 6

1 Answers1

0

You can use this function to check if the page has been scrolled to the bottom.

window.onscroll = function(){
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
     //bottom of page
    document.getElementsByClassName("header")[0].classList.add("red");
}
}

You can use this function to check if the page has been scrolled to the top.

window.onscroll = function(){
var B= document.body; //IE 'quirks'
    var D= document.documentElement; //IE with doctype
    D= (D.clientHeight)? D: B;

if (D.scrollTop == 0)
    {
       //top of page
        document.getElementsByClassName("header")[0].classList.remove("red");
    }    
}

.header{
  text-align: center;
  position: fixed;
  width: 100%;
  top: 0;
  border: 1px solid black;
  font-size: 20px;
  left: 0;
  background-color: green;
}

.red{
  background-color: red;
}

html, body{
 height: 2000px;
}
<html>
<body>
<div class="header">Header</div>
<script>
window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
         //bottom of page
        document.getElementsByClassName("header")[0].classList.add("red");
    }

   var B= document.body; //IE 'quirks'
    var D= document.documentElement; //IE with doctype
    D= (D.clientHeight)? D: B;

if (D.scrollTop == 0)
 {
       //top of page
  document.getElementsByClassName("header")[0].classList.remove("red");
 }    
   };
</script>
</body>
</html>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80