How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Scroll to an Element Using jQuery
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Scroll to an Element Using jQuery
Web Development

How to Scroll to an Element Using jQuery

how7o
By how7o
Last updated: May 23, 2026
4 Min Read
Scroll to an element on a web page with jQuery
SHARE

To scroll to an element using jQuery, animate the scrollTop of html and body to the target element’s offset: $('html, body').animate({ scrollTop: $('#target').offset().top }, 500). The 500 is the animation duration in milliseconds.

Contents
  • The jQuery one-liner
  • Both html and body — why the dual selector
  • With a fixed-header offset
  • Native equivalent — scrollIntoView
  • Scroll a container, not the page
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 with jQuery 3.7. Originally published 2023-01-23, rewritten and updated 2026-05-17.

The jQuery one-liner

$('button').on('click', function () {
    $('html, body').animate(
        { scrollTop: $('#element-id').offset().top },
        500
    );
});

.offset().top returns the element’s y-position relative to the document. .animate({ scrollTop: y }, duration) animates the scroll-bar position to that y-coordinate over the given duration.

Scroll to element — jQuery animate, native scrollIntoView, scroll-margin-top for sticky-header offset

Both html and body — why the dual selector

// Same effect, alternative form
$([document.documentElement, document.body]).animate(
    { scrollTop: $('#element-id').offset().top },
    500
);

Different browsers historically scrolled the document via different elements. Targeting both html (documentElement) and body covers every browser without sniffing. Modern browsers have converged but the dual selector is cheap insurance.

With a fixed-header offset

const headerHeight = $('#site-header').outerHeight();

$('html, body').animate(
    { scrollTop: $('#element-id').offset().top - headerHeight - 16 },
    500
);

Subtracting the header height (plus a little breathing room) prevents the target from disappearing under a sticky navigation bar. Read the header height with outerHeight() instead of hardcoding it — it survives theme changes and responsive breakpoints.

Native equivalent — scrollIntoView

document.getElementById('element-id').scrollIntoView({
    behavior: 'smooth',
    block:    'start',
});

Native, supported in every modern browser, hardware-accelerated, no library needed. For sticky-header offsets, set this in CSS on the target:

#element-id {
    scroll-margin-top: 80px;   /* matches your sticky header height */
}

The browser then scrolls so the target sits 80 px from the top — clean separation of behavior and presentation.

Scroll a container, not the page

// Scroll a scrollable div, not the window
const $container = $('#scroll-container');
const $target    = $('#item-42');

$container.animate({
    scrollTop: $target.offset().top - $container.offset().top + $container.scrollTop(),
}, 500);

For a scrollable container instead of the page, animate that container’s scrollTop. The arithmetic accounts for the container’s own position on the page and its current scroll offset.

Frequently asked questions

Why animate both html and body?

Different browsers historically tracked scroll on different roots: Chrome/Safari read the scroll position from body, Firefox/Edge from html. Targeting both ensures the animation works everywhere. Modern browsers have converged (it’s document.scrollingElement on all of them now), but the dual selector keeps backward compatibility cheap.

Should I use jQuery or native scrollIntoView?

For new code, native: document.getElementById('target').scrollIntoView({ behavior: 'smooth', block: 'start' }). One line, no library, hardware-accelerated. Use jQuery when you’re already in a jQuery codebase or need control over the easing function and duration that scrollIntoView doesn’t give you.

How do I add a fixed-header offset so the target isn’t hidden under a sticky nav?

Subtract the header’s height from the target’s offset: $('html, body').animate({ scrollTop: $('#target').offset().top - 80 }, 500). Hardcoding 80 is brittle; read the header’s actual height with $('#header').outerHeight() instead. For native scrollIntoView, set scroll-margin-top in CSS on the target instead — cleanest solution.

What’s the difference between scrollTop and scrollTo?

scrollTop is the y-position of the scroll bar (read/write). window.scrollTo({ top, behavior }) is the native API that animates if you ask for behavior: 'smooth'. jQuery’s .animate({ scrollTop: y }) writes to the property over time, simulating smooth scroll. Native scrollTo with 'smooth' is now widely supported and uses the browser’s own implementation.

Related guides

  • How to Check if an Element Is Visible or Hidden with jQuery
  • How to Get the Index in a jQuery .each() Loop
  • How to Check if a Checkbox Is Checked with jQuery

References

jQuery .animate(): api.jquery.com/animate. MDN Element.scrollIntoView(): developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView. CSS scroll-margin-top: developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin-top.

TAGGED:domJavaScriptjQuery

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Run a Node.js application from a Windows .bat file How to Run a Node.js Application from a Windows .bat File
Next Article Select all text in a contenteditable div on click How to Select All Text in a Contenteditable Div on Click
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026

You Might Also Like

MySQL combine columns into string — CONCAT and CONCAT_WS
Web Development

How to Combine Multiple Columns into One String in MySQL

6 Min Read
Laravel Eloquent records today — Carbon today helper and whereDate illustration
Web Development

How to Get Records Created Today in Laravel

6 Min Read
Laravel call controller from another controller — app() and constructor injection patterns
Web Development

How to Call a Controller Method from Another Controller in Laravel

8 Min Read
DataTables default sort order — order: [[1, 'desc']] config
Web Development

How to Change the Default Sort Order in DataTables

4 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?