feat(nav): smooth loading while changing page

This commit is contained in:
Anhgelus Morhtuuzh 2024-11-14 14:43:09 +01:00
parent 498a4ef4ca
commit 9787e1a1d5
No known key found for this signature in database
GPG key ID: CAD341EFA92DDDE5

View file

@ -1,7 +1,33 @@
const tags = document.querySelectorAll<HTMLElement>(".tag") function setupEvents() {
document.querySelectorAll<HTMLElement>(".tag")?.forEach(t => {
tags?.forEach(t => { t.addEventListener("click", _ => {
t.addEventListener("click", _ => { t.classList.toggle("active")
t.classList.toggle("active") })
}) })
})
document.querySelectorAll<HTMLAnchorElement>("a")?.forEach(a => {
a.addEventListener("click", e => {
if (!a.href.startsWith(window.location.origin)) return
e.preventDefault()
changePage(a.href)
})
})
}
function changePage(href: string) {
fetch(href)
.then(resp => resp.text())
.then(html => {
const doc = new DOMParser().parseFromString(html, "text/html")
window.history.pushState({}, "", href)
document.title = doc.title
const distMain = doc.querySelector("main")
const currentMain = document.querySelector("main")
if (distMain === null || currentMain === null) document.body = doc.body
else currentMain.innerHTML = distMain.innerHTML
setupEvents()
})
}
window.addEventListener("popstate", e => window.location.reload())
setupEvents()