Skip to content

Instantly share code, notes, and snippets.

@hyamamoto
Created September 14, 2016 02:40
Show Gist options
  • Save hyamamoto/392afde08805a666b8d08dfe7ae64459 to your computer and use it in GitHub Desktop.
Save hyamamoto/392afde08805a666b8d08dfe7ae64459 to your computer and use it in GitHub Desktop.
Enable smooth scroll jumping inside a web page to any given element, position or anchor(id). Written in plain JavaScript without jQuery. (tested on Chrome > 21, Firefox > 28, IE >= 8) https://jsfiddle.net/6xfd9dr8/
var scroll = {
iterr: 30, // miliseconds
tm: null,
reset_timer: function () { // reset
if (this.tm) {
clearTimeout(this.tm);
this.tm = null;
}
this.iterr = 30;
},
realtop_of: function (el) {
var elm = el;
var realTop = 0;
do {
realTop += elm.offsetTop;
elm = elm.offsetParent;
} while (elm);
return realTop;
},
pagescroll: function () {
var yOff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
return yOff;
},
go2top: function () {
return scroll.go2elem(document.body);
},
go2id: function (id) {
var targetEl = document.getElementById(id);
return scroll.go2elem(targetEl);
},
go2elem: function (targetEl) {
var eOff = targetEl.offsetTop;
var tOff = this.realtop_of(targetEl.parentNode);
return scroll.go2pos(eOff, tOff);
},
go2pos: function (eOff, tOff) {
// scroll to tha element with the given id.
// eOff : beginning point
// tOff : terminus point
this.reset_timer();
var pOff, scrVal, pos, dir, step;
pOff = this.pagescroll();
if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;
scrVal = eOff - pOff; // scroll amount
if (scrVal > tOff) {
pos = (eOff - tOff - pOff);
dir = 1;
}
if (scrVal < tOff) {
pos = (pOff + tOff) - eOff;
dir = -1;
}
if (scrVal !== tOff) {
step = ~~((pos / 4) + 1) * dir;
this.iterr = (this.iterr > 1) ? this.iterr - 1: 0;
window.scrollBy(0, step);
this.tm = window.setTimeout(function () {
scroll.go2pos(eOff, tOff);
}, this.iterr);
}
if (scrVal === tOff) {
this.reset_timer();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment