Day 4 — JavaScript: Making It Interactive
Variables · Functions · Selecting elements · Click events
⬇ Today's slides (PDF)Schedule
| Time | Activity |
|---|---|
| 0:00 – 0:45 | Lecture: the console, variables, functions, querySelector |
| 0:45 – 1:30 | Project: a button that changes the page |
| 1:30 – 1:40 | Break |
| 1:40 – 3:00 | Project: add one interactive feature to your site |
What JavaScript Is
HTML is content. CSS is style. JavaScript is behavior — it makes things happen when the user does something. It runs right in the browser, no install needed.
Add JavaScript to your page with a <script> tag, usually right before </body>:
<script>
console.log("Hello from JavaScript!");
</script>
</body>
console.log() messages and any errors show up. Keep it open while you work.
Give Your JavaScript Its Own File
Just like style.css holds all your CSS, keep all your JavaScript in one file — script.js — instead of a big <script> block in your HTML. It's cleaner and one file can run on every page.
Link it right before </body>:
<script src="script.js"></script>
</body>
Then make script.js next to your HTML and put your code in it — no <script> tags inside the file, just the JavaScript:
// script.js
console.log("Hello from my own file!");
</body>) so the page exists when your code runs. Every code example below can live in script.js — drop the surrounding <script> tags.
Quick Reference
Variables
let score = 0; // let = a value that can change
const name = "Alex"; // const = a value that won't change
let colors = ["red", "blue", "green"]; // an array (a list)
Functions
function sayHi() {
console.log("Hi there!");
}
sayHi(); // runs the function
Grabbing an Element from the Page
querySelector finds an element using a CSS selector, so you can change it. This runs inside a <script> tag, placed after the element it grabs:
<h1 id="title">Hello</h1>
<script>
const title = document.querySelector("#title"); // the element with id="title"
title.textContent = "New text!"; // change its text
title.style.color = "red"; // change its style
</script>
Reacting to a Click
const btn = document.querySelector("#btn");
btn.addEventListener("click", () => {
console.log("The button was clicked!");
});
Project — A Button That Changes the Page
Type this whole example into a fresh HTML file and open it. Click the button and watch the count go up.
Starter Code
<button id="btn">Click me</button>
<p id="output">You clicked 0 times</p>
<script>
let count = 0;
const btn = document.querySelector("#btn");
const output = document.querySelector("#output");
btn.addEventListener("click", () => {
count = count + 1;
output.textContent = "You clicked " + count + " times";
});
</script>
Project — Add One Interactive Feature
Pick one feature to add to your own site. Each one builds on the click example above.
- Dark-mode toggle — a button that adds/removes a CSS class on
<body> - Random quote / joke button — pick a random item from an array and show it
- Color changer — a button that randomizes the background color
- Name greeting — the user types their name and the page says hi
Example — Random Joke Button
<button id="jokeBtn">Tell me a joke</button>
<p id="joke"></p>
<script>
const jokes = [
"Why do programmers hate nature? Too many bugs.",
"Why was the computer cold? It left its Windows open.",
"There are 10 kinds of people: those who know binary and those who don't."
];
const btn = document.querySelector("#jokeBtn");
const output = document.querySelector("#joke");
btn.addEventListener("click", () => {
const random = Math.floor(Math.random() * jokes.length);
output.textContent = jokes[random];
});
</script>
Stretch Goals
- Remember the user's dark-mode choice with
localStorage - Pull a live joke or quote from a free API with
fetch() - Build a tiny quiz that scores the answers
- Make an image slideshow with next / previous buttons
- Add a "scroll to top" button that appears once you scroll down
Full Solutions — Stuck on One?
Here's complete, working code for the other three features. Read it, type it, then change it to fit your site. Each one is just the click example from above with different code inside the addEventListener.
Dark-Mode Toggle
Add a class to <body> when clicked; style that class in your CSS.
<button id="themeBtn">Toggle dark mode</button>
<script>
const btn = document.querySelector("#themeBtn");
btn.addEventListener("click", () => {
document.body.classList.toggle("dark");
});
</script>
And in your style.css:
body.dark {
background: #111;
color: #eee;
}
Color Changer
Pick a random color and set it as the background.
<button id="colorBtn">Surprise color</button>
<script>
const colors = ["#f94144", "#f3722c", "#f8961e", "#43aa8b", "#577590"];
const btn = document.querySelector("#colorBtn");
btn.addEventListener("click", () => {
const i = Math.floor(Math.random() * colors.length);
document.body.style.background = colors[i];
});
</script>
Name Greeting
Read what the user typed into a text box and greet them.
<input id="nameBox" placeholder="Your name">
<button id="greetBtn">Say hi</button>
<p id="greeting"></p>
<script>
const box = document.querySelector("#nameBox");
const btn = document.querySelector("#greetBtn");
const out = document.querySelector("#greeting");
btn.addEventListener("click", () => {
out.textContent = "Hi, " + box.value + "! Welcome to my site.";
});
</script>
Common Mistakes
- Nothing happens on click. Open the console (F12) — a red error usually points right at the line. Most often it's the next one:
- Selector doesn't match.
querySelector("#btn")needsid="btn"in the HTML. The#is for ids,.is for classes — same as CSS. - Script runs before the element exists. Put your
<script>right before</body>, after the elements it uses, so they're on the page first. =vs===. Use=to store a value, but===to compare two values in anif.- Missing quotes. Text needs quotes:
"click", notclick. Variable names and numbers don't. - Forgot to call the function. Defining
function sayHi() { }does nothing until you actually run it withsayHi().