A site with widgets

W00f! You know how to make a Web site! It looks good, has interactive menus, cool things like quizzes, and is generally w00fy.

This chapter shows you how to add more interactive stuff to your site. Games, movies, chat… lots of w00fy goodies. Some things you’ll make yourself. Other things you’ll copy (legally!) from other sites.

Let’s get going!

Search

Where are we?

You know how to make a static Web site. You can make a site more useful by adding widgets.

This lesson’s goals

Search is one of the most important widgets. This lesson shows you how to add a simple search function to your site.

By the end of this lesson, you should:

  • Know why search makes your site more valuable.
  • Be able to create a search form on your site.
  • Be able to run Google searches from your site.

Why search matters

A good search function makes your site more valuable to visitors. Why?

It’s about benefit/cost ratio. Someone comes to your site with a question. Your content helps them answer the question. That’s a benefit.

But using your site has a cost: the time it takes to find the answer. If it takes a long time, the cost of finding the answer gets too high. People will go elsewhere.

A search function does not add content to your site. But it reduces the cost of finding the content that is already there. The result? Your site has a higher benefit/cost ratio. It’s more valuable to users.

But how do you add search?

Using Google’s search engine

Google already does a good job with search. So let’s borrow their search engine.

You know how to use Google. You go to http://google.com, and enter your search terms:

Google URL

Google homepage

Figure 1. Starting a Google search

When you click the Search button, your browser takes the URL of the search engine:

http://www.google.com/search

Then it adds the data you typed into the search field:

http://www.google.com/search?q=page+layout

Your format may vary. But you should see page+layout somewhere.

Your browser sends the entire string to the server at google.com. The server extracts the data “page layout”, runs the search, and shows you the results.

Google search URL

Google search result

Figure 2. Search result

It’s not quite that simple, but this is close enough for us to work with.

Try it yourself. Go to Google, type in some search terms, and run the search. Check out the URL of the results page. It won’t look exactly like the one I just gave you, but you’ll see the terms you typed embedded in the URL.

Renata
Renata

The user typed “page layout” into the text field. But when it was added to the URL, it was changed to page+layout. Why?

Kieran
Kieran

This is called URL encoding. Special characters like spaces, colons, etc., don’t work well in URLs. Your browser replaces the special characters, like making a space into +. When the google.com server gets the URL, it reverses the changes, converting page+layout back to “page layout”.

Searching on one site

You can restrict your Google search to a specific site, using the site parameter:

Google URL

Google homepage

Figure 3. Starting another Google search

The search engine will only search within the site you named. The results might be:

Another Google search URL

Another Google search result

Figure 4. Another search result

CC
CC

That’s URL encoding again?

Kieran
Kieran

Right. The user typed:

site:coredogs.com page layout

The browser used URL encoding, to make:

site%3Acoredogs.com+page+layout

The : became %3A. The entire URL was:

http://www.google.com/search?q=site%3Acoredogs.com+page+layout

Adding search to our site

Two steps.

  • Visitors type in search terms to a form on our site.
  • We send the search terms to Google, telling it to restrict the search to just our own site.

The form will look like this:

Our form

Figure 5. Our form

The user will type in some search terms:

Our form with search terms

Figure 6. Our form with search terms

When the visitor clicks the button, s/he gets the search results:

Another Google search URL

Another Google search result

Figure 4 (again). Another search result

Let’s do it piece by piece.

Creating the search form

This HTML will create the search form:

<h1>Search Demonstration</h1>
<div id="search_form">
  <input id="search_terms" type="text" size="20">
  <button id="search_button" title="Search this site">Search</button>
</div>

Figure 7. HTML for the search form

The <div> contains the entire form. It’s just an <input> field and a single <button>.

Here’s some CSS to style the form:

#search_form {
  background-color: #FBC766;
  padding: 10px;
  margin: 10px;
  float: left;
  border: 1px gray dotted;
}

Figure 8. CSS for the search form

If you wanted to put the form on the right of the page (in the header, say), you would change float: left; to float: right;. You can read about page layout with headers and such in another lesson.

Coding the search button

