Got the code? Welcome, builder!
You're heading into Invent the Future — instructors hand out the access code on day one.
You're heading into Invent the Future — instructors hand out the access code on day one.
Your button does one thing. Conditionals let it do different things based on a condition — how many times it's been clicked, what the user typed, what time it is.
A conditional checks whether something is true and runs different code depending on the answer:
let clicks = 0;
btn.addEventListener("click", () => {
clicks = clicks + 1;
if (clicks < 3) {
heading.textContent = "You clicked " + clicks + " times.";
} else if (clicks < 6) {
heading.textContent = "Okay, you're really clicking.";
} else {
heading.textContent = "Stop.";
}
});
The flow: check the if condition first. If it's true, run that block. If not, check the else if. If that's true, run it. If nothing matched, run the else.
| Operator | Meaning | Example |
|---|---|---|
=== |
Equal (value and type) | clicks === 3 |
!== |
Not equal | mood !== "happy" |
< |
Less than | clicks < 10 |
> |
Greater than | score > 50 |
<= |
Less than or equal | age <= 17 |
>= |
Greater than or equal | temperature >= 20 |
Always use === rather than ==. The double equals (==) does type coercion and produces surprising results: 0 == "0" is true in JavaScript. Triple equals does not coerce: 0 === "0" is false. Write === by default.
An <input> element lets users type something. Add one to your HTML:
<input type="text" id="mood-input" placeholder="How are you feeling?">
In JavaScript, .value reads whatever the user typed:
const input = document.querySelector("#mood-input");
btn.addEventListener("click", () => {
const mood = input.value;
heading.textContent = "You said: " + mood;
});
.value always returns a string. If the user types 42, JavaScript reads it as "42", not the number 42. For string comparisons this doesn't matter. For math, convert it first: Number(input.value).
Combine input and conditionals to build a page that changes based on what the user types:
const input = document.querySelector("#mood-input");
const heading = document.querySelector("h1");
btn.addEventListener("click", () => {
const mood = input.value;
if (mood === "happy") {
document.body.style.backgroundColor = "gold";
heading.textContent = "Shine bright.";
} else if (mood === "sad") {
document.body.style.backgroundColor = "lightblue";
heading.textContent = "It's okay to feel that way.";
} else if (mood === "angry") {
document.body.style.backgroundColor = "tomato";
heading.textContent = "Take a breath.";
} else {
document.body.style.backgroundColor = "lightgray";
heading.textContent = "Tell me more.";
}
});
Stretch: Make the input case-insensitive so "Happy" and "HAPPY" both work:
const mood = input.value.toLowerCase();
Add a fourth mood of your choice with its own colour and message.