Adding spoiler text to pages

Ever wanted to have a hover spoiler, and wondered how to do it?

It's quite simple to do, but relies on CSS3 (this should be no issue these days). What we do is to set the original text to be transparent, and to apply text shadows to show the “blurring” of the text. Upon hover, we remove the shadows and restore the colour to default.

Here's what it looks like (hover to reveal):

Snape kills Darth Vader

.spoiler {
  text-shadow: 1px 0 10px #333333, -1px 0 10px #333333;
  color: rgba(51,51,51,0);
  transition: all 0.5s ease 0s;
}
.spoiler:hover {
  text-shadow: none;
  color: #333333;
}

We can choose to adjust the transition here to take less or more time – messing with more than the transition time will likely be confusing for the user. There's also some duplication in defining the colours here manually, so if you have CSS variables to use in here, it'll help to keep your code efficiency high.

Additionally, the reason we don’t simply render the text invisible with display: none; or visibility: invisible; is that the associated shadow effects would also fall away; setting the text instead to a custom colour with 0 opacity allows the shape of the text to remain while being completely invisible.

Click-to-reveal

Of course, not everyone wants spoilers to reveal on hover – clicking to reveal is far more common, and can be achieved in two ways, depending on your desired functionality:

  1. Native CSS: click to reveal, click away to hide
  2. JavaScript: click to reveal, click again to hide

Native CSS

The simplest way, by that of minimal code, is to make the item able to be focused. We do this by supplying the tabindex attribute, and applying the :focus pseudo-class to remove the blur:

Nobody expects the Spanish Inquisition

<span class="spoiler_click" tabindex="0">Luke makes out with his own tauntaun</span>
.spoiler_click { cursor: help; }

.spoiler_click:focus {
  text-shadow: none;
  color: #333333;
}

JavaScript

A more complex method, although far more flexible in its implementation, is to use JavaScript to apply and remove the spoiler class as required. The first below example will remove the spoiler upon click and remain removed, while the second will allow restoration of the spoiler with a second click:

Bruce Willis was cheese the entire time

<span class="spoiler_click spoiler_toggle" onclick="this.classList.remove('spoiler_click');">Donnie Darko can see through glass</span>

Tyler Durden was the friends we made along the way

<span class="spoiler_click spoiler_toggle" onclick="this.classList.toggle('spoiler_click');">Jigsaw was a puzzle the whole time</span>
.spoiler_toggle {
  cursor: help;
  transition: all 0.5s ease 0s;
}