|
| 1 | +window.counter.update = async () => { |
| 2 | + const counter = document.getElementById("counter"), |
| 3 | + key = window.counter.key, |
| 4 | + namespace = window.counter.namespace; |
| 5 | + |
| 6 | + // Clear existing nodes in the counter. |
| 7 | + while (counter.firstChild) counter.removeChild(counter.lastChild); |
| 8 | + |
| 9 | + const res = await fetch(`https://api.countapi.xyz/hit/${namespace}/${key}`); |
| 10 | + if (res.status !== 200) { |
| 11 | + throw `Failed to hit the counter API; received status ${res.status}.`; |
| 12 | + } |
| 13 | + |
| 14 | + const data = await res.json(); |
| 15 | + if (data.value === undefined) { |
| 16 | + throw `Missing counter value!`; |
| 17 | + } |
| 18 | + |
| 19 | + let value = data.value; |
| 20 | + window.counter.value = value; |
| 21 | + |
| 22 | + // Add an accessible version of the counter, hidden from normal view. |
| 23 | + const a11yCounter = document.createElement("p"); |
| 24 | + a11yCounter.classList.add("visually-hidden"); |
| 25 | + a11yCounter.innerText = `The current pageview count is ${value}.`; |
| 26 | + counter.append(a11yCounter); |
| 27 | + |
| 28 | + while (value > 0) { |
| 29 | + const digit = value % 10; |
| 30 | + value = Math.floor(value / 10); |
| 31 | + |
| 32 | + const digitNode = document.createElement("span"); |
| 33 | + digitNode.classList.add("digit"); |
| 34 | + digitNode.innerText = digit; |
| 35 | + |
| 36 | + // Hide digits from screen readers since their readout would be confusing. |
| 37 | + digitNode.setAttribute("aria-hidden", true); |
| 38 | + |
| 39 | + counter.prepend(digitNode); |
| 40 | + } |
| 41 | + |
| 42 | + return value; |
| 43 | +}; |
| 44 | + |
| 45 | +window.addEventListener("load", () => window.counter.update()); |
0 commit comments