Scroll is not binded, and I am stuck

Viewed 48
var id  = document.querySelector("#arrowUp");
var arrowUp = window.pageYOffset >= 5;
console.log(arrowUp);
id.classList.toggle("arrowUp", arrowUp);
id.addEventListener('click', function() {
    window.scrollTo(0, 0);      
})

I am trying to insert a class in certain HTML based on the scroll, but the issue is this part of the code:

var arrowUp = window.pageYOffset >= 5;

It is not dynamically getting true or false based on the scroll and the condition window.pageYOffset >= 5; is not dynamically true or false right now. Hence anticipated class is not getting inserted/deleted.

How to bind this part of the code to scroll event

2 Answers

Add an EventListener for the scroll event.

var id = document.querySelector("#arrowUp");

id.addEventListener('click', function() {
  window.scrollTo(0, 0);      
})

window.addEventListener('scroll', function() {
  var arrowUp = window.pageYOffset >= 5;

  if (arrowUp == true) {
    id.classList.add('visible');
  } else {
    id.classList.remove('visible');
  }
})

You can't do this "dynamically", window.pageYOffset is not a magic dynamic variable, it's a getter (function without arguments that retrieves some value)

In order for this to work, you have to check on each scroll event is the condition holds true.

var id  = document.querySelector("#arrowUp");
document.addEventListener("scroll", function() {
  var arrowUp = window.pageYOffset >= 5;
  console.log(arrowUp);
  id.classList.toggle("arrowUp", arrowUp);
});
id.addEventListener('click', function() {
    window.scrollTo(0, 0);      
});
Related