Web Technologies 2026 · BiUH · Lesson 5
What makes a page respond
Where it runs · values · functions · the DOM · events · state · when it breaks
What this lesson covers
| 1 · Where it runs | the script tag, and the Console |
| 2 · Values | numbers, text, lists — and the names you give them |
| 3 · Functions | work you describe once and run many times |
| 4 · The DOM | the page, as something JavaScript can change |
| 5 · Events | the moment something happens |
| 6 · State | what the page remembers — and why the screen must follow it |
| 7 · When it breaks | the red message, and reading code you did not write |
You have used most of this already — in nav.js and in your useless machine. This lesson gives each part its name.
JavaScript says what things do.
HTML is the content. CSS is the look. JavaScript is behaviour: it waits for something to happen, then it changes the page.
It is the last of the three layers. If it fails, the page should still work — with less to do, but nothing missing.
You are not starting from zero
fetch got a file, getElementById found the header,
innerHTML filled it. Then a function, load(file, target),
so you could do it twice.
A control that waits for an event, a state that goes on and off, and a timer that brings it back. Written with AI — and every line explained.
Those are the words of this lesson. Now each one gets a slide of its own.
Where it came from
let, const, arrow functions — the JavaScript you write todayWhen AI writes var instead of let and const, it is writing JavaScript from before 2015. It still works — but it is not how you write it now.
Part 1
A file, one tag, and a window that shows you everything
Getting it into the page
<script> tag goes.<head> <script src="main.js"></script> </head>
Runs before the body exists. Every element it looks for is not there yet.
<script src="main.js"></script> </body>
What you did in Lesson 4. The page is read; then the script runs.
<head> <script src="main.js" defer></script> </head>
Loads at once, waits to run until the whole page is read.
The browser reads HTML from top to bottom and runs a script the moment it reaches it. That is the whole rule.
One .js file, linked from every page — the same reason as one .css file. Change it once; the browser downloads it once.
Try it now · two minutes
F12 — on a Mac ⌥⌘J — then the Console tab. Type each line and press Enter:
2 + 2
'Web' + 'Tech'
document.title
document.title = 'I changed this'
document.querySelector('.slide.on').style.background = 'pink'
Look at the browser tab after line 4, and at this slide after line 5. You changed a live page.
Now reload. It is all gone: you changed the page in your browser, not the file on the server.
Part 2
What JavaScript works with
Five kinds of value
| Type | Looks like | For |
|---|---|---|
| number | 42 3.5 -1 | counting, measuring, prices |
| string | 'Hello' "Hello" `Hello` | any text — quotes at both ends |
| boolean | true false | yes or no: is the menu open? |
| array | ['Home', 'Quotes', 'Project'] | a list, in order |
| object | { name: 'Li Wei', group: 2 } | one thing, described by named values |
Two more mean "nothing here": null and undefined. You will meet them mostly in error messages — Part 7.
Give a value a name
const for what stays. let for what changes.const siteName = 'My Site'; // never changes let likes = 0; // will change likes = likes + 1; // fine: likes is now 1 siteName = 'Other Site'; // TypeError: Assignment to constant variable.
Start with const. Change it to let only when the value
has to change.
Names are written likeThis, and capitals count:
likes and Likes are two different names.
var is the old way, from before 2015. It works, but it has surprises that let and const were made to fix.
Text with values inside it
${ }.const name = 'Li Wei';
const count = 3;
'Hello, ' + name + '! You have ' + count + ' likes.' // the old way
`Hello, ${name}! You have ${count} likes.` // the same text
Inside backticks, ${ } puts a value into the text. No plus
signs, no missing spaces.
The backtick ` is top left on most keyboards, below Esc. Three kinds of quotes make a string; only the backtick understands ${ }.
One trap worth knowing
'5' + 1 // '51' — text joined to text
'5' * 2 // 10 — * only works on numbers, so it converts
Number('5') + 1 // 6
'5' == 5 // true — == converts first, then compares
'5' === 5 // false — === compares exactly
Everything a visitor types into a field arrives as text —
digits too. Convert it with Number() before you calculate.
Compare with ===. Always.
Lists and records · your quotes as data
const quotes = [
{ text: 'The best time to plant a tree was twenty years ago.', author: 'Chinese proverb', likes: 12 },
{ text: 'Simplicity is prerequisite for reliability.', author: 'Edsger Dijkstra', likes: 4 }
];
quotes.length // 2
quotes[0].author // 'Chinese proverb'
quotes[1].likes + 1 // 5
An array is a list in square brackets, counted from 0. An object is a record in curly brackets: names, colons, values. A dot reads one value out.
JSON — the format data travels in between servers and browsers — is this same notation, with double quotes everywhere.
Part 3
Describe the work once. Run it whenever you need it.
You wrote one in Lesson 4
function load(file, target) {
fetch(file)
.then(r => r.text())
.then(html => {
document.getElementById(target).innerHTML = html;
});
}
load('nav.html', 'site-header');
load('footer.html', 'site-footer');
load | the name |
(file, target) | the parameters — the parts that change each time |
{ … } | the work |
load('nav.html', …) | run it now, with these values |
Writing the function does nothing. Calling it — the last two lines — is what runs it.
A function can hand something back
returnfunction plural(count, word) {
if (count === 1) {
return `${count} ${word}`;
}
return `${count} ${word}s`;
}
plural(1, 'like') // '1 like'
plural(12, 'like') // '12 likes'
return gives a value back to whoever called the function —
and ends it there. if decides which line is reached.
One function, used on every like button of the site. Fix it once, and every button is right.
The same thing, shorter
=>function double(n) {
return n * 2;
}
const double = (n) => n * 2;
You will see arrows most where a function is handed to something else, to run later:
button.addEventListener('click', () => {
// runs on every click
});
() => { … } is a function with no name. You give it to addEventListener; the browser runs it — not you.
Two more shapes you will read
ifif (quote.likes > 10) {
card.classList.add('popular');
} else {
card.classList.remove('popular');
}
for … offor (const quote of quotes) {
console.log(quote.author);
}
if runs a block only when something is
true. for … of goes through a list, one item at a time.
AI often writes quotes.forEach(quote => …) instead. The same loop, written as a function.
Part 4
The page, as something JavaScript can change
The browser does not keep your HTML. It builds a tree.
document └─ html ├─ head │ └─ title └─ body ├─ header#site-header ├─ main │ └─ article.quote │ ├─ blockquote │ └─ button.like └─ footer
DOM — Document Object Model. Every element becomes an object JavaScript can find, read and change.
Change the tree, and the screen follows at once.
View source shows the HTML that arrived. DevTools → Elements shows the tree as it is now. Once JavaScript has changed the page, the two differ.
Step one · find it
document.querySelector('.like') | the first element that matches |
document.querySelectorAll('.quote') | all of them, as a list |
document.getElementById('site-header') | the one with that id — no # here |
querySelector takes any CSS selector:
'#site-nav', 'nav a', '.quote.popular'.
Lesson 3 pays off here.
Nothing matches? You get null — and the next line fails. That is the most common JavaScript error there is. Part 7.
Step two · change it
| Write | What changes |
|---|---|
el.textContent = 'Saved' | the text inside it |
el.classList.add('open') · .remove · .toggle | its classes — and so, through CSS, its look |
el.setAttribute('aria-expanded', 'true') | any attribute |
img.src = 'photo-2.webp' | the common attributes, directly |
el.hidden = true | hides it — and shows it again with false |
el.style.color = 'red' | one CSS property, written inline |
el is just a name: whatever querySelector found and you kept in a const.
The rule that keeps the three languages apart
button.style.color = 'white'; button.style.background = '#c2410c'; button.style.borderColor = '#c2410c';
Change the colour later, and you are searching through a script for it.
button.classList.add('liked');
.like.liked {
color: white;
background: #c2410c;
}
JavaScript decides when. CSS decides how it looks.
AI often writes the style.… version. It works — ask it to switch a class instead.
Two ways to put text in · one is a security hole
textContent, or innerHTML?output.textContent = field.value;
Puts in text. Whatever it contains, it is shown as letters.
output.innerHTML = field.value;
Reads the text as HTML and builds elements from it.
If a visitor types <img src=x onerror="…">
and you put it in with innerHTML, the browser runs their code on
your page. That attack is called XSS — cross-site scripting.
innerHTML with your own nav.html, as in Lesson 4, is fine. You wrote that HTML; a stranger did not.
Step three · build new elements from data
const list = document.querySelector('#quote-list');
for (const quote of quotes) {
const item = document.createElement('li');
item.textContent = `${quote.text} — ${quote.author}`;
list.append(item);
}
The quotes live in one array; the HTML is made from it. Add a quote to the array, and the page has one more.
In Vue this whole loop is one attribute, v-for — next lesson. Here you can see what it does for you.
Part 5
Nothing happens until something happens
Listen for it
const button = document.querySelector('.like');
button.addEventListener('click', () => {
console.log('clicked');
});
buttonwhich element'click'which event() => { … }what to do — every time it happensYou do not call that function. You hand it to the browser, and the browser calls it — once for every click.
The events you will actually use
| Event | Happens when |
|---|---|
click | a button or link is used — by mouse, finger, or Enter and Space on the keyboard |
input | a text field changes — at every letter typed |
change | a checkbox, a select or a slider has changed |
submit | a form is sent |
keydown | a key is pressed — event.key says which |
The keyboard part of click only comes free on a real <button>. A <div> with a click listener cannot be reached with Tab at all.
Try it · every event, as it happens
One action can fire several events: pressing Send
is a click on the button, then a submit of the form.
Five addEventListener calls drive that log. Nothing here is sent anywhere.
Three ways to listen · use one
<button onclick="like()">
JavaScript inside an HTML attribute. Two languages in one line, and hard to find.
button.onclick = like;
One per element. A second one silently replaces the first.
button.addEventListener('click', like);
In the .js file, where JavaScript belongs. As many as you need.
Use addEventListener. Always.
AI writes onclick="…" surprisingly often. Ask it to move the code into the .js file.
Forms · let HTML check first
<form> <label>Name <input name="name" required minlength="2"></label> <label>Email <input name="email" type="email" required></label> <button>Send</button> </form>
Leave a field empty or type an address without @, and the
browser refuses to send the form and says why — in the visitor's own language.
JavaScript only for what HTML cannot say: "the two passwords must match", "pick at least one".
The same rule as the three layers: HTML first. Then add JavaScript where HTML runs out.
Forms · stop the browser's own reaction
event.preventDefault()const form = document.querySelector('#contact');
const message = document.querySelector('#message');
form.addEventListener('submit', (event) => {
event.preventDefault(); // do not send it, do not reload
message.textContent = 'Thank you — we will reply soon.';
form.reset(); // empty the fields again
});
A sent form normally loads a new page. preventDefault() keeps
the visitor where they are, so your code decides what happens next.
submit only fires once the HTML checks have passed. And a static site has no server to receive the data — that is a server question, for the Frameworks lesson.
Part 6
What the page remembers, right now
State is a value. The screen is a copy of it.
| The question | The state | Kept in |
|---|---|---|
| Is the menu open? | true / false | a class on the nav |
| How many likes? | 12 | let likes |
| Which photo is shown large? | 3 | let current |
| Light or dark? | 'dark' | a class on the body |
| Is the machine switched on? | true / false | the checkbox itself |
If you can name the state of your feature, you understand it. If you cannot, nobody can.
The pattern · change the state, then draw it
let likes = 0;
const button = document.querySelector('.like');
function render() {
button.textContent = `♥ ${likes}`;
button.classList.toggle('liked', likes > 0);
}
button.addEventListener('click', () => {
likes++; // 1 · change the state
render(); // 2 · draw it again
});
render(); // and once at the start
The best time to plant a tree was twenty years ago. The second best time is now.
Click the heart. The value changes first; the button only shows it. toggle('liked', likes > 0) adds the class when the second part is true, and removes it when it is not.
The screen has to follow the state — every time.
In plain JavaScript that is your job: change, then render().
Forget it in one place, and the page shows something that is no longer true.
Frameworks were invented to do this for you. That is Lesson 6.
Later, not now · the useless machine
setTimeoutconst toggle = document.querySelector('#switch'); // a checkbox
toggle.addEventListener('change', () => {
if (!toggle.checked) return; // only when it was switched on
setTimeout(() => {
toggle.checked = false; // the machine switches itself off
}, 800); // after 800 milliseconds
});
setTimeout(function, ms) runs a function once, later.
! means "not". The last state is the first state.
Changing checked from code does not fire another change event — so the machine does not argue with itself.
State that survives a reload
localStoragelet likes = Number(localStorage.getItem('likes')) || 0; // read it back, or start at 0
button.addEventListener('click', () => {
likes++;
localStorage.setItem('likes', likes); // keep it
render();
});
A variable is gone when the page reloads. localStorage keeps a
value in this browser, on this device — and gives it back as text.
Only this visitor sees it. A like count that everyone shares needs a server and a database — not a static site.
Part 7
Read the red message. It tells you where.
HTML and CSS forgive. JavaScript stops.
A broken tag or CSS rule is skipped, and the rest still works. In JavaScript, everything after the error does nothing — so one typo can switch off every feature in the file.
Click main.js:4 and DevTools opens the file at that line.
The button looks right but does nothing? That is JavaScript. Open the Console first.
The five you will meet
| The Console says | It usually means | Look at |
|---|---|---|
Cannot read properties of null | querySelector found nothing | the selector · the script runs too early · the element comes later, by fetch |
likse is not defined | a name spelled two ways | the spelling, and the capitals: queryselector ≠ querySelector |
Unexpected token · missing ) | a bracket, quote or comma is missing — the whole file stops | that line, and the one above |
main.js … 404 (Not Found) | the src path is wrong | the folder and the capitals in <script src> |
Failed to fetch · CORS | the page was opened with file:// | open it with Live Server — Lesson 4 |
Read the message before you paste it anywhere. Half the time it already says the answer.
No red message, but nothing happens
console.log is your flashlight.button.addEventListener('click', () => {
console.log('clicked', likes); // does this run? what is likes right now?
likes++;
render();
});
No error means the code runs — just not the way you think.
Print what you are not sure of. If clicked never appears, the listener
is on the wrong element.
Take the console.log lines out before you hand in.
Part 7 · the habit that matters most
Most JavaScript you will meet, you did not write.
A library, a tutorial, a classmate — and more and more often, an AI. Reading it is the skill this course is built around.
Three questions for any interactive code
querySelector or getElementByIdaddEventListener and the word in quotesThe element, the event, the change.
Almost every interactive piece of the web is these three. Find them first; the rest is detail.
Read it · an AI wrote this dark-mode switch
const toggle = document.querySelector('#theme-toggle');
toggle.addEventListener('click', () => {
document.body.classList.toggle('dark');
const dark = document.body.classList.contains('dark');
toggle.textContent = dark ? 'Light mode' : 'Dark mode';
localStorage.setItem('theme', dark ? 'dark' : 'light');
});
New here: a ? b : c means "if a, then b, otherwise c".
The answers
theme-toggle, a click. It toggles the class
dark on the body, changes the button's text and saves the theme.body.dark { … }. Without it, the class changes and nothing looks different.if (localStorage.getItem('theme') === 'dark') {
document.body.classList.add('dark');
toggle.textContent = 'Light mode';
}
Code that runs is not code that is finished. You found that by reading, not by running it.
Your project
Your site needs at least one interactive element
The one most sites need · a menu button for phones
<button class="menu-button"
aria-expanded="false">
Menu
</button>
<ul class="links"> … </ul>
.menu-button { display: none; }
@media (max-width: 600px) {
.menu-button { display: block; }
nav .links { display: none; }
nav .links.open { display: block; }
}
const button =
document.querySelector('.menu-button');
const links =
document.querySelector('nav .links');
button.addEventListener('click', () => {
const open = links.classList.toggle('open');
button.setAttribute('aria-expanded', open);
});
HTML: the button exists. CSS: when it shows, and what open looks like. JavaScript: only the switch.
aria-expanded tells a screen reader whether the menu is open. toggle returns true or false — the new state.
Your nav comes from nav.html? Then wait for it.
function load(file, target) {
return fetch(file) // ← add return
.then(r => r.text())
.then(html => {
document.getElementById(target).innerHTML = html;
});
}
load('nav.html', 'site-header').then(() => {
// this runs once the nav is in the page
const button = document.querySelector('.menu-button');
const links = document.querySelector('nav .links');
button.addEventListener('click', () => {
const open = links.classList.toggle('open');
button.setAttribute('aria-expanded', open);
});
});
load('footer.html', 'site-footer');
fetch takes a moment, and the lines below it do not wait. return hands that moment back to you; .then runs your code once the nav has arrived.
Ideas that fit a small site
| The feature | The state | The event |
|---|---|---|
| a menu button for phones | open or closed | click |
| a light / dark switch | 'light' or 'dark' | click |
| a filter for your list | the chosen category | click or change |
| a photo that opens large | which photo, or none | click, and keydown for Escape |
| a like or a favourite | the count | click |
| feedback while typing | valid or not yet | input |
One that works perfectly beats three that half work.
Before you hand it in
<button> or <input> — Tab reaches it, Enter or Space worksWork you cannot explain does not pass — however it was made.
Lesson 5 · done
<script> tag goes, and what defer doesconst, when let — and why ===querySelector finds an element in ittextContent, not innerHTML, for anything a visitor typedwebtech.landrock.io/slides/frameworks.html
Next: Frameworks — when the screen follows the state by itself.