-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
50 lines (42 loc) · 1.5 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
window.onload = () => {
const routeElements: NodeListOf<HTMLElement> = document.querySelectorAll('.route');
// Add history push() event when boxes are clicked
routeElements.forEach(routeElement => routeElement.addEventListener('click', pushEvent));
}
window.addEventListener("popstate", popStateEvent);
function popStateEvent(event: PopStateEvent): void {
// Grab the history state id
let stateId = event.state.id;
// Visually select the clicked button/tab/box
selectTab(stateId);
// Load content for this tab/page
loadContent(stateId);
}
function pushEvent(event: MouseEvent): void {
const target = event.target as HTMLElement;
// Get id attribute of the box or button or link clicked
let id = target.id;
// Visually select the clicked button/tab/box
selectTab(id);
// Update Title in Window's Tab
document.title = id;
// Load content for this tab/page
loadContent(id);
// Finally push state change to the address bar
window.history.pushState({id}, `${id}`, `/${id}`);
}
function unselect(item: HTMLElement): void {
item.classList.remove('selected')
}
function select(item: HTMLElement): void {
item.classList.add('selected')
}
function selectTab(id: string): void {
// remove selected class from all buttons
document.querySelectorAll(".route").forEach(unselect);
// select clicked element (visually)
document.querySelectorAll("#" + id).forEach(select);
}
function loadContent(id: string) {
document.querySelector("#content").innerHTML = 'Content loading for /' + id + '...';
}