From f7632e0071e0920f693a65a1e121e5cccaf10282 Mon Sep 17 00:00:00 2001 From: Jake Jarvis Date: Wed, 1 Dec 2021 15:54:15 -0500 Subject: [PATCH] use much, much simpler logic for adding anchors to h[2-4] elements --- assets/js/src/anchor.js | 26 +++++++++++++++++++++----- package.json | 1 - yarn.lock | 5 ----- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/assets/js/src/anchor.js b/assets/js/src/anchor.js index 06d33ffc..40b188c2 100644 --- a/assets/js/src/anchor.js +++ b/assets/js/src/anchor.js @@ -1,7 +1,23 @@ -import SimpleAnchor from "simple-anchor"; +// Heavily inspired by AnchorJS: https://github.com/bryanbraun/anchorjs -const anchors = new SimpleAnchor({ - icon: null, +// loop through each h2, h3, h4 in this page's content area +document.querySelectorAll(["div#content h2", "div#content h3", "div#content h4"]).forEach((h) => { + // don't add to elements without a pre-existing ID (e.g. `

`) + if (!h.hasAttribute("id")) { + return; + } + + // build the anchor link (the "#" icon is added via CSS) + const anchor = document.createElement("a"); + anchor.className = "anchorjs-link"; + anchor.href = `#${h.getAttribute("id")}`; + + // if this is a touchscreen, always show the "#" icon instead waiting for hover + // NOTE: this is notoriously unreliable; see https://github.com/Modernizr/Modernizr/pull/2432 + if ("ontouchstart" in window) { + anchor.style.opacity = "1"; + } + + // add anchor link to the right of the heading + h.appendChild(anchor); }); - -anchors.add("div#content h2, div#content h3, div#content h4"); diff --git a/package.json b/package.json index 10d388bf..106eec9a 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,6 @@ "preact": "^10.6.2", "query-string": "^7.0.1", "rss-parser": "^3.12.0", - "simple-anchor": "^1.0.3", "trim-newlines": "^4.0.2", "twemoji": "^13.1.0", "twemoji-emojis": "^14.1.0", diff --git a/yarn.lock b/yarn.lock index 2aafc4d6..b985161a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8746,11 +8746,6 @@ signal-exit@^3.0.0, signal-exit@^3.0.2, signal-exit@^3.0.3: resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.6.tgz#24e630c4b0f03fea446a2bd299e62b4a6ca8d0af" integrity sha512-sDl4qMFpijcGw22U5w63KmD3cZJfBuFlVNbVMKje2keoKML7X2UzWbc4XrmEbDwg0NXJc3yv4/ox7b+JWb57kQ== -simple-anchor@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/simple-anchor/-/simple-anchor-1.0.3.tgz#9e23e3c53f6cd913e576e44a2b1cb666c4e553d1" - integrity sha512-g2CrKyqfxRzEpDuuLWsGaDrN/WlU+oft1xGkiGTUB73SiG4MmqW0YMBibQ32pcu4jpL4fnEotggpMpa+ddVM3g== - simple-git-hooks@^2.7.0: version "2.7.0" resolved "https://registry.yarnpkg.com/simple-git-hooks/-/simple-git-hooks-2.7.0.tgz#121a5c3023663b8abcc5648c8bfe8619dc263705"