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.
HTML gives content structure. CSS gives it style. JavaScript makes it respond to whoever's using it.
The three work together but live in separate files. You link a .js file the same way you link a .css file.
Create a file called script.js next to your index.html. Then add this line to the <head> of your HTML, above the closing </head> tag:
<script src="script.js" defer></script>
The defer attribute tells the browser to wait until the page has loaded before running the script. Without it, JavaScript runs before the page elements exist and document.querySelector returns null, which is a confusing first bug.
To confirm the link works, open script.js and add one line:
console.log("Hello from JavaScript!");
Save, refresh the browser, open the DevTools console (right-click anywhere on the page → Inspect → Console tab), and you should see your message. That's JavaScript running in the browser.
Variables store values you want to use later.
const name = "Leila";
let clicks = 0;
const is for values that will not change. let is for values that will. When in doubt, start with const and switch to let if you get an error.
document.querySelector finds an element on the page using the same selector syntax as CSS:
const heading = document.querySelector("h1"); // finds the first <h1>
const btn = document.querySelector("#my-button"); // finds id="my-button"
const card = document.querySelector(".card"); // finds the first class="card"
Once you have an element, you can change it:
heading.textContent = "You clicked the button!";
addEventListener tells an element to run some code when something happens:
const btn = document.querySelector("#greet-btn");
const heading = document.querySelector("h1");
btn.addEventListener("click", () => {
heading.textContent = "You clicked!";
});
"click" is the event type. Other common ones: "input", "submit", "mouseover". The () => { ... } part is the function that runs when the event fires — the code inside the braces is what actually happens.
The console is your best debugging tool. Open it with right-click → Inspect → Console, or the keyboard shortcut Cmd+Option+J (Mac) / Ctrl+Shift+J (Windows).
Two things to do with it:
console.log(value) — print anything you want to inspect.When your page isn't doing what you expect, the first question is always: "What does the console say?"
Add a button to your page:
<button id="greet-btn">Say Hi</button>
Then wire it up in script.js so clicking it changes something visible — a heading, a background colour, a counter. Use querySelector to grab the elements and addEventListener to respond to the click.
textContentdocument.body.style.backgroundColor = "gold"