{JavaScript}

Fortune Teller

To start, open this template:

   codepen.io/mslim/pen/BRYQqR

And then "Fork" it

(makes a copy)

Don't sign up if you're under 13

Just "Save as Anonymous"

HTML & CSS are already in place;

We will add JavaScript here

We use JavaScript (JS) to write functions. A function is a block of code that performs a task.

 

A JS function runs (executes) when something calls it.

Write a function called go()
which creates a pop-up alert that says "hi"

function go() {
  alert("hi");
}

Next, add onclick="go()" to the existing HTML <button> tag.

This tells the browser to call the "go()" function whenever the button is clicked.

<div>
  <form>
    What is your burning question?<br><br>
    <input type="text" id="question"><br><br>
    <button onclick="go()">
        Reveal your destiny
    </button>
  </form>
</div>

Click the button; it should say "hi"

Don't forget to save as you go

Changes are saved to your personal URL. Paste it somewhere so you can get to it later!

Now let's define an array (list) of possible "fortunes"

We will define this array as a const (constant)

function go() {
  alert("hi");
}

const fortunes = ["No", "Definitely", 
"Maybe", "Definitely maybe", 
"Stop trying to predict the future"]

Next, write a function called pickRandom(fortunes) that returns a random value from the fortunes array

function go() {
  alert("hi");
}

const fortunes = ["No", "Definitely", 
"Maybe", "Definitely maybe", 
"Stop trying to predict the future"]

function pickRandom(fortunes) {
  return fortunes[Math.floor(Math.random()*fortunes.length)];
}

Now instead of "hi" in the go() alert, let's use the value returned by pickRandom(fortunes)

 

 

function go() {
  alert(pickRandom(fortunes));
}

const fortunes = ["No", "Definitely", 
"Maybe", "Definitely maybe", 
"Stop trying to predict the future"]

function pickRandom(fortunes) {
  return fortunes[Math.floor(Math.random()*fortunes.length)];
}

What if someone clicks the button without typing anything?

We can modify the go() function to check if there's an input,
and then use an if/else statement to show different alerts depending on the case.

 

 

function go() {
  // get what's currently in the text input
  var input = document.getElementById("question").value;
  // if the # of letters in the input is greater than 0
  if (input.length > 0) {
    alert(pickRandom(fortunes));
  }
  // otherwise, do this
  else {
    alert("Ask a question to get an answer.");
  }
}

JavaScript Fortune Teller

By Michelle Lim

JavaScript Fortune Teller

  • 1,605