Set Vertical Scroll Position with jQuery
This guide explains how to set the vertical scroll position of a
webpage or any scrollable container using jQuery. You will learn how to
use the built-in .scrollTop() method to instantly jump to a
specific pixel offset, as well as how to combine it with the
.animate() method to create smooth scrolling effects.
The .scrollTop() Method
The primary jQuery method used to set the vertical scroll position is
.scrollTop(). When passed a numeric value (representing
pixels), it immediately scrolls the selected element to that exact
vertical position.
Basic Syntax
$(selector).scrollTop(value);selector: The scrollable container, such aswindow,document,'html, body', or a specificdivwith an overflow property.value: An integer representing the vertical position in pixels from the top.
Instant Scroll Examples
To instantly scroll the entire browser window to the very top:
$('html, body').scrollTop(0);To scroll a specific scrollable container (e.g., a div
with the ID #content) down by 300 pixels:
$('#content').scrollTop(300);Creating a Smooth Vertical Scroll
To avoid an abrupt jump and instead animate the scrolling movement,
use jQuery's .animate() method targeting the
scrollTop property.
$('html, body').animate({
scrollTop: 500
}, 600); // 600 represents the animation duration in millisecondsScrolling to a Specific Element
A common use case is scrolling vertically until a target element
enters view. You can achieve this by calculating the target element's
distance from the top of the document using
.offset().top:
var targetPosition = $('#target-section').offset().top;
$('html, body').animate({
scrollTop: targetPosition
}, 800);This approach allows you to build features like "Back to Top" buttons or smooth navigation menus that guide users to specific sections of a page.