Files
youhavetrouble.github.io/src/components/ViewCounter.astro
T

87 lines
1.9 KiB
Plaintext

<div class="view-counter">
<div data-viewcount>
<span>?</span>
<span>?</span>
<span>?</span>
<span>?</span>
<span>?</span>
<span>?</span>
</div>
<div>unique visitors</div>
</div>
<style lang="scss" is:global>
.view-counter {
display: flex;
flex-direction: column;
justify-content: center;
padding-block: 1rem;
width: max-content;
text-align: center;
[data-viewcount] {
display: flex;
justify-content: center;
align-items: center;
line-height: 1;
gap: 0.2rem;
padding: 0.25rem;
font-size: 1.25rem;
span {
display: inline-block;
background: black;
color: white;
padding: 0.5ch;
font-family: monospace;
}
}
}
@media (max-width: 800px) {
.view-counter {
margin: 0 auto;
}
}
</style>
<script>
updateViewCount();
let previousCount = 0;
async function updateViewCount() {
const viewCounter = document.querySelector("[data-viewcount]");
if (!viewCounter) {
setTimeout(updateViewCount, 10000);
return;
}
console.debug("Updating view count...");
const result = await fetch("https://youhavetrouble-view_counter.web.val.run").catch(() => null);
if (result === null) {
setTimeout(updateViewCount, 10000);
return;
}
const json = await result.json();
const rawCount = json.count;
if (rawCount === previousCount) {
setTimeout(updateViewCount, 10000);
return;
}
previousCount = rawCount;
let chars = rawCount.toString();
while (chars.length < 6) {
chars = "0" + chars;
}
viewCounter.innerHTML = "";
for (let i = 0; i < chars.length; i++) {
const span = document.createElement("span");
span.textContent = chars[i];
viewCounter.appendChild(span);
}
setTimeout(updateViewCount, 10000);
}
</script>