Explain Codes LogoExplain Codes Logo

How to scroll to specific item using jQuery?

javascript
scrolling
jquery
javascript-alternatives
Anton ShumikhinbyAnton Shumikhin·Jan 25, 2025
TLDR

To instantaneously scroll to an element, you should:

$('html, body').scrollTop($('#element-id').offset().top);

Just ensure that #element-id is replaced with the ID of your desired element for a quick jump to that item on the page.

Understanding the main components

The mechanics of scrolling in jQuery revolve around three core elements:

  • .scrollTop(): This method sets or fetches the vertical scrollbar position for the selected items.
  • .offset(): It helps to calculate the position of an item relative to the document.
  • .animate(): This method performs a custom animation on a series of CSS properties.

Scroll within a container

Often, the challenge is making sure elements are positioned correctly in a container with its own scrollbar. To achieve this:

let container = $('#container-id'), scrollTo = $('#element-id'); container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() });

Remember, #container-id is the scrollable item that contains #element-id.

Cross-browser compatibility and quirks

When it comes to web development, cross-browser compatibility is a key concern. For your smooth scrolling implementation:

  • Use both html and body concurrently in your jQuery selector for universal adaptability.
  • You can further customize the animate() speed parameter to modify your scroll speed - for instance, try 1500ms for a leisurely scroll.

Plain old JavaScript alternatives

If you're allergic to jQuery or it isn't an option, worry not, pure JavaScript alternatives are here:

  • window.scrollTo(): A JavaScript method for precise scrolling to specific coordinates.
  • scrollIntoView(): A method that scrolls the page to bring the desired element in the view within its container.

Here is a small demo:

document.querySelector('#element-id').scrollIntoView({ behavior: 'smooth' });

Practical examples to sink your teeth into

Some interactive examples to further solidify understanding:

  • Event-based dynamic scrolling: Play around with linking your smooth-scroll feature to clickable items like buttons or menu links.
  • Scroll position restoration: Take a stab at storing the last scroll position before a user leaves and then reviving it when the user returns.
  • Visibility verification: Implment a mechanism that checks if an element is already in the viewport before triggering a scroll.

Common tripping points

  • Element visibility: Ensure your element is not tucked away in a corner or hidden in an undisplayed branch of your DOM.
  • Selector accuracy: jQuery is highly sensitive to selectors; a small typo or incorrect target can crash your operation.