Website/js/trans.js

66 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-01-11 19:38:35 +00:00
/*
* Myadeleines' Simple Page Transition Script. "Trans" for short. :trol:
* Making CSS-powered animated transitions between pages possible.
*
* Licensed under the Apache License. Please refer to the LICENSE file.
*/
const transitionBufferingEvent = new Event("transitionBuffering");
const transitionStartEvent = new Event("transitionStart");
const transitionEndEvent = new Event("transitionEnd");
2024-01-11 19:38:35 +00:00
const $ = selector => document.querySelector(selector);
const parser = new DOMParser();
const mainElement = $("main");
2024-01-11 19:38:35 +00:00
export function enableTransition( hyperlinkElement ) {
hyperlinkElement.addEventListener("click", event => {
event.preventDefault(); // Browser won't load the page when the hyperlink is pressed.
2024-01-11 19:38:35 +00:00
loadURL(hyperlinkElement.href, true, hyperlinkElement);
});
}
2024-01-11 19:38:35 +00:00
2024-04-01 22:20:16 +00:00
function loadURL( targetedURL, updateURL, hyperlinkElement ) {
const activeHyperlink = $(".pageNav .active");
2024-01-11 19:38:35 +00:00
mainElement.classList.add("buffering");
window.dispatchEvent(transitionBufferingEvent);
2024-01-11 19:38:35 +00:00
2024-04-01 22:20:16 +00:00
fetch(targetedURL + "?reduced")
.catch(error => {
console.log(error);
alert(error);
mainElement.classList.remove("buffering");
})
.then(response => response.text().then( fetchedPage => {
fetchedPage = parser.parseFromString(fetchedPage, "text/html");
fetchedPage = {
content: fetchedPage.querySelector("main").innerHTML,
title: fetchedPage.querySelector("title").innerHTML,
}
2024-01-11 19:38:35 +00:00
if (activeHyperlink) activeHyperlink.classList.remove("active");
if (hyperlinkElement) hyperlinkElement.classList.add("active");
2024-01-11 19:38:35 +00:00
2024-04-01 22:20:16 +00:00
if (updateURL) history.pushState({}, fetchedPage.title, targetedURL);
$("title").innerHTML = fetchedPage.title;
2024-01-11 19:38:35 +00:00
mainElement.classList.remove("buffering");
mainElement.classList.add("transition");
2024-01-11 19:38:35 +00:00
let transitionDuration = getComputedStyle(mainElement).transitionDuration;
transitionDuration = parseFloat(transitionDuration) * 1000;
window.dispatchEvent(transitionStartEvent);
2024-01-11 19:38:35 +00:00
setTimeout(() => {
mainElement.innerHTML = fetchedPage.content;
mainElement.classList.remove("transition");
window.dispatchEvent(transitionEndEvent);
}, transitionDuration);
}));
2024-01-11 19:38:35 +00:00
}
window.addEventListener("popstate", Event => {
loadURL(window.location.href, false)
2024-01-11 19:38:35 +00:00
});