Lesson 105: Spoiler

Estimated Length: 20min | Difficulty: Beginner

In this lesson, we will be going over how to create a "spoiler" button using jQuery. The example we are using shows a spoiler button "hiding" the answer to the questions below. The user can reveal the answer by clicking on the button.

Example:

Academy Awards 2016

1. Who won Best Supporting Actor?

Mark Rylance

2. Who won Best Supporting Actress?

Alicia Vikander

3. Who won Best Actor?

Leonardo DiCaprio

4. Who won Best Actress?

Brie Larson

5. What was the Best Picture?

Spotlight

HTML

The HTML markup for the spoiler is the easy part. Simply set up a list of questions using the <p> tag.

Example:

<h1>Quiz Title</h1>

<!--Question-->

<p>1. Question 1</p>

<!--Question-->

<p>2. Question 2</p>

<!--Question-->

<p>3. Question 3</p>

Next, every question needs an answer! However, we don't want to just bodly give it away. That would "spoil" it! Instead, we want to "hide" the answer behind a clickable button.

Below each question, place in this code to hold the answer.

<span class="spoiler">Answer</span>

CSS

There is no CSS needed to complete this lesson

jQuery

The jQuery in this lesson is used to hide the answer to the questions until the user clicks on the button to reveal it. jQuery is also use to create this button and add the click function to it.

We also are adding a basic fade in effect so the answer appears more smoothly after the button is pressed and disappears.

<script>

$(document).ready(function(){ //document is ready

$('.spoiler').hide(); //hide selected class

$('<input type="button" class="revealer" value="Tell Me!"/>').insertBefore('.spoiler'); //creating a button and insert before the selected element

$('.revealer').click(function(){ //add click function to the selected element

$(this).hide(); //hide button

$(this).next().fadeIn(); //next fade in the message

}); //end click function

}); //end document

</script>

Don't forget to include your jQuery CDN!

See it all together

See the Pen Spoiler by Rachel Hutchings (@imracheljoy) on CodePen.