diff options
| author | Anhgelus Morhtuuzh <anhgelus.morhtuuzh@proton.me> | 2024-11-14 14:43:09 +0100 |
|---|---|---|
| committer | Anhgelus Morhtuuzh <anhgelus.morhtuuzh@proton.me> | 2024-11-14 14:43:09 +0100 |
| commit | 9787e1a1d5364ca056ec033f26e28a76ab6423e1 (patch) | |
| tree | f90c5c16ae0a7994f766cf3aa4d07dcf3baf77c5 /index.ts | |
| parent | 498a4ef4ca892e76eeea6db123ef3fe982688f85 (diff) | |
feat(nav): smooth loading while changing page
Diffstat (limited to 'index.ts')
| -rw-r--r-- | index.ts | 36 |
1 files changed, 31 insertions, 5 deletions
@@ -1,7 +1,33 @@ -const tags = document.querySelectorAll<HTMLElement>(".tag") +function setupEvents() { + document.querySelectorAll<HTMLElement>(".tag")?.forEach(t => { + t.addEventListener("click", _ => { + t.classList.toggle("active") + }) + }) -tags?.forEach(t => { - t.addEventListener("click", _ => { - 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() |
