Lesson 6 of 10
Mad Libs
Fill in a few words. The page puts them into a silly story.
What you will learn
- Reading several inputs
- Template literals
- Building a string
- .trim()
- Early return
Before you start
Quote Typer. There you compared text. Here you read several boxes and build new text from them.
What this page does
- Fill in every box: an adjective, an animal, a verb, a place, and a number.
- Click the button. Your story appears below.
- Leave a box empty and click again. The page reminds you to fill them all in.
How it works
makeStory()reads each box with.value. That is the text the user typed.- It checks that no box is empty.
.trim()removes spaces from the ends, so a box with only spaces still counts as empty. - If a box is empty, the function shows a reminder and uses
returnto stop early. Nothing after thereturnruns. - It builds the sentence with a template literal. That is a string in backticks, where
${animal}is replaced by the user's word. - It shows the result by setting
storyParagraph.textContent.
Style your story
Two lines in index.css. Try a big story on a bright page.
Build it step by step
Get one word onto the page first. Then build the sentence. Add the check last.
Make the page
Make
index.htmlwith a few labelled<input>boxes. Give each box anid. Add a button and an empty<p id="story">. Put the<script>tag at the end.Read one box
Write
makeStory(). Read one box with.valueand put that text straight into#story. Connect the button withaddEventListener("click", makeStory). Click it. Your word appears.Build the sentence
Read the other boxes. Join them into a sentence with a template literal. Reload and try it. You get a full silly story.
storyParagraph.textContent = `One day, a ${adjective} ${animal} decided to ${verb} ` + `all the way to ${place}. It took ${number} minutes.`;Add the empty-box check
Add an
ifthat uses.trim()to find empty boxes. Show a reminder andreturnearly. Test it by leaving one box blank.
Try these changes
Make these in the files beside this guide. None of them need anything the lesson has not covered.
- Add more boxes, such as a colour and a food, and put them in the story.
- Write a longer story with more blanks.
- Add a Surprise me button that fills the boxes with random words.
- Clear the boxes after the story is made.
Teacher's versionHow to run this lesson, what to check, and any answers. Students do not need this.
How to teach it
- Let the student choose the story. A story they wrote is worth three that you wrote.
- Build the string with
+first if template literals confuse them, then rewrite it with backticks side by side. Seeing both makes the backtick version obvious. - Add the empty-box check last, on purpose. The student should first see the broken output with a missing word, so the check has a reason to exist.