diff --git a/index.ts b/index.ts index 57e044c..598de5c 100644 --- a/index.ts +++ b/index.ts @@ -1,7 +1,33 @@ -const tags = document.querySelectorAll(".tag") - -tags?.forEach(t => { - t.addEventListener("click", _ => { - t.classList.toggle("active") +function setupEvents() { + document.querySelectorAll(".tag")?.forEach(t => { + t.addEventListener("click", _ => { + t.classList.toggle("active") + }) }) -}) + + document.querySelectorAll("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()