How to Animate Page Scroll with jQuery
Animating the scroll position of an entire web page using jQuery
allows you to create smooth transitions to specific sections, page
anchors, or back to the top. This guide demonstrates how to use the
jQuery .animate() method to control the document's vertical
scroll position, explains why targeting both html and
body ensures cross-browser compatibility, and covers
practical examples for buttons and target elements.
The Basic Syntax
To animate the scroll position of the entire page, select both the
html and body elements and animate the
scrollTop property:
$("html, body").animate({ scrollTop: 0 }, 1000);Targeting both html and body is necessary
for full cross-browser compatibility, as different browsers historically
assign the document's scroll position to either the
<html> or <body> element.
Scrolling to a Specific Element
To scroll to a specific section on the page rather than a fixed pixel
value, use the .offset().top method to dynamically
calculate the element's position relative to the top of the
document:
var targetOffset = $("#target-section").offset().top;
$("html, body").animate({
scrollTop: targetOffset
}, 800);Implementing on Click Events
To trigger the smooth scroll when a user clicks a navigation link or
button, attach a click event listener and prevent the browser's default
jump behavior using event.preventDefault():
$('a[href^="#"]').on('click', function(event) {
event.preventDefault();
var target = $(this.getAttribute('href'));
if (target.length) {
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 1000);
}
});Using the .stop() method immediately before
.animate() cancels any ongoing animations on the elements,
preventing animations from queuing up if the user clicks multiple links
rapidly.
Customization Options
The .animate() method accepts additional parameters to
control the behavior of the scroll:
- Duration: Define the animation length in
milliseconds (e.g.,
1000for 1 second) or use strings like'slow'(600ms) or'fast'(200ms). - Easing: Determine the speed curve of the animation.
Standard jQuery includes
'swing'(default) and'linear'. - Callback: Execute a function once the animation finishes.
$("html, body").animate(
{ scrollTop: 0 },
1200,
"swing",
function() {
console.log("Scroll animation completed.");
}
);