Implementing a Spoiler

I like to read fiction. I do it as often as I can. To keep track of my reading, I created a yearly list of the books with a short comment, not a full review.

In 2013, I added a "spoiler" feature so I could write the sort of secret details someone should skip before they read the book themselves. A small piece of JavaScript is the core of the feature. I think I grabbed it from CSS-Tricks (The same code sample is used at a lot of other sites, too).

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }

The function changes the display of a hidden block of text which is identified by its (id). If the text is visible with a style of 'block', then the style of the identified text block is changed to 'none' making it hidden. Even though that action is first in the function, it will happen second, since the block of text starts out hidden with a style of display:none. The else clause of the function is what makes the hidden text visible.

Initially, I implemented the feature using a link tag <a> to jump to the spoiler paragraph, just like the example I had read. It worked, but bothered me that the whole page jumped to the anchored text. It was visually jarring. Being able to go back later to change things is one of the best parts of Web coding. Changes may take time to percolate through my brain, but I'm not always stuck with my first effort.

I recently revisited the way I was calling the function and decided to try a button with no link components. Now I'm happy.

This page documents the implementation of the spoiler with a working example at the bottom of the page. You can also see spoiler examples in action at the recent reading page.

In addition to the JavaScript function, each spoiler needs two pieces, a button and a hidden <div>. Each spoiler must have a unique ID. In the code sample, "example" is the ID. To make several spoilers work on a page, you need a different ID for each one. The function can handle any number of hidden divs. The button code sends the specific ID to the function, and the appropriate hidden <div> is revealed.

When a spoiler is needed, I use the following button code. The onclick action calls the JavaScript function.

<button onclick="toggle_visibility('example');" class="spoilb"> SPOILER </button>
Click this to see the coding of the hidden text.

There is also a little bit of CSS style needed to finish the job. Click the next button to see that style code. You put the style code in the head section, too.

I write these notes for myself, to document my learning. If they help anybody else along the way, that's great. Good luck with your learning, too.