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

72 lines
1.8 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
*/
2020-02-15 22:52:32 +00:00
function SmoothScroll() {
2020-02-15 23:01:01 +00:00
var navLinks, eventListener, link;
2020-02-16 00:20:20 +00:00
if ( !( 'scrollBehavior' in document.documentElement.style ) ) {
navLinks = document.querySelectorAll( '#toc a' );
eventListener = function eventListener( e ) {
2020-02-15 23:01:01 +00:00
e.preventDefault();
2020-02-16 00:20:20 +00:00
e.target.scrollIntoView( {
behavior: 'smooth'
} );
2020-02-15 23:01:01 +00:00
};
2019-12-25 23:24:31 +00:00
2020-02-16 00:20:20 +00:00
for ( link in navLinks ) {
if ( Object.prototype.hasOwnProperty.call( navLinks, link ) ) {
navLinks[ link ].addEventListener( 'click', eventListener );
2020-02-15 22:56:29 +00:00
}
}
}
2020-02-15 22:55:31 +00:00
}
2019-08-15 17:40:13 +00:00
2020-02-15 22:52:32 +00:00
function ScrollSpy() {
2020-02-16 00:20:20 +00:00
var sections = document.querySelectorAll( '.mw-headline' );
window.addEventListener( 'scroll', function () {
2020-02-15 23:05:56 +00:00
var scrollPos = document.documentElement.scrollTop || document.body.scrollTop,
2020-02-15 23:12:09 +00:00
section, id, node, active;
2019-08-15 17:40:13 +00:00
2020-02-16 00:20:20 +00:00
for ( section in sections ) {
2020-02-15 23:01:01 +00:00
if (
2020-02-16 00:20:20 +00:00
Object.prototype.hasOwnProperty.call( sections, section ) &&
sections[ section ].offsetTop <= scrollPos
2020-02-15 23:01:01 +00:00
) {
2020-02-16 00:20:20 +00:00
id = mw.util.escapeIdForAttribute( sections[ section ].id );
node = document.querySelector( "a[href='#" + id + "']" ).parentNode;
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
}
}
}
2020-02-16 00:20:20 +00:00
} );
2020-02-15 22:55:31 +00:00
}
2020-02-15 22:52:32 +00:00
function CheckToC() {
2020-02-16 00:20:20 +00:00
if ( document.getElementById( 'toc' ) ) {
2020-02-15 22:56:29 +00:00
SmoothScroll();
ScrollSpy();
}
2020-02-15 22:55:31 +00:00
}
2020-02-16 00:20:20 +00:00
if ( document.readyState !== 'loading' ) {
2020-02-15 22:56:29 +00:00
CheckToC();
2020-02-16 00:20:20 +00:00
} else if ( document.addEventListener ) {
2020-02-15 22:56:29 +00:00
// All modern browsers to register DOMContentLoaded
2020-02-16 00:20:20 +00:00
document.addEventListener( 'DOMContentLoaded', CheckToC );
2019-08-19 05:30:24 +00:00
} else {
2020-02-15 22:56:29 +00:00
// Old IE browsers
2020-02-16 00:20:20 +00:00
document.attachEvent( 'onreadystatechange', function () {
if ( document.readyState === 'complete' ) {
2020-02-15 22:56:29 +00:00
CheckToC();
}
2020-02-16 00:20:20 +00:00
} );
}