Explain Codes LogoExplain Codes Logo

Scroll to an element with jQuery

javascript
scrolling
animation
smooth-scrolling
Alex KataevbyAlex Kataev·Nov 6, 2024
TLDR

Smoothly scroll to any element on your website with the power of jQuery's animate() method combined with scrollTop. To implement this, grab the following snippet:

// Get to the top, babies! 🚀 $('html, body').animate({ scrollTop: $('#id').offset().top }, 'slow');

Replace #id with your targeted element's ID, and enjoy a bon voyage across your website!

The "how" behind it all

Smooth scrolling with scrollTop

scrollTop is a powerful property that gauges the distance from an element's top to its scrollable area's top. When you pair this with animate(), it creates a smooth scroll through your site that even Miss Universe would envy!

click your way to glory

Often, you'll want the smooth scrolling to occur after a certain event e.g., a button click. jQuery's click event method makes this a cakewalk:

// "Clicking is believing", isn't it? $('#buttonID').click(function() { $('html, body').animate({ scrollTop: $('#target').offset().top }, 2000); });

Upon clicking #buttonID, the website will lovingly whisk the user over to #target within 2000 milliseconds. This duration is, of course, customizable!

Scrollitecting for all

Every browser is its own Picasso - ensuring a universally smooth scrolling experience is vital. Combining html, body in your jQuery selector is our paintbrush:

// Making an all-browser compatible masterpiece 👩‍🎨 $('html, body').animate({ scrollTop: $('#id').offset().top }, 'slow');

Testing across different browsers will keep Picasso and Da Vinci from wrestling over your website's stylings!

Sharpening your scroll-saw

jQuery-free scrolling

If 'native' is your jam, cheer up! JavaScript's own scrollIntoView() offers a jQuery-free route to smooth scrolling:

// No jQuery? No problem! NativeScroll™ to the rescue! document.querySelector('#id').scrollIntoView({ behavior: 'smooth' });

The flexi-scrolls with plugins

With the scrollTo jQuery plugin, you can enjoy advanced features to aid you in your smooth scrolling quest. From customizable easing and duration to after-scroll callbacks, this plugin has it all:

// "Rolling down the website, flexing all the way" 🎶 $.scrollTo('#id', 1000, { easing: 'swing', onAfter: function() { console.log('Mission scroll-possible accomplished!'); } });

Hashing out instant navigation

Detect URL hashes to auto-scroll to corresponding page sections, adding a magic carpet ride through deep linking:

// User: "Take me there!" // Website: "Your wish is my URL command!" if (window.location.hash) { var hash = window.location.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 'slow'); }

Legitimate concerns

Beware dynamic content

For pages with dynamic content (especially loaded asynchronously), be ready to wrestle some changes:

$(window).on('load', function() { // Now we scroll! });

Let's go on a scroll-stroll

Chain .animate() calls to create stunning sequences for multi-target scrolling:

$('#startJourney').click(function() { // Stroll, stroll, baby! 🚶‍♀️🚶‍♂️ $('html, body').animate({ scrollTop: $('#part1').offset().top }, 1000) .animate({ scrollTop: $('#part2').offset().top }, 1000); });

Scroll to remember

Consider updating browser history for supporting bookmarks and back-button navigation. It's all about making the journey memorable!

window.history.pushState(null, null, '#target');