Last active
October 2, 2023 14:45
TamperMonkey User Script - WordPress Developer Docs > In-Page Navigation Anchors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name WordPress Developer Docs - In-Page Navigation Anchors | |
// @namespace http://tampermonkey.net/ | |
// @version 0.1 | |
// @description Adds a sticky table of contents to the sidebar that contains anchor links to in-page sections when on developer.wordpress.org | |
// @author Gabriel Rose (@roseg43) | |
// @match https://developer.wordpress.org/* | |
// @icon https://www.google.com/s2/favicons?sz=64&domain=wordpress.org | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
const headings = Array.from(document.querySelectorAll('#primary :is(h1,h2,h3,h4,h5,h6)[id]')); | |
const sidebar = document.getElementById('secondary'); | |
if (!headings.length || !sidebar || window.matchMedia('(max-width: 768px)').matches) { | |
return; | |
} | |
const content = document.getElementById('content'); | |
// Wrap the sidebar in a div so that sticky positioning works properly. | |
const sidebarWrapper = document.createElement('div'); | |
// Create ToC nav / set styles | |
const tocNavEl = document.createElement('div'); | |
tocNavEl.classList.add('menu-table-of-contents-container'); | |
tocNavEl.style.position = "sticky"; | |
tocNavEl.style.top = `${content.getBoundingClientRect().y + window.scrollY}px`; | |
// Add a title to the nav | |
const tocNavHeading = document.createElement('h3'); | |
tocNavHeading.innerText = "On this page"; | |
tocNavEl.appendChild(tocNavHeading); | |
// Create the nav list | |
const tocNavList = document.createElement('ul'); | |
tocNavEl.appendChild(tocNavList); | |
// Create nav items from headings | |
const tocNavListItems = headings.map(heading => { | |
const listItem = document.createElement('li'); | |
const link = document.createElement('a'); | |
link.setAttribute('href', `#${heading.id}`); | |
link.textContent = heading.textContent; | |
link.style.padding = "2px 2px 2px 13px"; | |
listItem.appendChild(link); | |
return listItem; | |
}); | |
// Append items | |
tocNavListItems.forEach(item => tocNavList.appendChild(item)); | |
sidebarWrapper.appendChild(sidebar) | |
sidebarWrapper.appendChild(tocNavEl); | |
// Fix width of the sidebar | |
sidebar.style.width = "100%"; | |
content.prepend(sidebarWrapper); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This adds a really simple sticky navigation to the sidebar on developer docs:
Clicking any of these navigation items will navigate you to the relevant section on the page.