Cover Image for jQuery scrollTop() method
137 views

jQuery scrollTop() method

The jQuery scrollTop() method is used to get or set the vertical scroll position of an element with a scrollable content. It works for both the window object and elements that have a scrollbar, such as <div> elements with the CSS overflow property set to “auto” or “scroll.”

The syntax for using the scrollTop() method is as follows:

To Get the Vertical Scroll Position:

$(selector).scrollTop();

To Set the Vertical Scroll Position:

$(selector).scrollTop(value);
  • selector: It is a string that specifies the elements to be selected.
  • value (optional): It is an integer representing the new vertical scroll position that you want to set for the element. If you omit this parameter, the scrollTop() method will act as a getter and return the current vertical scroll position.

Here’s an example of how you can use the scrollTop() method:

HTML:

<div style="height: 200px; overflow-y: scroll;">
  <p>This is some content inside the div.</p>
</div>

JavaScript:

// Get the current vertical scroll position of the div element
var scrollPosition = $('div').scrollTop();
console.log('Vertical Scroll Position: ' + scrollPosition);

// Set a new vertical scroll position for the div element
$('div').scrollTop(100);

In the above example, the scrollTop() method is used to get the current vertical scroll position of the <div> element with a scrollbar. The value will be the number of pixels that the content is currently scrolled from the top.

Then, the scrollTop() method is used again to set a new vertical scroll position of 100 pixels for the same <div> element. This will scroll the content inside the <div> to the specified position.

Keep in mind that the scrollTop() method will work only for elements with a scrollable content. If the element does not have a scrollbar or its content is not overflowing, the scrollTop() method will return 0, and setting a new value will have no effect.

The scrollTop() method is commonly used when you want to programmatically control the scroll position of elements, especially in cases where you have long content that requires scrolling or when implementing features like smooth scrolling animations.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS