How To Use The jQuery scrollTop() Method

jquery scrolltopThe jQuery scrollTop() method allows you to find the scroll position in a scrolling block of text, and it also allows you to set the position.  In this post, we’ll show you how to do both of those things.

It’s well worth your while to know jQuery and JavaScript if you’re interested in web development  —  either as a career, or for your own use.  And there are many first-rate online classes covering all phases of web development, from design through programming.  Why not check them out today?

jQuery And JavaScript

What’s jQuery?  It’s a very useful library of JavaScript code that you can use to perform a variety of tasks, typically in the user’s browser window (rather than on the server).

It’s a single, open-source JavaScript file.  you can download it and use a local copy, or link to one of the publicly-hosted jQuery sites, like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

The code to use a jQuery command typically looks something like this:

$("select_something").do_something(optional_args_or_function);

The “select_something” part selects one or more page elements (by type, ID, etc.), the do_something part is one of several jQuery methods, and if the method includes a function, the function can contain one or more jQuery or JavaScript methods.

Much of the time, it’s a good idea to make sure that the page is fully loaded before running the jQuery code, so we’ll do that by placing it within the function part of the ready() method, which checks to see if the page is ready:

$(document).ready(function(){jq_stuff_goes_here});

What scrollTop() Does

The scrollTop() method is intended for use with page elements that scroll  —  whether they contain large blocks of text, large images, or other oversize content.  When you use it without any arguments, it returns the current position of the vertical scrollbar in pixels, counting down from the top (with the topmost position being 0 px).  Note that it does this only for the first element that matches the selection criteria  —  one of several good reasons to use IDs to identify page elements.

When you use scrollTop() with a numeric argument (it only takes numeric arguments), it will set the position of the vertical scrollbar, using the numeric argument as the number of pixels.  In this case, it sets the position for all elements that match the identifier  —  an even better reason to be specific about identifying the target elements.

(There’s a similar method, scrollLeft(), for returning and setting the horizontal scroll position.)

Returning The Scroll Position

When you use scrollTop() without an argument, it returns the current vertical scroll position.  Take a look at the following example to see how it works  —  you can copy the code, paste it into a text file, save it with the extension .HTM, and open it in a browser to see it in action:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#get_pos").click(function(){
    var scrol_pos = $("#small_div").scrollTop();
    $("#inst_text").html("<p><b><font face='Georgia'>Your current scroll position is:</font> 
<font color='#FF0000'>" + scrol_pos + "</font><font face='Georgia'> px.</font></b></p>" );
  });
});
</script>
</head>
<body>
<p id="inst_text">Did you just scroll?</p>
<div id="small_div" style="width: 375px; height: 150px; overflow: auto">
<p style="line-height: 300%">
<font face="Georgia"><font size="6">
Arma virumque cano, Troiae qui primus ab oris<br>
Italiam, fato profugus, Laviniaque venit<br>
litora, multum ille et terris iactatus et alto<br>
vi superum saevae memorem Iunonis ob iram;<br>
multa quoque et bello passus, dum conderet urbem,<br>
inferretque deos Latio, genus unde Latinum,<br>
Albanique patres, atque altae moenia Romae.</font><br>
</font></p>
</div><br>
<button id="get_pos">Where's my scroll?</button>
</body>
</html>

It displays a a block of large-type text (the opening of Virgil’s Aeneid, in case you’re wondering) in a scrolling window.  When you click on the button, the text “Did you just scroll?” is replaced with a message telling you the current scroll position in pixels.

Laying It Out

First, let’s take a quick look at the HTML code.  It includes the text (which under real-world conditions would probably be added to the page dynamically), set to a rather large font size and line height, simply because we want it to do a lot of scrolling. It also creates the <div> element (deliberately made too small, because we want it to scroll for this example) that holds the text, plus the button and the “Did you just scroll?” message.  We assigned easily-readable IDs to the <div>, the button, and the message paragraph for readability, as well as good programming style.

Reading The Scroll

Now let’s look at the jQuery code.  As described above, it’s all within the wavy brackets of the ready() method’s function():

  $("#get_pos").click(function(){
    var scrol_pos = $("#small_div").scrollTop();
    $("#inst_text").html("<p><b><font face='Georgia'>Your current scroll position is:</font> 
<font color='#FF0000'>" + scrol_pos + "</font><font face='Georgia'> px.</font></b></p>" );
  });

First, we respond to the user’s action  —  clicking the button (selected using the button’s ID – “#get_pos”).  Everything else goes on inside the click() method’s function.

Next, we set a variable to equal the scroll position returned by scrollTop(), and again, we select the element using its ID (“#small_div”)

Finally, we use the html() method to replace the “#inst_text” message with a new message giving the position of the vertical scrollbar.

Setting The Scrollbar Position

Now, consider what would happen if we replaced these lines:

    var scrol_pos = $("#small_div").scrollTop();
    $("#inst_text").html("<p><b><font face='Georgia'>Your current scroll position is:</font> 
<font color='#FF0000'>" + scrol_pos + "</font><font face='Georgia'> px.</font></b></p>" );

With this:

$("#small_div").scrollTop(250);

If you were to click the button now, the vertical scrollbar would go to a position 250 pixels below the top of the text; adding a numeric argument to scrollTop() sets the position of the scrollbar, rather than reading it.

Put It To Work

OK  — let’s do something useful with scrollTop():

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#set_pos").click(function(){
    var scrol_pos = $("#small_div").scrollTop();
    $("#small_div").scrollTop(scrol_pos + 150);
  });
});
</script>
</head>
<body>
<div id="small_div" style="width: 375px; height: 150px; overflow: auto">
<p style="line-height: 300%">
<font face="Georgia"><font size="6">
Arma ... Romae.</font><br>
</font></p>
</div><br>
<button id="set_pos">Down three lines.</button>
</body>
</html>

Now, when you click on the “Down three lines.” button, the scrollbar automatically moves to a point 150 pixels below the current position.

(We took out most of the Latin just to save space, but if you want to try the code out, you can paste it back in.)

What It Does

We replaced the old button with a new one (with the ID “set_pos”), and we took out a few things that we didn’t need.  We still set the variable “scrol_pos” to the scrollbar’s current position using scrollTop(), but we’ve replaced the line below it with a much simpler-looking line, which also uses scrollTop():

$("#small_div").scrollTop(scrol_pos + 150);

This line sets the scroll position to the current position plus 150 pixels.  So we’re using scrollTop() twice  —  once to read the current position, and once to set the new position.  All in all, it’s a pretty useful method!

JavaScript and jQuery are extraordinarily useful tools for web development; to find out more about what you can do with jQuery, JavaScript, and other web programming languages, take a look at some of the excellent online classes that are available.