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.
Asked
Active
Viewed 56 times
-2
-
1what did you try so far? – messerbill Jul 27 '18 at 14:28
-
4why tag with jquery if you don't want jquery answers? – Pete Jul 27 '18 at 14:29
-
Possible duplicate of [Capturing the "scroll down" event?](https://stackoverflow.com/questions/4670834/capturing-the-scroll-down-event) – messerbill Jul 27 '18 at 14:30
-
have a look here: https://stackoverflow.com/a/32757060/4450187 – messerbill Jul 27 '18 at 14:31
-
What have you already tried... – Adam Jul 27 '18 at 14:33
-
i did not try because i don't know a way to do that – rateb Jul 27 '18 at 14:37
-
sorry about Jquery tag i removed – rateb Jul 27 '18 at 14:37
1 Answers
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
-
no man that is not what i'm asking for. i said toggle this code just add class not remove class – rateb Jul 27 '18 at 14:39
-