jQuery scrollTop() Method

Last Updated:

jQuery scrollTop() Method

The jQuery scrollTop() method is used for the following 2 purpose

  1. To get the current vertical position of the scroll bar for the first element in the set of matched elements.
  2. To set the current vertical position of the scroll bar for each of the set of matched elements.

Get Vertical Position

In the following example, we will get the vertical position of a div container.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> div{ border: 1px solid black; line-height: 2; width: 120px; height: 100px; overflow-y: scroll; } </style> </head> <body> <h1>jQuery scrollTop() Method</h1> <div> Here is some dummy text to make the div scrollable. Please don't forget to scroll up and down. </div> <p>scroll left is at = <span id="point">0</span>px</p> <script> $(document).ready(function(){ var count = 0; $("div").scroll(function(){ count += 1; $("#point").text($("div").scrollTop()); }); }); </script> </body> </html>

Syntax

$(selector).scrollTop(y-pos);

Parameter Values

ValueTypeExplanation
y-pos Optional Specifies the vertical scrollbar position in pixels.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
scrollTop()YesYesYesYesYesYesYesYesYesYesYesYesYes

Set Vertical Position

In the following example, we will set the vertical position of a div container.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> div{ border: 1px solid black; line-height: 2; margin-bottom: 10px; width: 120px; height: 100px; overflow-y: scroll; } </style> </head> <body> <h1>jQuery scrollTop() Method</h1> <div> Here is some dummy text to make the div scrollable. Please don't forget to scroll up and down. </div> <button>Move y-pos to litte</button> <script> $(document).ready(function(){ $("button").click(function(){ var myPixel = $("div").scrollTop() + 40; $("div").scrollTop(myPixel); }); }); </script> </body> </html>

Share this Page

Meet the Author