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

54 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-08-15 17:40:13 +00:00
/*
* Citizen - ToC JS
* https://starcitizen.tools
*/
2020-06-17 03:16:45 +00:00
/**
* Add active HTML class to items in table of content based on user viewport.
*
2020-06-17 03:16:45 +00:00
* @constructor
*/
function intersectionHandler() {
2021-03-08 20:02:20 +00:00
var sections = document.querySelectorAll( '.mw-headline' ),
htmlStyles = window.getComputedStyle( document.documentElement ),
scrollPaddingTop = htmlStyles.getPropertyValue( 'scroll-padding-top' ),
// Align with scroll offset set in CSS
marginTop = "-" + scrollPaddingTop,
id, id2, toclink, node, active;
for (let i = 0; i < sections.length; i++) {
const observer = new IntersectionObserver( ( entry ) => {
if ( entry[ 0 ].isIntersecting ) {
id = sections[i].id;
// Try the ID of the span before
if ( sections[i].previousSibling !== null ) {
id2 = sections[i].previousSibling.id || '';
}
toclink = document.querySelector( "a[href='#" + id + "']" ) || document.querySelector( "a[href='#" + id2 + "']" );
node = toclink.parentNode;
2020-02-16 00:20:20 +00:00
active = document.querySelector( '.active' );
if ( active !== null ) {
active.classList.remove( 'active' );
2020-02-15 22:56:29 +00:00
}
2020-02-16 00:20:20 +00:00
if ( node !== null ) {
node.classList.add( 'active' );
2020-02-15 22:56:29 +00:00
}
}
}, {
// Will break in viewport with short height
// But calculating bottom margin on the fly is too costly
rootMargin: marginTop + " 0px -85% 0px"
} );
observer.observe( sections[i] );
2020-02-15 22:56:29 +00:00
}
2020-02-15 22:55:31 +00:00
}
2020-08-12 16:37:43 +00:00
function main() {
// Check for has-toc class since it is loaded way before #toc is present
if ( document.body.classList.contains( 'skin-citizen-has-toc' ) ) {
intersectionHandler();
2020-08-12 16:37:43 +00:00
}
2020-02-16 00:20:20 +00:00
}
2020-08-12 16:37:43 +00:00
main();