Explain Codes LogoExplain Codes Logo

How to scroll to an element inside a div?

javascript
scrolling
smooth-scroll
scrollintoview
Nikita BarsukovbyNikita Barsukov·Aug 21, 2024
TLDR

The fast and furious way to navigate to an element inside a div is to use the scrollIntoView() method:

// Use the Force, Luke! document.querySelector('#element').scrollIntoView({ behavior: 'smooth' });

Here, the #element will glide smoothly towards the center of the viewport.

Guiding tour of scrollIntoView

The scrollIntoView() method provides a one-stop solution to immediately transport an element into clear view. By adding { behavior: 'smooth' }, it's like riding on a hoverboard to your destination.

However, for more precision, you might need to operate on the scrollTop and offset properties directly:

// Declare variables, not war const scrollableContainer = document.querySelector('.scrollable-div'); const targetElement = document.querySelector('#target-element'); // Fly me to the offsetTop const topPosition = targetElement.offsetTop - scrollableContainer.offsetTop; // scrollTop to the rescue scrollableContainer.scrollTop = topPosition;

In this particular bit, the #target-element smoothly materializes into view within the .scrollable-div.

Scroll methods brew

Adjusting scrollTop to position element

In specific scenarios, such as dynamic elements or nested components, working directly with the scrollTop property can be handy:

// It's a bird, It’s a plane, It's..scrollToElement const myElement = document.getElementById('desiredElement'); const containerDiv = myElement.parentNode; const elementOffset = myElement.offsetTop; // Hop, skip, and scrollTop containerDiv.scrollTop = elementOffset;

This code will drag the scrollbar till the element is aligned at the top of the container.

Smooth as butter with CSS

For a smooth scroll across all site-wide elements, go full CSS with scroll-behavior: smooth;:

// Welcome to the smoother side .scrollable-div { scroll-behavior: smooth; }

With this, every scroll inside .scrollable-div will feel like gliding on ice, sans the chills.

Visibility first, scrolling next

Before scrolling, do check if the element is already in view. Here, a scrollIfNeeded function checks visibility before scrolling:

// Peek a boo, I scroll you function scrollIfNeeded(container, element) { const elementRect = element.getBoundingClientRect(); const containerRect = container.getBoundingClientRect(); // If the coast is not clear if (elementRect.top < containerRect.top || elementRect.bottom > containerRect.bottom) { element.scrollIntoView({ behavior: "smooth" }); } }

By avoiding unnecessary scrolls, you're making the web a better place.

Garment of scrollable container

Appearance matters, even for a scrollable container. Style it right with CSS properties including overflow, height, and position to appropriately set scrolling:

// Dressing the scrollable div, one property at a time .scrollable-div { overflow-y: auto; height: 300px; position: relative; }

These properties ensure the container is set for correct scrolling alignment.

Events leading to scrolling

User interaction often involves scrolling as a response to events such as clicks. Here's how to set that up:

// One small click for user, one smooth scroll for mankind document.querySelector('#scroll-button').addEventListener('click', () => { document.querySelector('#target-element').scrollIntoView({ behavior: 'smooth' }); });

Clicking the #scroll-button now results in smooth scrolling to the #target-element, making it a joyride.

Overcoming browser hurdles

The scrollIntoView method is a global citizen, but the { behavior: 'smooth' } option may face passport issues. Always refer caniuse.com for compatibility checks.

Utilize a polyfill or provide a fallback for the browsers that are too cool for the smooth option.

User experience: key to the kingdom

Scrolling actions should enhance user experience, not mar it. Don't go too fast or be choppy. Also, ensure consistency across devices.

Remember, a smooth scroll can guide users to key content without being bossy.