diff --git a/src/Elastic.Markdown/Assets/main.ts b/src/Elastic.Markdown/Assets/main.ts index aa11996d8..7fcd9e98d 100644 --- a/src/Elastic.Markdown/Assets/main.ts +++ b/src/Elastic.Markdown/Assets/main.ts @@ -8,12 +8,22 @@ import {initHighlight} from "./hljs"; import {initTabs} from "./tabs"; import {initCopyButton} from "./copybutton"; import {initNav} from "./pages-nav"; +import {openDetailsWithAnchor} from "./open-details-with-anchor"; import {$, $$} from "select-dom" - import { UAParser } from 'ua-parser-js'; const { getOS } = new UAParser(); +document.addEventListener('htmx:load', function() { + initTocNav(); + initHighlight(); + initCopyButton(); + initTabs(); + initNav() + openDetailsWithAnchor(); +}); + + // Don't remove style tags because they are used by the elastic global nav. document.addEventListener('htmx:removingHeadElement', function(event) { if (event.detail.headElement.tagName === 'STYLE') { @@ -33,14 +43,6 @@ document.addEventListener('htmx:beforeRequest', function(event) { } }); -document.addEventListener('htmx:load', function() { - initTocNav(); - initHighlight(); - initCopyButton(); - initTabs(); - initNav(); -}); - document.body.addEventListener('htmx:oobBeforeSwap', function(event) { // This is needed to scroll to the top of the page when the content is swapped if (event.target.id === 'markdown-content' || event.target.id === 'content-container') { diff --git a/src/Elastic.Markdown/Assets/open-details-with-anchor.ts b/src/Elastic.Markdown/Assets/open-details-with-anchor.ts new file mode 100644 index 000000000..eddd4cb56 --- /dev/null +++ b/src/Elastic.Markdown/Assets/open-details-with-anchor.ts @@ -0,0 +1,19 @@ +import { UAParser } from 'ua-parser-js'; +const { getBrowser } = new UAParser(); + +// This is a fix for anchors in details elements in non-Chrome browsers. +export function openDetailsWithAnchor() { + if (window.location.hash) { + const target = document.querySelector(window.location.hash); + if (target) { + const closestDetails = target.closest('details'); + if (closestDetails) { + const browser = getBrowser(); + if (browser.name !== 'Chrome') { + closestDetails.open = true; + target.scrollIntoView({ behavior: "instant", block: "start" }); + } + } + } + } +}