Now for the JavaScript code.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $("#search_terms").focus();
    $("#search_button").click(function() {
      var search_terms = $("#search_terms").val();
      if ( search_terms != "") {
        var google_url = "http://google.com/search?q="
          + "site:coredogs.com "
          + search_terms;
        window.location.href = google_url;
      }
    });
  });
</script>

Figure 9. JavaScript for the search form

As usual, we include the jQuery library (line 1). You can just copy-and-paste this line into your own page.

The code in the ready() event (lines 3 to 14) runs when the page has finished loading. It puts the keyboard cursor in the search field (line 4). You might not do this normally, but it’s convenient for testing the script.

Line 5 attaches code to the button’s click event. When the user clicks the Search button, the code in lines 6 to 11 runs.

Line 6 gets what the visitor typed into the text field, and puts it into a variable called search_terms.

Maybe the visitor clicked the Search button without typing anything. We don’t want to run the search, because there’s nothing to search for.

Line 7 takes care of that. Remember that != means “not equal to.” Two quotes together – "" – are an empty string. So, with:

if ( search_terms != "" ) {
...
}

the statements in the … will only run if search_terms has something in it.

Here are lines 8 to 10 again:

var google_url = "http://google.com/search?q="
   + "site:coredogs.com "
   + search_terms;

This makes the destination URL, and puts it into the variable google_url. We start with http://google.com/search?q=, then add the site name, and finally the search terms typed by the site visitor.

To search a different site, replace coredogs.com with another site name.

Here’s the next line (line 11):

window.location.href = google_url;

This tells the browser to go to URL in google_url. The browser will automatically URL encode google_url.

You can try it yourself.

W00f!

What we did works, but it loses the look of your site. Here’s what people see after using our search form:

Another Google search result

Part of Figure 4 (again). Another search result

Nothing like our site’s colors.

But there are other ways to add search to your site. You have two choices.

  • Use someone else’s search engine, like we did above.
  • Install your own search engine on your Web site.

Using someone else’s is easier. Googe Site Search is a paid service that can be used without Google branding. It shows search results on your site in your format.

To use your own search engine, you install a program on your server. You link your search form to it, so that the program runs when a user does a search.

You need to know how to install server-side programs to operate your own search engine. The ServerCore book is all about server-side programs. But if you want to see what’s out there, try HotScript’s PHP search engines page.

Exercise: YouTube searching

Make a page that will let people search YouTube. Here’s what mine looks like:

YouTube search form

Figure 1. YouTube search form

The user enters some text in the fields, and clicks the button. The results of a YouTube search appear.

For example, I entered Drupal in the field:

Drupal search

Figure 2. Drupal search

Here’s what I saw:

Drupal search results

Figure 3. Drupal search results

Upload your solution to your server, and enter the URL here.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

Search is one of the most important widgets. This lesson showed you how to add a simple search function to your site. You learned:

  • Why search makes your site more valuable.
  • How to create a search form on your site.
  • How to run Google searches from your site.

What now?

We’ve just started our tour of widgets you can add to your site. Let’s look at some social widgets.

The social Web

Where are we?

You added a search widget to your site. Now let’s look at social widgets.

This lesson’s goals

  • What is the social Web?
  • Add a chat page to your site.
  • Add a Twitter widget to a page.
  • Add a Facebook Like button to a page.

What is the social Web?

Compare email and the social Web. There are some differences.

First, email is often one person talking to one other person, or a few people. Social media is lots of people doing things that many other people can see. It’s sometimes called multi-way, many-to-many, or n-to-n.

Second, email is about conversation. You send messages that are (usually) read and discarded. The life of an email can be a few seconds. You can do that with social media as well. But you can also post content that has a longer life. For example, you can put photos on Facebook that people can look at for years to come.

People use social media for many different things. Some uses are personal.

Renata: My humans are a pain. Let them in, let them out, let them in… They’re driving me nuts.

CC: Chew up their shoes.

Social media is for business as well.

CC: Patrolling the yard last night. Rabbits are coming through a hole in the fence. Any ideas?

Renata: Tell them they can come in, but first they have to write a mission statement they all agree on.

CC: Good one. :=) I’ll try it.

