Smooth Scrolling

JavaScript

You might think you need a library to make scrolling to an element on your page smoothly. You'd be wrong.

This solution provided below will work with all major browsers, so you should be good to go. Further it uses the easeOutCubic() easing function, however, you can use any you like. A few are here.

function scrollTo(target) { var origin = window.pageYOffset var timeOrigin = Date.now() var change = target.offsetTop - window.pageYOffset - 10 // -10 means 10 pixel above the target var durration = 1200 // in milliseconds var pageHeight = window.innerHeight + window.pageYOffset ;(function update() { var now = Date.now() var progress = easeOutCubic(now - timeOrigin, origin, change, durration) // if still time && not reached the bottom if (timeOrigin + durration > now && (change < 0 || pageHeight < document.body.offsetHeight)) { requestAnimationFrame(update) window.scrollTo(window.scrollX, progress) } else window.scrollTo(window.scrollX, origin + change) }()) } // you may use any easing fuction you like function easeOutCubic(t, b, c, d) { t /= d t-- return c * (t * t * t + 1) + b }

Reference

No known

History Apr 01, 2017