30

Suppose we have a html page with large height.So there will be a vertical scrollbar.

As the user scrolls down I want to know how much he has scrolled using javascript (jquery) I suppose... Is this possible?

T J
  • 42,762
  • 13
  • 83
  • 138
gadlol
  • 1,343
  • 2
  • 15
  • 24

6 Answers6

63

In pure javascript you can simply do like that:

window.onscroll = function (e) {
    console.log(window.scrollY); // Value of scroll Y in px
};

More infos (The Mozilla Developer Network) :

Fabien Sa
  • 9,135
  • 4
  • 37
  • 44
26

You can do this using .scroll() and .scrollTop().

 $(window).scroll(function() {
     // use the value from $(window).scrollTop(); 
 });

See also this question.

Community
  • 1
  • 1
justkt
  • 14,610
  • 8
  • 42
  • 62
6

This is what i used on my website... when anyone scrolls 620 pixels down the menu will pop up, I input the numbers manually. I'm still a noob at javascript but I hope this helps

    <script>
    $(document).ready(function(){
        $(window).scroll(function(){
            var scrollTop = 620;
            if($(window).scrollTop() >= scrollTop){
                $('.Nav').css({
                    position : 'fixed',
                    top : '0'
                });
            }
            if($(window).scrollTop() < scrollTop){
                $('.Nav').removeAttr('style');  
            }
        })
    })
    </script>
T J
  • 42,762
  • 13
  • 83
  • 138
Four.Twenty
  • 51
  • 1
  • 4
  • 3
    While this works, it could be improved, no need for the second if statement, just use an else. Also just removing the 'style' attribute could be dangerous if there is something else inline styled, perhaps by another js function. I think a better practice would be to reverse the style you added in the initial if – jakecraige Aug 07 '13 at 13:30
5

Yes. See scrollTop() in jQuery, which wraps the scrollTop DOM property.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
3

You can use window.scrollX to detect how much pixels the user has scrolled right.
You can use window.scrollY to detect how much pixels the user has scrolled down.
You can use window.scrollTo(x, y); to set scroll pixels right (x) and down (y).


Example code:
var x = window.scrollX, y = window.scrollY;
window.scrollTo(0, 200);
Plantt
  • 230
  • 1
  • 10
0

This will work fine in chrome

window.addEventListener('scroll', function() {
    console.log(scrollY);
});
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129