Explain Codes LogoExplain Codes Logo

Javascript to scroll long page to DIV

javascript
scrolling
smooth-scroll
javascript-scroll
Anton ShumikhinbyAnton Shumikhin·Jan 2, 2025
TLDR

Make your page jump to a specific section instantly:

document.querySelector('#targetDiv').scrollIntoView();

Or smooth it out for a gentler scroll:

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

Replace '#targetDiv' with your div's selector for a precise scroll action.

Handy adjustments

Customizing scroll offset

Want to jazz up your scroll by adding an offset? Use this:

const element = document.querySelector('#targetDiv'); const offset = 100; // Make it a diva, set the offset spotlight! const elementPosition = element.getBoundingClientRect().top; const offsetPosition = elementPosition + window.pageYOffset - offset; window.scrollTo({ top: offsetPosition, behavior: 'smooth' });

Scroll on event

For those "click me!" moments, link a button click to a scroll action:

document.getElementById('scrollButton').addEventListener('click', function() { document.querySelector('#targetDiv').scrollIntoView({ behavior: 'smooth' }); });

Don't forget to check if your div is ready for their moment before sending them on stage!

Tackling dynamic content

Loading content, no worries. Efficiently scroll to the dynamically loaded content:

// Your Broadway production load function function loadYourContent(callback) { // Your content loading logic callback(); } loadYourContent(function() { document.querySelector('#dynamicDiv').scrollIntoView({ behavior: 'smooth' }); });

Patience is a virtue. Await the load, then scroll.

Look under the hood

Exploring alternatives

When scrollIntoView() doesn't make the cut, go classic with HTML page anchors or relax with jQuery's animate:

<!-- Meet your anchor --> <a href="#targetDiv">Go to Target Div</a> <!-- Anchor's hangout --> <div id="targetDiv"></div>

And with jQuery:

$('a[href^="#"]').click(function() { var target = $(this.hash); if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1000); return false; // Override anchor's FOMO (Fear Of Missing Out) on default behaviour } });

Double checking browser compatibility

Be a good citizen, always check your solution's browser compatibility. Not all browsers are created equal.

Being accessible

Make friends with assistive technologies users. Control those scrolling urges and use ARIA roles for smoother user experience.