skip to Main Content

I want to know what is scrollTop and using jQuery. But, it’s always showing 0.

here is my jQuery code:

var scrollTop = $(window).scrollTop()

//onscroll
window.onscroll = function (e) {
    console.log(scrollTop);
}

If need, I can also add HTML and CSS codes.

I try to use JavaScript:

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

//onscroll
window.onscroll = function (e) {
    console.log(scrollTop);
}

But, same.

If answer isn’t writed in jQuery it’s better.

3

Answers


  1. scrollTop will initially get set to 0, then every time you log it, it’s going to use that value.

    If you want a new value for scrollTop, it needs to be recalculated. Put the calculation inside of your function bound to window.onscroll.

    Login or Signup to reply.
  2. The value of scrollTop is not being updated dynamically in the onscroll event handler. Instead, it is only assigned once when the script is initially run.
    Maybe this?

    Using jQuery:

    // onscroll
    $(window).scroll(function () {
      var scrollTop = $(window).scrollTop();
      console.log(scrollTop);
    });
    

    Plain JS:

    window.addEventListener('scroll', function () {
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      console.log(scrollTop);
    });
    
    Login or Signup to reply.
  3. Your scrollTop variable is initialized but it is not updated inside the onscroll function, that’s why it remains unchanged. Explanation: your onscroll function is called each time you move your cursor, and its state (positions:e.pageY) is stored in the variable e of your onscroll function.

    Here is a way to get the cursor/pointer position onScroll using jQuery:

    $(window).on('scroll', function(e) {
      var current_position_from_top = e.pageY;
      console.log('Vertical position in pixel:', current_position_from_top);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search