This example of JavaScript uses a combination of alerts, prompts, random number generation, and a redirect to create a script that interacts with the user when a button is clicked. Sample code for an alert looks like this:
alert("This program has performed an illegal operation and will be shut down.");
This displays the message "This program has performed an illegal operation and will be shut down" in a popup. To prompt the user for information, you do the following:
var name = prompt("What is you name?","John Smith");
This asks the user for their name (automatically populating the field in the popup for the prompt with John Smith) and stores it in the variable name. Random numbers can be done using the following:
var rand = Math.floor(Math.random() * 3);
Math.random() generates a random decimal number between 0 and 1; in this example it is multiplied by 3 (to get a random number between 0 and 3) and then Math.floor rounds the decimal to the nearist integer, which is then stored in the variable rand. An if statement can then be used to generate different outcomes based on the random number generated.
Redirects are accomplished by setting window.location equal to the URL of a page or image, shown in the code below.
window.location = "bridge3.jpg";
The Bridge of Death


Complete code for demo
The JavaScript
<script type="text/javascript">
function displayPrompt() {
alert("STOP! He who would cross the bridge of death must answer me these questions three, err the other side he see.");
var name;
name = prompt("WHAT is you name?","");
if (name !== null && name != "") {
var quest;
quest = prompt("WHAT is your quest?","");
if (quest !== null && quest!= "") {
var rand;
rand = Math.floor(Math.random() * 3);
var ans;
if(rand === 0) {
ans = prompt("WHAT is you favorite color?","");
if(ans == "Blue" || ans == "blue") {
alert("Well of you go.");
}
else {
alert("WRONG!");
window.location = "bridge3.jpg";
}
}
else if(rand === 1) {
ans = prompt("WHAT... is the capital of Assyria?","");
if(ans == "Nineveh") {
alert("Well off you go.");
}
else {
alert("WRONG!");
window.location = "bridge3.jpg";
}
}
else {
ans = prompt("WHAT... is the airspeed velocity of an unlaiden swallow?","");
if(ans == "What do you mean? African or European swallow?") {
alert("What? I don't know that! ARGHHHHHHHHHHHHHH!");
}
else {
alert("WRONG!");
window.location = "bridge3.jpg";
}
}
}
else {
alert("WRONG!");
window.location = "bridge3.jpg";
}
}
else {
alert("WRONG!");
window.location = "bridge3.jpg";
}
}
</script>
The Button
<input type="button" onclick="displayPrompt()" value="Cross The Bridge of Death!" />