81

I have a web document with scroll. I want to get the value, in pixels, of the current scroll position. When I run the below function it returns the value zero. How can I do this?

<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="js/jquery.mousewheel.min.js"></script>
<script type="text/javascript">
    $(function (){
        $('#Eframe').on("mousewheel", function() {
            alert(document.body.scrollDown)
        }
    })
</script>
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • You want to get the amount of pixels a user scrolled ? just the first time they scroll ? correct ? – Manse May 16 '12 at 09:39
  • 1
    This links will be usefull for you:- http://papermashup.com/jquery-page-scrolling/ http://stackoverflow.com/questions/4081064/how-to-get-the-num-of-pixels-a-user-has-scrolled-down-the-page http://stackoverflow.com/questions/8148310/jquery-if-scroll-is-a-certain-amount-of-pixels http://stackoverflow.com/questions/2021440/detect-distance-scrolled-from-top-jquery – Javascript Coder May 16 '12 at 09:43

3 Answers3

130

Since it appears you are using jQuery, here is a jQuery solution.

$(function() {
    $('#Eframe').on("mousewheel", function() {
        alert($(document).scrollTop());
    });
});

Not much to explain here. If you want, here is the jQuery documentation.

user2503552
  • 601
  • 2
  • 8
  • 14
  • 5
    This just gives me 0 the whole time – Pomster Jan 28 '14 at 13:08
  • 3
    @Pomster @r3wt You have to make sure you set the function to whatever document object is scrolling. So if the scroll is on some `
    ...`, the syntax would be `$("#foo").scrollTop()`.
    – Steven Mann Apr 20 '15 at 15:36
34

It's better to use $(window).scroll() rather than $('#Eframe').on("mousewheel")

$('#Eframe').on("mousewheel") will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.

$(window).scroll(function(){
    var scrollPos = $(document).scrollTop();
    console.log(scrollPos);
});

If #Eframe is an element with overflow:scroll on it and you want it's scroll position. I think this should work (I haven't tested it though).

$('#Eframe').scroll(function(){
    var scrollPos = $('#Eframe').scrollTop();
    console.log(scrollPos);
});
Daniel Tonon
  • 9,261
  • 5
  • 61
  • 64
12

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
Amos
  • 2,222
  • 1
  • 26
  • 42