Social media is for learning, too. For example, I follow Jane Bozarth on Twitter. She’s an expert on social media for education. When she comes across something interesting, she tweets it. I learn from what she says, and the URLs she includes in her tweets.

A third difference between email and the social Web is aggregation. Each email is more-or-less independent. But you can use the social Web to combine information from different people. For example, you can look at a product on Amazon.com, and see ratings from different people. Here is the ratings summary for the PC game Mass Effect 2:

Game ratings

Figure 1. Game ratings

The social Web is always changing. But it will be important for a long time to come.

Let’s look at easy ways to add social stuff to your site.

Adding chat to your site

There are many ways to do this. The easiest is to use a service someone has already created, rather than making something yourself.

Let’s use Chatango to add chat to a site. It’s free. Free is good.

You can go to http://chatango.com/ and click the “Create a public group” button:

Chatango home page

Figure 2. Chatango home page

You’ll get a screen that lets you create a chat group:

Creating a chat group

Figure 3. Creating a chat group

You can customize the look of your chat widget, changing colors and such:

Customizing the chat widget

Figure 4. Customizing the chat widget

When you are ready, click the Continue button. You can always come back and change the settings.

You’ll get some code you can paste into a Web page. It will start something like this:

<object width="350" height="450"

Paste it into your page.

Here’s a CoreDogs chat, created with Chatango.

You also get a subdomain name on Chatango’s site. The one for CoreDogs is http://coredogs.chatango.com.

Exercise: Create a chat

Add a chat widget to your site. Use Chatango or another service, like ewc or Chat-Forum.Com.

Enter the URL of your page below.

Find another chat service you like? Tell us about it in the discussion below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

A Twitter widget

Twitter offers various widgets you can insert in your Web site. You can see them at http://twitter.com/goodies/widgets. Click on the My Website link.

Let’s use the search widget. It will show tweets that match a search phrase we can specify. Let’s show tweets that have the words “dog” and “love” in them.

Here’s what we’ll end up with:

Go to http://twitter.com/goodies/widget_search to get started. You’ll see a screen like this:

Settings

Figure 5. Settings

I typed stuff into the fields. The most important is the first one, Search Query. The widget will show tweets that match this search.

I messed with the appearance a bit:

Appearance

Figure 6. Appearance

On the dimensions tab, I selected auto width:

Dimensions

Figure 7. Dimensions

Click on the Finish & Grab Code button:

Finish button

Figure 8. Finish button

You’ll get some code you can paste into your HTML.

Exercise: Create a Twitter widget

Add a Twitter widget to your site. Use it to search for any phrase you want.

Enter the URL of your page below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Facebook Like button

Here’s a Like button for the page you’re reading now:

When someone clicks on the button, their Facebook page records that they Like something. The “something” is usually the page the Like button is on.

Here’s how I made the button. First, I went to Facebook’s page for making Like buttons. I got a form like this:

Making a Facebook Like button

Figure 9. Making a Facebook Like button

The only thing I changed was the first field, the URL for the page. I copied and pasted the URL for the page you’re reading now. Look at the address bar of your browser. You’ll see it’s the same as “URL to Like” in Figure 9.

Then I clicked on the Get Code button in Figure 9. I saw this:

Code for the Like button

Figure 10. Code for the Like button

Use the code at the top. Copy and paste it into your page.

The code uses the HTML iframe tag. iframe inserts one page inside another. iframe is not a core tag, so isn’t covered in CoreDogs. But you can read more about it, if you want.

These screen shots were current when I wrote this page. They may have changed by now.

Summary

  • The social Web is multi-way conversations and content. It has personal, business, and learning uses. Aggregation is one of its most powerful uses.
  • You learned how to add chat to your site.
  • You learned how to add a Twitter widget.
  • You learned how to add a Facebook Like button.

What now?

Now lets add some games.

Games

Where are we?

This chapter is about adding widgets to your site. We’ve looked at search, advertising, affiliate sales, and other things. This lesson looks at games.

You can use games that others have created. But you can also use games you write yourself. The advantage of doing it yourself is that you can customize the games to match the content and the look and feel of your site.

Let’s see how you can add a Mad Lib to your site.

This lesson’s goals

