Jitender
Jitender

Reputation: 7971

How do I get the browser scroll position in jQuery?

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>

Upvotes: 81

Views: 204170

Answers (3)

Amos
Amos

Reputation: 2630

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

Upvotes: 12

Daniel Tonon
Daniel Tonon

Reputation: 10412

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

Upvotes: 36

user672118
user672118

Reputation:

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.

Upvotes: 132

Related Questions