1

I need to do something like this -> If the scroll goes below 200px, change the page colour to red. If it is over 200px, change it to white. How can I achieve this?

const event11 = window.addEventListener('wheel', function(e) {
  console.log(e);
  console.log(window.innerHeight);
  if(e.pageY < (window.innerHeight - 200)) {
     document.body.style.backgroundColor = "red";
  } else {
    document.body.style.backgroundColor = "white";
  }
});
Jacob
  • 2,769
  • 3
  • 21
  • 29
Shakered
  • 71
  • 7

3 Answers3

2

You can also achieved the scroll position with pure JavaScript scrollY & scrollX properties.

Notes

The pageXOffset property is an alias for the scrollX property, and The pageYOffset property is an alias for the scrollY property

Codepen Example: https://codepen.io/cursorrux/pen/VwKWeRL

Below is example of same effect with scroll event listener:

const event11 = window.addEventListener('scroll', function(e) {
  if(this.scrollY < 200) {
     document.body.style.backgroundColor = "white";
  } else {
    document.body.style.backgroundColor = "red";
  }
});
body {
  min-height: 500px;
}
<html>
  <body>
    
  </body>
</html>
cursorrux
  • 1,382
  • 4
  • 9
  • 20
1

You can find scroll position with window.pageYOffset || document.documentElement.scrollTop;. Use it to compare with your expected height 200.

Also use scroll event instead of wheel because wheel event will only fire on mouse wheel scroll. If some one scrolls page with dragging scrollbar then it won't work. So use scroll event which will work on those case also.

Add window.dispatchEvent(new CustomEvent('scroll')); so initially it will trigger scroll event and set proper background color.

References : 1. JavaScript get window X/Y position for scroll

  1. How to trigger an on scroll event without scrolling

Try it below.

window.addEventListener('scroll', function(e) {
  var top = window.pageYOffset || document.documentElement.scrollTop;
  if (top < 200) {
    document.body.style.backgroundColor = "red";
  } else {
    document.body.style.backgroundColor = "white";
  }
});

// trigger scroll event when page loads.
window.dispatchEvent(new CustomEvent('scroll'));
<div style="height:1000px;">
</div>
Karan
  • 12,059
  • 3
  • 24
  • 40
0

There is one property in DOM tree which shows scroll's current Y position called document.scrollingElement.scrollTop.

const event11 = window.addEventListener('wheel', function(e) {
  
  if(document.scrollingElement.scrollTop > 200) {
     document.body.style.backgroundColor = "red";
  } else {
    document.body.style.backgroundColor = "white";
  }
});
jacobkim
  • 1,043
  • 10
  • 20