JavaScript City

Number Guess

This script allows you to give your visitors a "number guess" game. It will choose a random number between one and a number of your choosing (default is 1-10). The viewer enters a number, clicks the button to guess, and is given feedback on the guess and how many chances are left to guess correctly.

Script Code

Grab a copy of the file below and place it in the same directory as the Web page on which you will use the script (if you wish to place the script file in a different directory you will need to make the necessary adjustments to the src attribute of the script tag that calls it).

sgames002.js

The code below should be placed between the <body> and </body> tags where you want the form to appear.

Example

A working sample of the script is shown below. It uses the default settings: 3 chances to guess a number between 1 and 10.


Options

You can change the appearance of the text and form by using the appropriate IDs in your your style sheet and by editing the labels in the HTML as desired.

Most of the options can be edited using the variable values near the top of the script file:

/* Maximum number */
var m_num = 10;
/* Number of guesses the viewer has */
var num_chances = 3;
/* Message displayed after a correct guess */
var you_win = "Correct! You Win!";
/* Message displayed after after all guesses have been used */
var you_lose = "Sorry! You lose!";
/* Message displayed if user guesses too low */
var need_higher = "I\'m looking for a higher number.";
/* Message displayed if user guesses too high */
var need_lower = "I\'m looking for a lower number.";

If you need to use single or double quotation marks within a quote, you should write them with a backslash before them (i.e. \" and \') in order to avoid JavaScript errors.

Accessibility

Setting the form action to link to a backup server-side script that performs the same function should do the trick for those without JavaScript.


eXTReMe Tracker