By the end of this lesson, you should:

  • Know what a Mad Lib is.
  • Understand the flow of a Mad Lib game.
  • Be able to create the input form and output story for a Mad Lib.
  • Be able to write the JavaScript code for a Mab Lib.

What is a Mad Lib?

The goal of a Mad Lib is to create a story. There are two people, the reader and the player. The reader has a piece of paper that looks something like this:

Mad Lib

Figure 1. Mad Lib

The reader asks the player for words to fill in the blanks.

Getting the words

Figure 2. Getting the words

The reader writes the words into the story. When all the blanks have been filled, the reader tells the completed story.

Telling the story

Figure 3. Telling the story

The result? Fun for all dogs! And young players learn a bit about language as well.

You can visit the official Mad Lib site. There’s a history of the game, Mab Lib books, and other stuff.

Game flow

Let’s make a Mad Lib game. The computer takes the part of the reader in Figure 2. The person is the player. The player fills in a form:

Input form

Figure 4. Input form

The player clicks the Go button, and gets the output:

Story output

Figure 5. Story output

You can try it. It isn’t a complete story. I just wanted enough to show you how it works.

Here is the overall pattern for game flow. You can see what the Web browser does and what the player (the user) does.

  1. Browser: Show the form
  2. Player: Complete the form
  3. Player: Click the Go button
  4. Browser: Get the player's input

    If the form is not complete, show an error and stop.

  5. Browser: Fill in the blanks in the story
  6. Browser: Show the story

Figure 6. Game flow

The player has to complete all of the fields in the form. If s/he does not, the browser shows an error message, and stops.

Making the input form

As Figure 4 shows, I wanted input fields that look like this:

Input field

Figure 7. Input field

Here’s the HTML for one field:

<p>
  The first name of someone you know (e.g., Tom).
  <input id="first_name1_in" type="text" size="20">
</p>

Figure 8. HTML for an input field

The field has an id, so that the JavaScript can easily get what the user entered into the field. The value of the id property – first_name1_in – says what the field is for. It’s a first name input. There are two first name input fields. This is number 1 of 2.

Renata
Renata

Could it have been called first_name_in1, or name_first_1_in?

Kieran
Kieran

Yes. Use whatever ids make sense to you, and that you think other Webers will understand. Just make sure they are descriptive.

For example, q43s would not be a very good id. The computer won’t care, but it makes the code harder for other Webers to understand.

There’s some CSS as well for styling. Setting the font family, background color, and such.

For each person’s name in Figure 4, I also wanted radio buttons for choosing gender:

Gender radio buttons

Figure 9. Gender radio buttons

Here’s some HTML.

<p id="html_for_gender_radio_buttons">
  Is this person male or female?<br>
  <input type="radio" name="gender1_in" id="gender1_in_male" value="male" checked="true"> Male<br>
  <input type="radio" name="gender1_in" id="gender1_in_female" value="female"> Female<br>
</p>

Figure 10. HTML for gender radio buttons

There are two <input> fields, one for each radio button. The first one has checked="true", so it is checked when the page first displays.

Each radio button has a name property and an id property. The names are the same, but the ids are different. What’s going on?

Radio buttons usually don’t work alone. They work in groups. Only one radio button in a group can be selected at a time.

Here are two button groups. Pick your favorite animal and food below.

Cat
Dog
Horse

Chocolate
Dog biscuits
Ice cream
Pizza

Figure 11. Some radio buttons

Click on all the options. In the first group, you can only select one animal. In the second group, you can only select one food.

How does the browser know which buttons form a group? By the name property.

All of the animal radio buttons start like this:

<input type="radio" name="animal"

All of the food radio buttons start like this:

<input type="radio" name="food"

When there are several radio buttons with the same name, the browser will only let one of them be selected.

Suppose I change all of the names of the radio buttons in Figure 11 to the same thing. Let’s make them all bark. The HTML for all the buttons starts this way:

<input type="radio" name="bark"

Here’s what you get:

Cat
Dog
Horse

Chocolate
Dog biscuits
Ice cream
Pizza

Figure 12. Messed up radio buttons

Try clicking on all the radio buttons.

