Web Technologies 2026 · BiUH · Lesson 5

JavaScript

What makes a page respond

Where it runs · values · functions · the DOM · events · state · when it breaks

webtech.landrock.io

What this lesson covers

Seven parts, then your project.

1 · Where it runsthe script tag, and the Console
2 · Valuesnumbers, text, lists — and the names you give them
3 · Functionswork you describe once and run many times
4 · The DOMthe page, as something JavaScript can change
5 · Eventsthe moment something happens
6 · Statewhat the page remembers — and why the screen must follow it
7 · When it breaksthe 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

You have run JavaScript twice already.

Lesson 4 · nav.js

fetch got a file, getElementById found the header, innerHTML filled it. Then a function, load(file, target), so you could do it twice.

Session 6 · the useless machine

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

Written in ten days, still everywhere.

1995Brendan Eich writes it at Netscape in ten days. Called JavaScript for marketing — no relation to Java.
1997ECMAScript — the standard every browser follows. That is the "ES" in ES2015.
2005Ajax — Gmail and Google Maps change the page without reloading it
2009Node.js — JavaScript leaves the browser and runs servers too
2015let, const, arrow functions — the JavaScript you write today
todayEvery browser, every phone runs it. Nothing to install.

When 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

Where it runs

A file, one tag, and a window that shows you everything

Getting it into the page

Where the <script> tag goes.

In the head ✗

<head>
  <script src="main.js"></script>
</head>

Runs before the body exists. Every element it looks for is not there yet.

End of the body ✓

  <script src="main.js"></script>
</body>

What you did in Lesson 4. The page is read; then the script runs.

In the head, with defer ✓

<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

Open the Console on this page.

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

Values, and their names

What JavaScript works with

Five kinds of value

TypeLooks likeFor
number42 3.5 -1counting, measuring, prices
string'Hello' "Hello" `Hello`any text — quotes at both ends
booleantrue falseyes 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

Backticks and ${ }.

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

Text that looks like a number is still text.

'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

Functions

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');
loadthe 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

return

function 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

Arrow functions: =>

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

Decide · if

if (quote.likes > 10) {
  card.classList.add('popular');
} else {
  card.classList.remove('popular');
}

Repeat · for … of

for (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 DOM

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

With the CSS selectors you already know.

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

WriteWhat changes
el.textContent = 'Saved'the text inside it
el.classList.add('open') · .remove · .toggleits 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 = truehides 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

Change the class. Let CSS do the look.

The look, in JavaScript ✗

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.

A class, and a CSS rule ✓

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?

textContent ✓

output.textContent = field.value;

Puts in text. Whatever it contains, it is shown as letters.

innerHTML — not with what a visitor typed

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

Events

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 happens

You 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

EventHappens when
clicka button or link is used — by mouse, finger, or Enter and Space on the keyboard
inputa text field changes — at every letter typed
changea checkbox, a select or a slider has changed
submita form is sent
keydowna 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

  1. Type, tick the box, press Send —
  2. each event appears here, newest on top.

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

In the HTML ✗

<button onclick="like()">

JavaScript inside an HTML attribute. Two languages in one line, and hard to find.

A property

button.onclick = like;

One per element. A second one silently replaces the first.

addEventListener ✓

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

Most validation needs no JavaScript.

<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

State

What the page remembers, right now

State is a value. The screen is a copy of it.

The questionThe stateKept in
Is the menu open?true / falsea class on the nav
How many likes?12let likes
Which photo is shown large?3let current
Light or dark?'dark'a class on the body
Is the machine switched on?true / falsethe 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.
Chinese proverb
likes = 0
click→likes++→render()

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

setTimeout

const 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
});
off→ you →on→ 800 ms →off

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

localStorage

let 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

When it breaks

Read the red message. It tells you where.

HTML and CSS forgive. JavaScript stops.

One error, and the script stops at that line.

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')what went wrong
    at main.js:4:8file · line · column

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 saysIt usually meansLook at
Cannot read properties of nullquerySelector found nothingthe selector · the script runs too early · the element comes later, by fetch
likse is not defineda name spelled two waysthe spelling, and the capitals: queryselector ≠ querySelector
Unexpected token · missing )a bracket, quote or comma is missing — the whole file stopsthat line, and the one above
main.js … 404 (Not Found)the src path is wrongthe folder and the capitals in <script src>
Failed to fetch · CORSthe 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

1 · Which element?look for querySelector or getElementById
2 · Which event?look for addEventListener and the word in quotes
3 · What changes?a value, a class, a text, an attribute

The 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');
});
  1. Which element, which event — and what changes?
  2. What must exist in the CSS for this to do anything?
  3. Switch to dark, then reload. What happens — and why?

New here: a ? b : c means "if a, then b, otherwise c".

The answers

  1. The element with id theme-toggle, a click. It toggles the class dark on the body, changes the button's text and saves the theme.
  2. A rule for body.dark { … }. Without it, the class changes and nothing looks different.
  3. It comes back light. The code saves the theme but never reads it back. It is missing:
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

One feature, done well

Your site needs at least one interactive element

The one most sites need · a menu button for phones

One feature, three languages, three jobs.

<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.

The button is not in the page yet.

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 featureThe stateThe event
a menu button for phonesopen or closedclick
a light / dark switch'light' or 'dark'click
a filter for your listthe chosen categoryclick or change
a photo that opens largewhich photo, or noneclick, and keydown for Escape
a like or a favouritethe countclick
feedback while typingvalid or not yetinput

One that works perfectly beats three that half work.

Before you hand it in

Check it like a stranger would.

Work you cannot explain does not pass — however it was made.

Lesson 5 · done

What you should be able to say now.

webtech.landrock.io/slides/frameworks.html

Next: Frameworks — when the screen follows the state by itself.

← → navigate · F fullscreen · P print · Copy never turns the page