44

jquery how to get the page's current screen top position?

If I scroll my mouse wheel to some part of the page, how do I get the page's current top position?

I want click one element in my page, then open a div which top is to current screen top.

So just put the current screen top position to:

$('#content').css('top','current position');

And

#content
{
position:absolute;
left:100px;
}
cj333
  • 2,547
  • 20
  • 67
  • 110

2 Answers2

73

Use this to get the page scroll position.

var screenTop = $(document).scrollTop();

$('#content').css('top', screenTop);
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
50
var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

numbers1311407
  • 33,686
  • 9
  • 90
  • 92
  • 3
    This will not give what OP is looking for. It will give the offset top of the html element which will be a negative value if we have scrolled the page. – ShankarSangoli Aug 11 '11 at 00:00
  • 4
    As noted in the edit, this is the negative of `$(document).scrollTop()`, which yes, is more appropriate in this case. But the html offset * -1 is effectively the same thing. – numbers1311407 Aug 11 '11 at 00:05
  • right. `$(document).scrollTop()`, not `$(window).scrollTop()` thanks both – cj333 Aug 11 '11 at 00:10
  • 1
    You are right, but `$(document).scrollTop()` gives what you want then why use `$('html').offset().top` and multiply by `-1`. – ShankarSangoli Aug 11 '11 at 00:12
  • 1
    @ShankarSangoli I acknowledged that your answer is more appropriate, which is why I edited mine. The answer should go to you, yes. Still, isn't it always better to learn 2 different ways of accomplishing a task, if you start out knowing 0? – numbers1311407 Aug 11 '11 at 00:14
  • 1
    Debugging in IE11: ?$(document).scrollTop() 593 ?$("html").scrollTop() 593 ?$("html").offset().top -0.44000244140625 593 was the right answer. Similar result in chrome, except the last one reported zero. – user2728841 Nov 07 '18 at 15:35