Because they all have name="bark", they are all part of the same group. So only one of them can be selected.

Here’s another way to mess things up. Suppose I give all of the buttons different names. The first one is thing1, the next is thing2, the next thing3, and so on, up to thing7.

Try clicking on these buttons.

Cat
Dog
Horse

Chocolate
Dog biscuits
Ice cream
Pizza

Figure 13. More messed up radio buttons

Because each button has a different name, each one is in a different group.

OK, so you know that the name property defines a group. But how can your JavaScript code tell which button within a group is checked?

Here’s the gender code again:

<p id="html_for_gender_radio_buttons">
  Is this person male or female?<br>
  <input type="radio" name="gender1_in" id="gender1_in_male" value="male" checked="true"> Male<br>
  <input type="radio" name="gender1_in" id="gender1_in_female" value="female"> Female<br>
</p>

Figure 10 (again). HTML for gender radio buttons

The id properties are different for male and female. You can write JavaScript to use them. We’ll see that in a moment.

Renata
Renata

There’s also a value property in each of them.

Kieran
Kieran

Good eye. The value isn’t used here. It’s for sending data to the server. We’ll talk about that in ServerCore.

Here is all the HTML for the input form:

<div id="input_stuff">
  <p>Please fill in the fields and click <strong>Go</strong>.</p>
  <p>
    The first name of someone you know (e.g., Tom).
    <input id="first_name1_in" type="text" size="20">
  </p>
  <p>
    Is this person male or female?<br>
    <input type="radio" name="gender1_in" id="gender1_in_male" value="male" checked="true"> Male<br>
    <input type="radio" name="gender1_in" id="gender1_in_female" value="female"> Female<br>
  </p>
  <p>
    The first name of another person you know (e.g., Rita).
    <input id="first_name2_in" type="text" size="20" checked="true">
  </p>
  <p>
    Is this person male or female?<br>
    <input type="radio" name="gender2_in" id="gender2_in_male" value="male" checked="true"> Male<br>
    <input type="radio" name="gender2_in" id="gender2_in_female" value="female"> Female<br>
  </p>
  <p>
    A color (e.g., blue).
    <input id="color1_in" type="text" size="20">
  </p>
  <p>
    Animal, plural (e.g., penguins).
    <input id="animal1_in" type="text" size="20">
  </p>
  <p>
    Another animal, plural (e.g., moles).
    <input id="animal2_in" type="text" size="20">
  </p>
  <p>
    <button id="go_button" title="Tell story">Go</button>
  </p>
</div>

Figure 14. HTML for the input form

Notice that the entire input form is wrapped in a <div> (line 1). This lets JavaScript hide the form in one step.

Making the output area

Let’s look at the part of the page that shows the output, that is, the story with the blanks filled in. Here’s what the paper version looks like.

Mad Lib

Figure 1 (again). Mad Lib

We need to give each of the blank spots an id. Then we can use JavaScript to put text in there. The <span> tag is good for that.

Here’s all the code for the output area.

<div id="story">
  <p>
    <span id="first_name1_out"></span>&nbsp;was walking in the park one day,
    humming to <span id="gender1_out"></span>self. The day was bright, the
    sun was shining, and the <span id="animal1_out"></span>&nbsp;were singing.
  </p>
  <p>
    Suddenly, two <span id="color1_out"></span>&nbsp;<span id="animal2_out"></span> ran by.
  </p>
  <p>
    "Run! Run!" they cried. "<span id="first_name2_out"></span>&nbsp;is coming!
    And <span id="gender2_out"></span>'s really angry!"
  </p>
  <p>
    <button id="reset_button" title="Show input fields again">Reset</button>
  </p>
</div>

Figure 15. HTML for the output area

Have a look at line 3. The blank for the first name is created with this:

<span id="first_name1_out"></span>

There’s no text in the <span>. We’ll write some JavaScript to fill it in from the form.

But what about the thing that follows the </span>?

...</span>&nbsp;was...

The &nbsp; is a hard space. We should be able to put just:

...</span> was...

That should work, and it does in most browsers. But when Internet Explorer and jQuery are used together, the space gets gobbled up. So we have to use the HTML entity code &nbsp; to force the space to appear.

