Skip to content

Commit

Permalink
Add details open functions
Browse files Browse the repository at this point in the history
  • Loading branch information
adamscott committed Nov 21, 2024
1 parent 6a51e30 commit fc51738
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions assets/js/priorities.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { gsap } from "./modules/[email protected]";

/**
* Adds `target="_blank"` to element links. This will open links in a new window.
* @returns {void}
*/
function addBlankTargetToElementLinks() {
for (const anchor of document.querySelectorAll(".element-content a")) {
Expand All @@ -25,6 +26,7 @@ function addBlankTargetToElementLinks() {

/**
* Setups scroll to top functionality.
* @returns {void}
*/
function setupScrollToTop() {
const navElement = document.querySelector("#priorities-navigation");
Expand Down Expand Up @@ -77,6 +79,71 @@ function setupScrollToTop() {
scrollToTopObserver.observe(navElement);
}

// ============================
// Open details selected in URL
// ============================
/**
* If there's a hash to the URL, make sure that the appropritate details tag is open.
* @returns {void}
*/
function openDetailsSelectedInUrl() {
if (window.location.hash === "") {
return;
}

/** @type {HTMLDetailsElement | null} */
const element = document.querySelector(`${window.location.hash} details.element-main`);
if (element == null) {
return;
}
element.open = true;
}

// ========================
// Handle navigation events
// ========================
/**
* Opens the current hash when the navigation changes.
* The API is still quite new, not supported by some browsers. (2024-11-21)
* @returns {void}
*/
function handleNavigateEvent() {
// The API is not yet supported by all browsers.
if (!("Navigation" in window)) {
//openOnHandleClick();
handleHashChangeEvent();
return;
}

/**
* @param {NavigateEvent} event
*/
navigation.addEventListener("navigate", (event) => {
const url = new URL(event.destination.url);
/** @type {HTMLDetailsElement | null} */
const element = document.querySelector(`${url.hash} details.element-main`);
if (element == null) {
return;
}
element.open = true;
});
}

/**
* More common API, listens to "hashchange" event.
* @returns {void}
*/
function handleHashChangeEvent() {
window.addEventListener("hashchange", () => {
/** @type {HTMLDetailsElement | null} */
const element = document.querySelector(`${window.location.hash} details.element-main`);
if (element == null) {
return;
}
element.open = true;
});
}

// ====
// Main
// ====
Expand All @@ -87,5 +154,7 @@ function setupScrollToTop() {
function main() {
addBlankTargetToElementLinks();
setupScrollToTop();
openDetailsSelectedInUrl();
handleNavigateEvent();
}
main();

0 comments on commit fc51738

Please sign in to comment.