mediawiki-skins-Citizen/resources/scripts/toc.js

60 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-08-15 17:40:13 +00:00
/*
* Citizen - ToC JS
* https://starcitizen.tools
*
* Smooth scroll fallback and Scrollspy
*/
const SmoothScroll = () => {
2019-08-19 04:24:40 +00:00
if (!'scrollBehavior' in document.documentElement.style) {
const navLinks = document.querySelectorAll('#toc a');
2019-08-15 17:40:13 +00:00
2019-08-19 04:24:40 +00:00
for (let n in navLinks) {
if (navLinks.hasOwnProperty(n)) {
navLinks[n].addEventListener('click', e => {
e.preventDefault();
document.querySelector(navLinks[n].hash)
.scrollIntoView({
behavior: "smooth"
});
});
}
}
2019-08-15 17:40:13 +00:00
}
}
const ScrollSpy = () => {
2019-08-19 04:24:40 +00:00
const sections = document.querySelectorAll('.mw-headline');
2019-08-15 17:40:13 +00:00
2019-08-19 04:24:40 +00:00
window.onscroll = () => {
const scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
2019-08-15 17:40:13 +00:00
2019-08-19 04:24:40 +00:00
for (let s in sections)
if (sections.hasOwnProperty(s) && sections[s].offsetTop <= scrollPos) {
const id = mw.util.escapeIdForAttribute(sections[s].id);
document.querySelector('.active').classList.remove('active');
document.querySelector(`a[href*="${ id }"]`).parentNode.classList.add('active');
}
}
2019-08-15 17:40:13 +00:00
}
2019-08-19 04:24:40 +00:00
const CheckToC = () => {
2019-08-19 05:30:24 +00:00
if (document.getElementById("toc")) {
2019-08-19 04:24:40 +00:00
SmoothScroll();
ScrollSpy();
}
}
2019-08-19 05:30:24 +00:00
if (document.readyState !== 'loading') {
CheckToC();
} else if (document.addEventListener) {
// All modern browsers to register DOMContentLoaded
document.addEventListener('DOMContentLoaded', CheckToC);
} else {
// Old IE browsers
document.attachEvent('onreadystatechange', function() {
if (document.readyState === 'complete') {
CheckToC();
}
});
2019-08-19 04:24:40 +00:00
}