Explain Codes LogoExplain Codes Logo

How do I scroll to an element using JavaScript?

javascript
scrolling
javascript-functions
web-development
Anton ShumikhinbyAnton ShumikhinΒ·Sep 4, 2024
⚑TLDR

To instantly jump to a specific location:

// "Houston, we have liftoff!" πŸš€ document.querySelector('#target').scrollIntoView();

For a leisurely smooth scroll:

// Like gliding on a zephyr, but with pixels document.querySelector('#target').scrollIntoView({ behavior: 'smooth' });

Replace '#target' with your element's CSS selector. For selector versatility, consider querySelector.

Scroll methods examined

Direct scroll sans flair

For instant scroll without animations:

// Transporter mode: Engage! πŸ–– location.href = '#target';

Ensure your element has an id of "target" for this.

Programmatically scrolling to the rescue

To manually brew the scroll position and pour the scroll:

// Yarrr, there be the treasure! πŸ΄β€β˜ οΈ const navigationalChart = document.getElementById('target'); const treasureLocation = navigationalChart.getBoundingClientRect().top + window.scrollY; window.scroll({ top: treasureLocation, behavior: 'smooth' });

This formula takes into account any vertical scroll offset the page may harbor.

Handling stubborn fixed elements

Have a fixed navigation bar ? Fear not:

// Hey, who put this giant header here? const navbarHeight = -60; const element = document.getElementById('target'); const y = element.getBoundingClientRect().top + window.scrollY + navbarHeight; window.scrollTo({ top: y, behavior: 'smooth' });

Dealing with WebKit browsers oddities

WebKit browsers may exhibit a scrolling quirk:

// Yeah, I don't understand why either, it's a WebKit thing πŸ€·β€β™‚οΈ if (document.body.scrollTop || document.documentElement.scrollTop) { location.href = "#"; setTimeout(() => { element.scrollIntoView(); }, 0); }

This two-stepper sets the scroll position to the top, then instantly scrolls to the target.

jQuery jazz

If jQuery is your mojo:

// Get over here, Scorpion-style! $('#target').animate({ scrollTop: $('#target').offset().top }, 1000);

This moves to the element via a 1-second animation.

Going the extra mile

Attaining absolute precision with scroll

To scroll to an element based on absolute page position:

// Archimedes would be proud of this kind of precise measurement const yPos = document.getElementById("myDiv").offsetTop; window.scrollTo({ top: yPos, behavior: 'smooth' });

Reusable scroll function, anyone?

A reusable scroll function can be quite the handy tool:

// Scroll in style, as many times as you want 🎩 function scrollToElement(selector, offset = 0) { const element = document.querySelector(selector); const y = element.getBoundingClientRect().top + window.scrollY + offset; window.scrollTo({top: y, behavior: 'smooth'}); } // Usage: scrollToElement('#target', -60);

Scrolls smoothly considering offset for fixed elements.