dedaumiersmith dedaumiersmith - 1 year ago 101
Javascript Question

JavaScript only smooth scrolling across browsers

I have a smooth-scrolling function that works fine in Chrome and Safari, but won't play ball in Firefox, because it's calling on


function smoothScroll(body, destination, duration) {
duration = (typeof duration != "undefined")
? duration
: 500;
if (duration <= 0) return;
var difference = destination - body.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function() {
body.scrollTop = body.scrollTop + perTick;
if (body.scrollTop === destination) {
smoothScroll(body, destination, duration - 10);
}, 10);

function findDestination(element) {
var value = element.getAttribute("value"),
destination = document.getElementById(value).offsetTop;
return destination;

smoothScroll(document.body, findDestination(element));

I tried replacing
, which identifies the right locations but doesn't scroll to those locations.

Can anyone recommend a more browser-friendly alternative to
that will enable smooth scrolling across browsers?

Thanks for your help!

Answer Source

Instead of using body.scrollTop directly, try the following helper function, used like so: getScrollTop(window)

function getScrollTop(scrollable) {
    return scrollable.scrollTop || document.body.scrollTop || document.documentElement.scrollTop;

To actually scroll to the target, try this cross browser method:

window.scrollTo(0, getScrollTop(window) + perTick);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download