0

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 document.body.scrollTop.

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) {
      showAndHideNav("hide");
      return;
    }
    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 scrollTop with pageYOffset, which identifies the right locations but doesn't scroll to those locations.

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

Thanks for your help!

dedaumiersmith
  • 337
  • 4
  • 14

1 Answers1

3

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);
jedifans
  • 2,287
  • 1
  • 13
  • 9