Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

.scrollTop() Explaination

Hi, On the jQuery website there isn't very useful documentation on .scrollTop(), I was wondering if anyone could explain how I could use it? I'm kind of confused :/

1 Answer

Hi tate,

The scrollTop() method in jQuery is used to get or set the vertical position of the scroll bar in an element. The number it returns is an integer value that represents the number of pixels that the scroll bar has moved from the top of the screen. At the top of the element, the value is 0. The very bottom of the element's value is the value of the height of that element.

For example, if we use the body of the document as the element, you can scroll to the top of the page by passing in the 0 value to scrollTop

$('body').scrollTop(0);

And you can scroll to the bottom of the page by passing in the integer value of the body's height. You can easily get this by calling the height() method in jQuery, which returns the integer value of the height of an element

$('body').scrollTop($('body').height());

These are all instantaneous jumps to the position in the element. There is an article on CSS tricks about smooth scrolling that uses scrollTop to achieve a nice scrolling effect with anchor links: https://css-tricks.com/snippets/jquery/smooth-scrolling/