Search code examples
javascriptscrolloffset

Scroll is not binded, and I am stuck


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


Solution

  • 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');
      }
    })