1 / 15

User Input & Basic Interaction

Making Your Webpage Interactive

Lesson 5: Your First Interactive Program

From static to interactive experiences

What We'll Learn Today

Why User Input?

Websites become truly useful when they respond to people!

How Can We Get Input?

Today: We'll use prompt()

Using prompt()

let name = prompt("What is your name?");

Shows a box asking the user for input. Stores the answer in a variable.

Using alert()

alert("Hello, " + name + "!");

Shows a message box to the user.

Making Decisions: if/else

if (age >= 18) {
  alert("You are an adult!");
} else {
  alert("You are a minor!");
}

Decide what happens based on user input.

Project: Age Calculator (Step 1)

let birthYear = prompt("What year were you born?");

Ask the user for their birth year.

Project: Age Calculator (Step 2)

let currentYear = new Date().getFullYear();
let age = currentYear - birthYear;

Calculate the user's age.

Project: Age Calculator (Step 3)

alert("You are " + age + " years old.");

Show the result to the user!

Project: Simple Quiz

let answer = prompt("What is 2 + 2?");
if (answer == 4) {
  alert("Correct!");
} else {
  alert("Try again!");
}

Respond to the user's answer.

Activity: Try It Yourself!

Write a program that asks for your favorite color and responds with a message.

let color = prompt("What's your favorite color?");
alert("Nice choice! " + color);

Common Mistakes

Challenge: Make Your Own Interactive Page

Ideas:

Show your code to a friend!

Summary & Homework

Homework

Write a program that asks for your birth year and calculates your age in 2100.