From 3d3588455d428035b829840b408884cb6e9d3ad4 Mon Sep 17 00:00:00 2001 From: Dillon Kearns Date: Sun, 22 Sep 2019 15:51:22 -0700 Subject: [PATCH] Make sure anchor headings are scrolled into view on page render. --- index.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/index.js b/index.js index 1b10c13b..5b712057 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ const elmPagesVersion = require("./package.json").version; module.exports = function pagesInit( /** @type { { mainElmModule: { init: any } } } */ { mainElmModule } ) { + const initialLocationHash = document.location.hash.replace(/^#/, ""); let prefetchedPages = [window.location.pathname]; document.addEventListener("DOMContentLoaded", function() { @@ -40,10 +41,20 @@ module.exports = function pagesInit( }); } + function loadNamedAnchor() { + if (initialLocationHash !== "") { + const namedAnchor = document.querySelector( + `[name=${initialLocationHash}]` + ); + namedAnchor && namedAnchor.scrollIntoView(); + } + } + function observeFirstRender( /** @type {MutationRecord[]} */ mutationList, /** @type {MutationObserver} */ firstRenderObserver ) { + loadNamedAnchor(); for (let mutation of mutationList) { if (mutation.type === "childList") { setupLinkPrefetchingHelp();