Click without JavaScript !

This post is about clicking on an element without JavaScript.

ยท

2 min read

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 of a page.
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!

1- We have a hash-link :

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

2- We have a div with an ID matching the hash-link :

<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>

3- We hide this div by default :

/* Hide the div by default */
#the-code {
    display: none;
}
/* Show the div when it's hash-link is clicked */
#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 its original state, hidden since this hash-link doesn't match it's ID.

Hope you'll find it useful.

SYA,
LebCit.

ย