Explain Codes LogoExplain Codes Logo

How do I get an element to scroll into view, using jQuery?

javascript
scrolling
jquery
animation
Nikita BarsukovbyNikita Barsukov·Nov 3, 2024
TLDR

Rapid-fire solution: Combine animate and scrollTop to scroll smoothly to a specific element:

$('html, body').animate({ scrollTop: $('#element').offset().top }, 'slow');

This scrolls smoothly to #element. Change 'slow' to adjust the scrolling speed.

In-depth answer: Advanced scrolling tricks and tips

Option 1: Precise positioning with viewport alignment

To land an element directly in view, employ scrollIntoView(). This method enables fine-tuned alignment, supported by all major browsers:

$('#element').get(0).scrollIntoView({ behavior: 'smooth', // enjoys long scrolls on the web page block: 'start', // top align because it has the best views inline: 'nearest' // snaps in line like a disciplined soldier });

The result? Precise alignment of our element within the viewport.

Option 2: Browser history incorporation

For browser history inclusion, elegantly modify the hash property of the location object:

location.hash = '#elementId'; // hash it out with the URL $('#elementId').get(0).scrollIntoView();

Now, the URL’s hash changes as you click a link. That way, the back and forward buttons in the browser can navigate properly.

Option 3: Ensure pixel perfect render

In situations requiring an element at a specific point, adjust the scrollTop and scrollLeft values accordingly:

let topPosition = $('#element').offset().top - 20; let leftPosition = $('#element').offset().left - 20; $('html, body').animate({ scrollTop: topPosition, scrollLeft: leftPosition }, 'slow');

We're now 20px to the top and to the left from our element, as simple as a breeze.

Scroll Wrangling: Diving Deeper

Factoring in variable content heights

Factor in dynamic content to skillfully manage negative offset values:

let offsetTop = $('#element').offset().top; $('html, body').animate({ scrollTop: offsetTop > 0 ? offsetTop - 20 : 0 // "I see no negativity in our scroll future." }, 'slow');

Advanced gameplay with plugins

Plugins like jQuery.scrollTo add extra functionality to your scrolling. More power to your scroll:

  • Control animation duration
  • Choose axis of scroll
  • Set extra padding for final scroll position
$('body').scrollTo('#element', 800, { offset: -20 }); // "Honey, where is my super scrollTop?"

One click, many scrolls

With multiple scrollable elements, make each image scroll to its enlarged version on click:

$('img.thumbnail').on('click', function() { const imageId = $(this).attr('id'); $('#' + imageId + '_full').get(0).scrollIntoView(); // "You've got mail... err... full view!" location.hash = '#' + imageId + '_full'; // "Let's hash this out!" });