Codementor Events

CSS tricks: A click counter without Javascript

Published Feb 18, 2019
CSS tricks: A click counter without Javascript

Is it possible to make a click counter on a pure HTML/CSS without any Javascript involved? This came as an 'out of curiosity questions' from a friend web-developer. After short investigation I found out this technique which is not only funny, but which might be useful.

And here is the solution: JSFiddle. Click at the number in the Result window and see the numbers go from 1 to 4 in a cycle. With HTML and CSS only!

The idea is pretty simple: in the HTML we have only two checkboxes with labels to code 4 different states in binary format. And in the CSS we have 4 blocks generated with the :after pseudo-element. Only one of each gets visible based on the checkbox states.

Where this could be used? In the most cases Javascript is better than CSS in producing such effects. But CSS is better when we are talking not about behavior, but about presentation of data.

Say you have a test for users: a list of questions with checkbox or radiobuttons for answers. On a laptop it is better for to have separate checkboxes for answers, but on a mobile device checkboxes are too hard to use. It is better to have a large button for choosing answers on mobile. And the approach above allows you to implement this with the same HTML.

Besides that having representation logic in CSS instead of Javascipt makes this logic much easier to understand and maintain.

Discover and read more posts from Konstantin Borisov
get started
post commentsBe the first to share your opinion
Show more replies