Explain Codes LogoExplain Codes Logo

Scroll / Jump to id without jQuery

javascript
performance
responsive-design
accessibility
Alex KataevbyAlex Kataev·Nov 17, 2024
TLDR

Easily navigate to any page section using JavaScript's scrollIntoView(). Apply it to a specified element's id like so:

document.querySelector('#yourElementId').scrollIntoView({ behavior: 'smooth' });

The querySelector method fetches the selected element, while scrollIntoView() ensures instant scrolling to that item. With an additive feature of behavior: 'smooth' enhancing the overall user experience with a smooth slide to the target element.

A step back: The scrollTop and jQuery myth

Initially, it might seem like a simpler task to handle scrolling using jQuery's scrollTop or the like, but we're not striving for simple, we're striving for efficient. scrollIntoView() works wonders for replacing heavy jQuery libraries, therefore, improving your JavaScript's performance and ensuring a fast and smooth experience particularly on mobile devices.

Event-based scrolling and URL changes

You can attach scrollIntoView() to onclick events. This creates a pathway for users to navigate around your site without disturbing the URL state and without the need for a page refresh, resulting in a smoother and more interactive user experience.

Personalizing with scrollIntoView

For a more personalized scrolling experience, you can add an options object to the scrollIntoView() method. This object allows settings like block and inline, which determine the scrollbar arrangements after the scroll:

element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });

This is equivalent to asking the scrollbar to go inline skating on a smooth road and stop at the nearest block.

Selecting elements like an artist: beyond getElementById

Where document.getElementById('id') streamlines the precision, querySelector licenses a more modern and flexible approach where you can select elements using any CSS selector. This means you can target class, id, data attributes, and more!

document.querySelector('.yourElementClass').scrollIntoView({ behavior: 'smooth' });

Whoever said artists can't code?

Compatibility: The cross-browser Scrolling

Before coding a swinging interactive scroll, it's crucial to ensure the scrollIntoView() method's browser compatibility. For browsers that don't handle the method as deftly, consider providing a fallback to let it degrade gracefully.

Enhancing Accessibility: No Scrolling left behind

While implementing custom scrolling logics, always be aware of accessibility. Ensure that key navigation controls like "Skip to content" are keyboard-accessible and do not interfere with assistive technologies. Furthermore, remember to preserve users' scroll positions when navigating between sections to provide enhanced accessibility to differently-abled users.

Performance: The need for speed

Ensure optimal performance when dealing with scrolling, particularly for mobile devices, which crave efficiency like their life depends on it(too dramatic?). Avoid unnecessary complex animations; instead, consider offloading heavy animations using CSS transitions. This shifts some work to the GPU, resulting in a smoother scrolling experience.

No href? No problem!

If your project's guidelines prohibit href in anchor tags, you can work with a function that handles your scrolling logic. Here's a quirky solution that stores 'IDs' in data attributes and uses event listeners to trigger the scroll:

<button data-scrollto="section1">Go to Section 1</button>
document.querySelectorAll('[data-scrollto]').forEach(button => { button.addEventListener('click', function() { const targetId = this.getAttribute('data-scrollto'); // it's like saying "Hey JavaScript! Remember that stored ID? Yeah, scroll to it" const targetElement = document.querySelector('#' + targetId); targetElement.scrollIntoView({ behavior: 'smooth' }); }); });

This way, you maintain a semantic HTML, ensuring an engaging and user-friendly page.