The JavaScript

Let’s review the overall flow of the game.

  1. Browser: Show the form
  2. Player: Complete the form
  3. Player: Click the Go button
  4. Browser: Get the player's input

    If the form is not complete, show an error and stop.

  5. Browser: Fill in the blanks in the story
  6. Browser: Show the story

Figure 6 (again). Game flow

Let’s write the JavaScript for the Go button. It needs to do steps 4, 5, and 6.

Here’s code that will get the value of an input field and check whether it’s empty.

var first_name1_in = $("#first_name1_in").val();
if ( first_name1_in == "") {
  alert("Please complete all fields.");
  $("#first_name1_in").focus();
  return;
}

Figure 16. Check that a field was completed

Line 1 gets the value the user typed into the field, and puts it in a variable.

Line 2 checks whether the user put anything in the field. If the field is empty, the variable will be equal to an empty string: "".

If the field is empty, show an error message (line 3). Then put the input focus into the empty field (line 4). The user can then start typing, without having to click on the field him/herself.

Line 5 is important. This stops the $("#go_button").click() function from going any further.

All of the text input fields are checked for missing data. The pattern in Figure 16 is repeated for each text input field.

In fact, these checks make up most of the code in the $("#go_button").click() function. It’s common for most of the code in a program to be error checking.

We also need to get the data from the gender radio buttons. As a reminder, here is some HTML for one of the buttons. It creates a group of two radio buttons.

<p id="html_for_gender_radio_buttons">
  Is this person male or female?<br>
  <input type="radio" name="gender1_in" id="gender1_in_male" value="male" checked="true"> Male<br>
  <input type="radio" name="gender1_in" id="gender1_in_female" value="female"> Female<br>
</p>

Figure 10 (again). HTML for gender radio buttons

The user tells us whether a person is male or female. How do we use this? Here’s part of the HTML for the story:

humming to <span id="gender1_out"></span>self.

We want gender1_out to be “him” for a male, or “her” for a female.

Here’s some JavaScript to get the value of this radio button group, and create a variable with the text we want to show.

var gender1_out;
if ( $("#gender1_in_male").is(":checked") ) {
  gender1_out = "him";
}
else {
  gender1_out = "her";
}

Figure 17. Compute gender pronoun

The syntax in line 2 is a little strange. gender1_in_male is the id of one of the radio buttons in the group. is(":checked") is true if that button is checked.

There are two radio button groups in the input form:

Input form

Figure 4 (again). Input form

So we have another version of Figure 17 for the other group.

We have two more steps in the game flow:

  1. Browser: Show the form
  2. Player: Complete the form
  3. Player: Click the Go button
  4. Browser: Get the player's input

    If the form is not complete, show an error and stop.

  5. Browser: Fill in the blanks in the story
  6. Browser: Show the story

Figure 6 (again). Game flow

Here’s some HTML for the story:

<p>
  "Run! Run!" they cried. "<span id="first_name2_out"></span>>nbsp;is coming!
  And <span id="gender2_out"></span>'s really angry!"
</p>

Figure 18. Part of the HTML for the output area (from Figure 15)

We put the text of each input field into a variable, like this (from Figure 16):

var first_name2_in = $("#first_name2_in").val();

We put each gender pronoun into a variable, like this (from Figure 17):

gender1_out = "him";

Here is some JavaScript for using these variables to fill in part of the story:

$("#first_name2_out").text(first_name2_in);
$("#gender2_out").text(gender2_out);

Figure 19. Filling in the story

The code puts the values from the variables into the appropriate <span>s.

There is one more step in the game flow:

  1. Browser: Show the form
  2. Player: Complete the form
  3. Player: Click the Go button
  4. Browser: Get the player's input

    If the form is not complete, show an error and stop.

  5. Browser: Fill in the blanks in the story
  6. Browser: Show the story

Figure 6 (again). Game flow

Here’s code to hide the input form, and show the output area.

$("#input_stuff").hide();
$("#story").show();

Figure 20. Hiding the input form and showing the story

I added something else to the end of the story:

Story output

Figure 5 (again). Story output

