183

I need to grab the height of the window and the scrolling offset in jQuery, but I haven't had any luck finding this in the jQuery docs or Google.

I'm 90% certain there's a way to access height and scrollTop for an element (presumably including the window), but I just can't find the specific reference.

T J
  • 42,762
  • 13
  • 83
  • 138
One Crayon
  • 19,119
  • 11
  • 33
  • 40

5 Answers5

301

From jQuery Docs:

const height = $(window).height();
const scrollTop = $(window).scrollTop();

http://api.jquery.com/scrollTop/
http://api.jquery.com/height/

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Pim Jager
  • 31,965
  • 17
  • 72
  • 98
  • 1
    Figures I just missed it in the docs; searched them, but their organization frankly makes no sense to me (still thinking in Mootools, I suppose). Thanks! – One Crayon Nov 19 '08 at 23:31
  • This doesn't work in any browser for jQuery 1.3.2 even though it was supposedly added in an earlier version. Either that or I have something wrong with my code here – Philluminati Jun 04 '10 at 08:48
  • 11
    $(window).height() gives the height viewport and not the scroll height. $(document).height() gives the real scroll height, as Aidamina suggested. – Jonathan Mar 07 '11 at 01:51
  • I'm often amazed at how many upvotes simple things like this attract, but since I've looked this up twice this week already, have another +1 – Neil May 17 '16 at 12:52
41

from http://api.jquery.com/height/ (Note: The difference between the use for the window and the document object)

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

from http://api.jquery.com/scrollTop/

$(window).scrollTop() // return the number of pixels scrolled vertically
Aidamina
  • 1,894
  • 20
  • 14
12

Pure JS

window.innerHeight
window.scrollY

is more than 10x faster than jquery (and code has similar size):

enter image description here

Here you can perform test on your machine: https://jsperf.com/window-height-width

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
6
$(window).height()

$(window).width()

There is also a plugin to jquery to determine element location and offsets

http://plugins.jquery.com/project/dimensions

scrolling offset = offsetHeight property of an element

Omar
  • 32,302
  • 9
  • 69
  • 112
Joey V.
  • 1,866
  • 1
  • 22
  • 18
  • 1
    Thanks, Joseph. It's not exactly what I was looking for as I was trying to avoid using another plugin, but you got me searching in the right direction. In the end, it turns out what I really needed was '$(window).scrollTop()' to figure out how much of the page has scrolled past the viewport to adjust elements accordingly. – DA. Oct 14 '09 at 16:26
1

If you need to scroll to a point of an element. You can use Jquery function to scroll it up/down.

$('html, body').animate({
                scrollTop: $("#div1").offset().top
            }, 'slow');
dush88c
  • 1,918
  • 1
  • 27
  • 34