Click without JavaScript !

This post is about clicking on an element without JavaScript.

Intro #

Let's say that you have a button on which you want to click and perform a simple action like displaying some hidden content.
You'll directly think :

const btn = document.getElementById("btn")
btn.addEventListener("click", () => {
// display my hidden content...
})

What if I tell you that you could do it with CSS ?!

The :target CSS pseudo-class #

While surfing the net, you surely clicked before on a hash-link, a link that redirects to a particular section in a page, just like the above Intro heading !
It could also redirect to another page, but always to a particular target on the page.
The target in this case is reached by a link with a hash # :

<a href="#intro">Intro</a>

This is why we call it a hash-link.

CSS has a :target pseudo-class, that can be used to select a target and style it !
Are you already thinking about the display property ? 😉
Let's do it !

Reveal the code !

<a href="#the-code">Reveal the code !</a>

<div id="the-code">
<p>This block of code is displayed after you click on the link</p>

<a href="#hide-the-code">Hide the code !</a>
</div>
#the-code {
display: none;
}

#the-code:target {
display: block;
}

Hide the code !

So how does this work ?!
It's quite simple :

  1. We have a hash-link :
<a href="#the-code">Reveal the code !</a>
  1. We have a div with an ID matching the hash-link :
<div id="the-code">...</div>
  1. We hide this div by default :
#the-code {
display: none;
}
  1. Then we display it if the hash-link becomes the target :
#the-code:target {
display: block;
}

I've also added at the end of the div a hash-link that doesn't correspond to any target :

<a href="#hide-the-code">Hide the code !</a>

When this one is clicked, the target is changed and the block of code goes back to it's original state, hidden, since this hash-link doesn't match it's ID.

Hope you'll find it useful.

SYA,
LebCit.