Skip to content

Instantly share code, notes, and snippets.

@A1rPun
Forked from pascaldevink/scrollspy.js
Last active November 16, 2015 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A1rPun/89c8c8ce36f4cd0b5583 to your computer and use it in GitHub Desktop.
Save A1rPun/89c8c8ce36f4cd0b5583 to your computer and use it in GitHub Desktop.
/*
Copyright (C) 2021 Pascal de Vink (Tweakers.net)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
var ScrollSpy = (function () {
var elements = [],
lastVisibleIndex = -1,
fn,
initialized = false;
function init() {
if (document.addEventListener) {
document.addEventListener("touchmove", handleScroll, false);
document.addEventListener("scroll", handleScroll, false);
} else if (window.attachEvent) {
window.attachEvent("onscroll", handleScroll);
} else {
window.onscroll = handleScroll;
}
initialized = true;
}
function handleScroll() {
var i = elements.length,
currentViewPosition = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
for (; i--;) {
var el = elements[i],
pos = getPositionOfElement(el.target);
if ((currentViewPosition - el.target.clientHeight) < pos && pos < currentViewPosition) { break; }
}
if (i !== lastVisibleIndex) {
if (fn) {
~lastVisibleIndex && fn(elements[lastVisibleIndex].self, false);
~i && fn(elements[i].self, true);
}
lastVisibleIndex = i;
}
}
function getPositionOfElement(domElement) {
var pos = 0;
while (domElement != null) {
pos += domElement.offsetTop;
domElement = domElement.offsetParent;
}
return pos;
}
return function (parentElement, convertFunction) {
!initialized && init();
fn = convertFunction;
var query = parentElement.querySelectorAll('[href^="#"]');
for (var i = 0, l = query.length; i < l; i++) {
var el = query[i];
elements.push({
self: el,
target: document.querySelector(el.getAttribute('href'))
});
}
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment