-
Notifications
You must be signed in to change notification settings - Fork 5
/
nav.js
58 lines (53 loc) · 1.71 KB
/
nav.js
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
51
52
53
54
55
56
57
58
export default class Nav extends HTMLElement {
constructor() {
super();
this.navLinks = [
{
name: 'Home',
url: '/'
}, {
name: 'Contact',
url: '/contact/'
}
];
}
connectedCallback() {
const { navLinks } = this;
if (this.innerHTML !== '') {
// if already server-rendered, all we need to do is highlight the active link
Array.from(this.querySelectorAll('a')).forEach(link => {
const path = globalThis.location.pathname;
const isCurrentLink = link.getAttribute('href').replace(window.location.origin, '') === path;
link.style.color = isCurrentLink ? 'var(--color-accent)' : 'var(--color-black)';
});
} else {
this.innerHTML = `
<nav>
<ul class="flex justify-center p-4 font-title text-2xl text-black-tt">
${
navLinks.map((link, index) => {
const { name, url } = link;
const isLast = index + 1 === navLinks.length;
const path = typeof globalThis.location === 'undefined' ? null : globalThis.location.pathname;
const activePath = path === url;
return `
<li>
<a
class="nav-link ${activePath ? 'text-orange-tt' : 'text-black-tt'} hover:text-gray-tt"
href="${url}"
title="Visit our ${name} page"
>
${name}
</a>
<span style="margin: 0 ${isLast ? 0 : '1rem' };">${ isLast ? '' : '|'}</span>
</li>
`;
}).join('')
}
</ul>
</nav>
`;
}
}
}
customElements.define('tt-nav', Nav);