Last Updated: October 11, 2021
·
11.79K
· leemachin

smoothly scroll to an element in javascript

Why use a massive plugin, when one line of code will cover most trivial use cases?

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

Want it in a plugin still, so you can re-use it?

jQuery.fn.smoothScroll = function() {
  $('html, body').animate({'scrollTop': this.offset().top}, 'slow', 'swing');
};

Works in Chrome, Opera, Safari, IE8, and Firefox.

You can grab it as a ready made plugin here: https://github.com/leemachin/scroll

1 Response
Add your response

Just for the record, I developed a library-agnostic script to do it (if you don't want be forced to use jQuery, which may be in your wish if you don't want to use something massive) : http://cl.ly/MEqo

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside