dark mode

Code Bites: simulate click events only with CSS

Code Bites: simulate click events only with CSS

Often, I like to joke that you can program with CSS. In this case, I’ll show you how to have click events without JavaScript.

The Issue

We have our standard CSS pseudo-classes like :hover, :active, :focus, etc. and if we need to change something on click, we fall back to good old JavaScript and its event listeners.

The Solution

Here is a little trick how to avoid JS by using inputs.

We will utilize the functionality of the label tag and the :checked selector. By clicking on the label tag with for attribute and id on the input we can change the state of the given checkbox.

After we set the label-input relationship, we need to reflect these changes with CSS.

One possible solution is for example with General sibling selectors. And it means that you can target every element after the input tag.

The example below is a dropdown made only with HTML and CSS:

See the Pen Simulate click event only with CSS by Pantaley (@pantaley) on CodePen.

Related articles

© 2020 All rights reserved.