The Reset button just hides the output area (the story) and shows the input form again. This lets the user make a quick changes to the story.

Here’s the HTML and the JavaScript:

<div id="story">
...
  <p>
    <button id="reset_button" title="Show input fields again">Reset</button>
  </p>
</div>
...
$(document).ready(function() {
...
  $("#reset_button").click(function() {
    $("#story").hide();
    $("#input_stuff").show();
  });
});

Figure 21. The Reset button

Notice that the HTML for the <button> is inside the story element. So the user only sees it when the story is shown.

The JavaScript is simple. It hides the story, and shows the input form.

Remember that you can try the game. It isn’t a complete story. I just wanted enough to show you how it works.

Here’s all the JavaScript. It includes a few extra details.

$(document).ready(function() {
  $("#story").hide();
  $("#first_name1_in").focus();
  $("#go_button").click(function() {
    //Check that all the fields are completed.
    var first_name1_in = $("#first_name1_in").val();
    if ( first_name1_in == "") {
      alert("Please complete all fields.");
      $("#first_name1_in").focus();
      return;
    }
    var first_name2_in = $("#first_name2_in").val();
    if ( first_name2_in == "") {
      alert("Please complete all fields.");
      $("#first_name2_in").focus();
      return;
    }
    var color1_in = $("#color1_in").val();
    if ( color1_in == "") {
      alert("Please complete all fields.");
      $("#color1_in").focus();
      return;
    }
    var animal1_in = $("#animal1_in").val();
    if ( animal1_in == "") {
      alert("Please complete all fields.");
      $("#animal1_in").focus();
      return;
    }
    var animal2_in = $("#animal2_in").val();
    if ( animal2_in == "") {
      alert("Please complete all fields.");
      $("#animal2_in").focus();
      return;
    }
    //Get genders
    var gender1_out;
    if ( $("#gender1_in_male").is(":checked") ) {
      gender1_out = "him";
    }
    else {
      gender1_out = "her";
    }
    var gender2_out;
    if ( $("#gender2_in_male").is(":checked") ) {
      gender2_out = "he";
    }
    else {
      gender2_out = "she";
    }
    //Fill in the story
    $("#first_name1_out").text(first_name1_in);
    $("#first_name2_out").text(first_name2_in);
    $("#color1_out").text(color1_in);
    $("#animal1_out").text(animal1_in);
    $("#animal2_out").text(animal2_in);
    $("#gender1_out").text(gender1_out);
    $("#gender2_out").text(gender2_out);
    //Hide the input area
    $("#input_stuff").hide();
    //Show the story
    $("#story").show();
  });
  $("#reset_button").click(function() {
    //Hide the story
    $("#story").hide();
    //Show the input area
    $("#input_stuff").show();
  });
});

Figure 22. All of the JavaScript

Lines 2 and 3 are executed when the page loads. Line 2 hides the story. We only want the input form showing at the start. Line 3 puts the input focus on the first form field. The user is ready to type, without having to click on anything.

Notice that there are comments throughout the code. Comments are a Good Thing. When the code needs to be changed, the comments will help the person making the changes understand how the code works. S/he can then make changes quickly and accurately.

Context-specific Mad Libs

One of the nice things about Mab Libs is that you can customize them. You can match them to your organization.

Suppose you have characters on your Web site, like, I don’t know, Kieran, CC, and Renata. Instead of having the user type in a name, you could have him/her select from a set of existing names.

Here is some HTML and JavaScript for a story that only makes sense on CoreDogs.

<p>
  A first name.<br>
  <input type="radio" name="first_name1_in" id="first_name1_in_cc" value="cc" checked="true"> CC<br>
  <input type="radio" name="first_name1_in" id="first_name1_in_kieran" value="kieran"> Kieran<br>
  <input type="radio" name="first_name1_in" id="first_name1_in_renata" value="renata"> Renata<br>
</p>
...
<p>
  <span id="first_name1_out"></span> was walking in the park one day,
  humming to <span id="gender1_out"></span>self. ...
</p>
...
$("#go_button").click(function() {
  var first_name1_out;
  var gender1_out;
  if ( $("#first_name1_in_cc").is(":checked") ) {
    first_name1_out = "CC";
    gender1_out = "her";
  }
  if ( $("#first_name1_in_kieran").is(":checked") ) {
    first_name1_out = "Kieran";
    gender1_out = "him";
  }
  if ( $("#first_name1_in_renata").is(":checked") ) {
    first_name1_out = "Renata";
    gender1_out = "her";
  }
  ...
  $("#first_name1_out").text(first_name1_out);
  $("#gender1_out").text(gender1_out);
  ...
});

Figure 23. Context-specific Mad Lib

This creates:

CoreDogs names

Figure 24. CoreDogs names

These radio buttons replace both the first name field and the gender radio buttons. We can compute gender. We don’t need to ask the user.

You can customize Mad Libs to your own company, school, etc. Use people and things that make sense in your context.

Other ways to add games

This lesson showed how to create a Mad Lib for your Web site. But there are many other ways to add games.

Sites like FreeGamesJungle have Flash games you can add to your site. There are also plenty of JavaScript games available. The JavaScript Source has a bunch.

JavaScriptGaming has some very interesting stuff. Including some first-person shooters in JavaScript! They show how capable JavaScript is in today’s browsers.

Summary

This lesson showed you:

  • What a Mad Lib is.
  • The flow of a Mad Lib game.
  • How to create the input form and output story for a Mad Lib.
  • How to write the JavaScript code for a Mab Lib.

What now?

Let’s finish up by looking at some other widgets you could add to your site.

More widgets

Where are we?

You’ve seen how to add search widgets, social widgets, and games to your site. Let’s look at some others.

This lesson’s goals

By the end of this lesson, you should:

  • Be able to add YouTube videos to your site.
  • Be able to make a Flickr badge.
  • Know where to get more fun widgets!

YouTube videos

YouTube gives you HTML code to add a video into your page. Copy their code, and paste it into your HTML.

Visit a YouTube page, like this one. You’ll see an embed button:

Embed button

Figure 1. Embed button

This is what I saw at the time of writing. It may have changed by now.

YouTube will give you HTML code you can copy and paste into your own HTML.

Here’s a page I’ve prepared for the video:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Video</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
      body {
        background-color: #FFFFDD;
        font-family: sans-serif;
        font-size: 14px;
      }
      #video_container {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <h1>Video</h1>
    <p>Here is a video, explaining why teaching Web stuff is hard.</p>
    <div id="video_container">

    </div>
  </body>
</html>

Figure 2. Page ready for video

I’m going to put the video code in line 21.

Notice that I’ve made a container for the video, in line 20. Why? Check the CSS. I’ve centered the container, so the video will be centered on the page.

Here’s the code I got from Google:

<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/F0ue3BxvMAU" frameborder="0" allowfullscreen></iframe>

Figure 3. Code from Google

I pasted into line 21, and saved. You can see the result.

Exercise: Add a YouTube video

Find a YouTube video to put on your site. If you’re stuck for ideas, try this one.

Upload your new page to your server. Put the URL below.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

A Flickr badge

Flickr is a photo sharing service. Here’s a badge I made:

www.flickr.com

To make it, I went to Flickr’s badge creation page. I choose one of my photos:

Choosing a photo

Figure 4. Choosing a photo

Then I clicked the Next button at the bottom of the page:

The Next button

Figure 5. The Next button

Flickr asked me a few more questions, like how many photos I wanted to display. Then I got some code:

The Flickr code

Figure 6. The Flickr code

I copied it into my HTML. All done!

Even more widgets

There are a bazillion other widgets you can add. Weather reports, polls, news headlines, stock information… you name it.

Here are some places to get widgets:

Exercise: Add the Dog Breed widget

Go to Google’s gadget directory. Find the Dog Breeds gadget from PuppyFinder.Com. Add it to your site.

Enter the URL of the page on your server.

(Log in to enter your solution to this exercise.)

Can't find the 'comment' module! Was it selected?

Summary

It’s easy to add YouTube videos to your site. Go the YouTube page for the video you want to show, and copy-and-paste some code.

You can use photos from your Flickr stream to create a simple badge Flickr give you the code.

There are bazillions of other fun widgets!