How do I determine height and scrolling position of window in jQuery?

JavascriptJquery

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

From jQuery Docs:

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

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

$(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

Solution 5 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOne CrayonView Question on Stackoverflow
Solution 1 - JavascriptPim JagerView Answer on Stackoverflow
Solution 2 - JavascriptAidaminaView Answer on Stackoverflow
Solution 3 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 4 - JavascriptJoey V.View Answer on Stackoverflow
Solution 5 - Javascriptdush88cView Answer on Stackoverflow