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

67 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-12-26 09:40:43 +00:00
if ( !( 'scrollBehavior' in document.documentElement.style ) ) {
const navLinks = document.querySelectorAll( '#toc a' ),
eventListener = e => {
e.preventDefault();
e.target.scrollIntoView( {
behavior: 'smooth'
} );
};
2019-12-25 23:24:31 +00:00
2019-12-26 09:40:43 +00:00
for ( let link in navLinks ) {
if ( Object.prototype.hasOwnProperty.call( navLinks, link ) ) {
navLinks[ link ].addEventListener( 'click', eventListener );
}
2019-12-25 23:24:31 +00:00
}
}
2019-12-26 09:40:43 +00:00
},
2019-08-15 17:40:13 +00:00
2019-12-26 09:40:43 +00:00
ScrollSpy = () => {
const sections = document.querySelectorAll( '.mw-headline' );
2019-12-25 23:24:31 +00:00
2019-12-26 09:40:43 +00:00
window.addEventListener( 'scroll', () => {
const scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
2019-08-15 17:40:13 +00:00
2019-12-26 09:40:43 +00:00
for ( let section in sections ) {
if ( Object.prototype.hasOwnProperty.call( sections, section ) &&
sections[ section ].offsetTop <= scrollPos ) {
const id = mw.util.escapeIdForAttribute( sections[ section ].id ),
node = document.querySelector( `a[href * = "${id}"]` ).parentNode;
2019-08-15 17:40:13 +00:00
2019-12-26 09:40:43 +00:00
document.querySelector( '.active' ).classList.remove( 'active' );
if ( node !== null ) {
node.classList.add( 'active' );
}
2019-12-25 23:24:31 +00:00
}
}
2019-12-26 09:40:43 +00:00
} );
},
2019-08-15 17:40:13 +00:00
2019-12-26 09:40:43 +00:00
CheckToC = () => {
if ( document.getElementById( 'toc' ) ) {
SmoothScroll();
ScrollSpy();
}
};
2019-08-19 04:24:40 +00:00
2019-12-26 09:40:43 +00:00
if ( document.readyState !== 'loading' ) {
2019-12-25 23:24:31 +00:00
CheckToC();
2019-12-26 09:40:43 +00:00
} else if ( document.addEventListener ) {
2019-12-25 23:24:31 +00:00
// All modern browsers to register DOMContentLoaded
2019-12-26 09:40:43 +00:00
document.addEventListener( 'DOMContentLoaded', CheckToC );
2019-08-19 05:30:24 +00:00
} else {
2019-12-25 23:24:31 +00:00
// Old IE browsers
2019-12-26 09:40:43 +00:00
document.attachEvent( 'onreadystatechange', function () {
if ( document.readyState === 'complete' ) {
2019-12-25 23:24:31 +00:00
CheckToC();
}
2019-12-26 09:40:43 +00:00
} );
}