Explain Codes LogoExplain Codes Logo

Is it possible to animate scrollTop with jQuery?

javascript
animation
scrolling
jquery
Alex KataevbyAlex Kataev·Jan 27, 2025
⚡TLDR

Yes, we can do that using jQuery's animate() method. Here's an example where we scroll to a specific HTML element:

$('html, body').animate({ scrollTop: $('#yourElement').offset().top }, 'slow');

In the above code, we're saying: "Hey jQuery, please animate a scroll to our element and do it slowly.

Deeper dive into scrolling animation

Control the pace: Tuning animation duration

Duration in animation works like a speedometer. The lower the duration, the faster the scroll. Here's a modification to control the pace:

// Just like your grandma driving, takes a full second (1000 ms) to scroll. $('html, body').animate({ scrollTop: 300 }, 1000);

Post-animation actions: Using promise and callback

Once the scrolling has ended—just like the ending credits after a movie—you might want to execute some additional actions. Here's where the callback function comes into play:

// It’s like, ‘after the ride, shout hurray!’ $('html, body').animate({ scrollTop: 300 }, 'slow', function() { console.log('Hurray! We have reached the point.'); });

If you’re a fan of promises (who isn't?), you can use them for more readable after-scroll operations:

// It’s like a well-behaved child. Once the job is done, then only it promises to do the next. $('html, body').animate({ scrollTop: 300 }, 'slow').promise().done(function() { console.log('We did promise, right? Scroll over!'); });

Efficient and compatible scroll operations

To ensure wefuel efficiency and consider cross-browser compatibility, animate a single element:

// Here we play smart choosing the fuel-efficient car for a ride var $scrollElement = $('html, body').scrollTop() ? $('html, body') : $('body'); $scrollElement.animate({ scrollTop: 300 }, 'slow');

Allow user control during animation

Allow users to interrupt the scrolling animation if they want:

// In case user gets impatient and scrolls manually, we stop the animation $('html').add('body').on('scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove', function(){ $(this).stop(); });

Spice up the move with easing

Want to make your scrolling feel more natural? Add easing to your animation:

// Let’s swing and add rhythm to our scrolling dance! $('html, body').animate({ scrollTop: 300 }, 'slow', 'swing');

Handling edge cases

A good programmer always thinks about edge cases, like when an element is invisible:

// Just to ensure we don’t run after what doesn’t exist if ($yourElement.is(':visible')) { $('html, body').animate({ scrollTop: $yourElement.offset().top }, 'slow'); } // While animating, make sure there is no redundancy $('html, not(body)').animate({ scrollTop: 300 }, 'slow');

Immediate scroll—no waiting around

Times when you need an instant scroll without animation, scrollTop can be set directly:

// Whoosh! We arrive instantly. $(window).scrollTop(300);