Skip to content

Instantly share code, notes, and snippets.

@MightyPork
Created April 27, 2018 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MightyPork/827a654b6cfb816ae50a057a8ea5e40b to your computer and use it in GitHub Desktop.
Save MightyPork/827a654b6cfb816ae50a057a8ea5e40b to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Wiki Toc Toggles
// @namespace http://tampermonkey.net/
// @match https://en.wikipedia.org/wiki/*
// ==/UserScript==
(function() {
'use strict';
function setUpTocToggles() {
console.info("Setting up TOC toggles");
let toc = document.querySelector('#toc');
let head = document.querySelector('#mw-head');
let content = document.querySelector('#content');
let foot = document.querySelector('#footer');
let tocul = toc.querySelector('ul');
if (!toc || !head || !foot || !tocul) {
console.warn("Elements not found!");
return;
}
// remove the [hide] toggle
setTimeout(function(){
let tt = toc.querySelector('.toctoggle');
if (tt) tt.parentElement.removeChild(tt);
}, 500); // delay because it is added by javascript and it takes a while to load
const SIDEBAR_W = 300; // TOC width
const RPAD = 16; // distance between TOC and content
// move TOC to the right, make it sticky
toc.style.position = 'fixed';
toc.style.right = 0;
toc.style.top = 0;
toc.style.height = '100%';
toc.style.overflow = 'scroll';
toc.style.width = SIDEBAR_W+'px';
toc.style.borderTop = 'none';
toc.style.borderBottom = 'none';
toc.style.borderRight = 'none';
// move content away from the right border
head.style.marginRight = (SIDEBAR_W+RPAD)+'px';
content.style.marginRight = (SIDEBAR_W+RPAD)+'px';
foot.style.marginRight = (SIDEBAR_W+RPAD)+'px';
// make TOC scrollable if too long
tocul.style.overflowY = 'auto';
tocul.style.maxHeight = '95%';
// add hiding buttons to all <a> followed by <ul>
let hidingUls = toc.querySelectorAll('a+ul'); // this selects the ul's
for(let i = 0; i < hidingUls.length; i++) {
let ul = hidingUls[i];
ul.style.display = 'none'; // hide by default
// Find the <a>
let a = ul.previousSibling;
// if it's a text element (space), go further
if (a.nodeType == 3) {
a = a.previousSibling;
}
// now add the toggle button
let togbtn = document.createElement('a');
togbtn.type = 'button';
togbtn.textContent = '[+]';
togbtn.style.marginLeft = '5px';
// Click handler
togbtn.addEventListener('click', function (e) {
if (ul.style.display == 'none') {
// Open
ul.style.display = '';
togbtn.textContent = '[–]'; // en dash
} else {
// Close
ul.style.display = 'none';
togbtn.textContent = '[+]';
}
e.preventDefault();
});
// Add the button into the <a>
a.appendChild(togbtn);
}
}
setUpTocToggles();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment