1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Unobtrusive Hangman

I am sure you remember playing hangman when you were younger where one person chose a word or phrase and the other person had to guess which letters that it contained. Every time they guessed wrong they were one step closer to being hanged. Enough wrong guesses before solving the word or phrase and they lost the game.

Let's look at having JavaScript play this same game with us on the web page by setting up an array of possible answers and having JavaScript use Math methods to select one of the answers at random and String and Function methods to perform the other necessary processing to allow the script to play the game. We'll add the game using unobtrusive methods so that those visitors with JavaScript disabled will not even notice that it isn't there. We'll also wrap everything except the opts array that contains our answers within an anonymous function to minimise the chances of interference with any other scripts on the page.

We'll need three pieces of static code for this script (one each of HTML, stylesheet, and JavaScript) as well as a dynamically generated JavaScript with obfuscated versions of the words you want to use (we'll do that to prevent people cheating by viewing the source). We'll also need the Hangman Images that the game will display.

Copy and save the above content as hang.htm.

There are four lines in this code that allow our script to work. You can change anything else in the HTML to add whatever else you want in the page as long as the four lines remain intact.

  • The reference to the hangq.js script will refer to our dynamically generated file containing the word the script uses as answers. You can change that name and create multiple files if you want multiple hangman games using different answers.
  • The second script hangman.js is the static portion of the script that does all the actual work. You'll find the code for that below.
  • The stylesheet that defines our page appearance is called hangman.css and is linked into the HTML using a link tag. Again the code is below.
  • This div tag with id="hang" identifies the spot in the page where the hangman game is to appear.

The styles required for the hangman game are fairly simple and control how the game will look. You need to save the following in a file called hang.css.

Copy and save the above content as season.css.

The next and probably the most important part of the code is the JavaScript which does all the work. This needs to be saved as hangman.js.

You will not need to change anything in this code.

All that remains now is to generate the second JavaScript file with all of the answers to our hangman game.

See More About

©2017 About.com. All rights reserved.