How I added an AlpineJS click counter to my HTMX-powered website

Date: 2025-01-01 | create | build | one-million-checkboxes | alpine-js | htmx |

Earlier this year I built a One Million Checkboxes clone using HTMX.

It's been running in prod for a few months getting 1000s of clicks but I felt it was a bit boring so wanted to add a bit more gamification to it - first with some click counters.

Adding a client-side click counter with Alpine JS

HTMX can certainly do click counters and if your counter requires a db fetch then that may make sense. For now though I'm keeping things simple with a client-side counter so a network call for that is a bit heavyweight. I've previously built a few projects combining HTMX and Alpine and had a good experience so decided to reach for that.

Creating a click counter was simple with Alpine:

  • Add Alpine js library to page
  • Create data on my element that has a count attribute
  • On click of a checkbox, increment count
  • Create a text element that references the updating count

To add Alpine js I include the library from CDN into my page:

<script src="https://cdn.jsdelivr.net/npm/alpinejs@3.14.7/dist/cdn.min.js" defer=""></script>

To create the data, I add the x-data="{ count: 0 }" to my surrounding div. This instantiates data with an attribute count set to 0.

To make checkbox clicks update the count, I add @click="count++" to each one which means on click it will run count++ which will effect the surrounding data scope.

Note: I was a little worried this would blow up my page reload payload cause I'm adding this literally 1000 times for each polling refresh but in practice this only increased the payload by ~0.1kB so not that big of a deal.

To actually show the number of clicks you've made, I created a little text element with a span bound to the count variable. Alpine is reactive so whenever the variable changes, it updates its references in the page as well.

<div class="max-w-xl mx-auto">
    Your Clicks: 
    <span x-text="count">0</span>
</div>

Future Work

I like having a counter here, it makes the page feel a bit more alive. Of course it's still pretty basic so there's a few ways I'm considering increasing dynamism:

  • Persist count to local storage so you can save progress
  • Consider some global counters as well - maybe some overall counts that could be shared by everyone playing?

Let me know if you have ideas for making One Million Checkboxes more fun to click.

Next

If you haven't already, please check out One Million Checkboxes and check some boxes!

If you liked this post you might also like:

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.