0

I'am trying to detect the scroll of a web page using JavaScript

I want to get an alert once only when the page is at top or not

var top = true;
      
    $(window).on('scroll', function () {
      
      if (window.scrollY > 0 && top==true) {
        top = false;
       alert("not top");
      }else if (window.scrollY == 0 && top==false){
       top = true;
       alert("top");
      }     
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The above code is not triggering alert at all !

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71

1 Answers1

-1

The problem here is top is a javascript global variable which is conflicting with your variable. Your solution will work if you use another variable. If you just want an alert when the window is scrolled to the top then you can use the following solution -

$(window).on('scroll', function () {
    if(window.pageYOffset === 0) {
        alert("top");
    }
})
neha soni
  • 221
  • 3
  • 12