jQuery scrollTop() Method

You are Here:

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-posOptionalSpecifies the vertical scrollbar position in pixels.

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>

Reminder

Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in jQuery.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author