How a Web Page Works: HTML, CSS and Your First JavaScript

A from-zero introduction to web development that builds one profile-card page: how a browser loads a page, HTML elements, nesting and the DOM tree, CSS rules, selectors, the box model and specificity, a first JavaScript event listener, and using DevTools to see what the browser actually understood.

Subject: Web Development · 71 slides · code lesson

Open the interactive version of this deck

What this lesson covers

The lesson, slide by slide

1. How a Web Page Works

Title

Web Development 1

HTML, CSS and your first JavaScript, by building one small page

2. What this session gives you

Objectives

By the end you will have built a real page from an empty folder: a profile card with a button that does something. Every idea in this deck goes into that one page.

MDN Web Docs — How the web works — MDN is the reference used for every rule in this deck

3. How the Web Actually Works

Section

Section 1

4. What do you think happens?

Warm-up

No wrong answers yet. Thirty seconds.

Discussion prompt

You type a web address and press Enter. List everything you think happens before the page appears.

Hint: Where do the words and pictures on the page come from before they reach your screen?

Answer:

Your browser sends a request across the internet to a computer called a server. The server finds the files for that page and sends them back.

Those files are plain text: HTML, CSS and JavaScript. The browser reads them and draws the page. That is the whole trick, and it means you can write those files yourself in any text editor.

MDN Web Docs — How the web works — How the web works

5. A page is files, and a browser draws them

Concept

A web page is not a picture and not a program you install. It is a few text files that a browser knows how to read.

browser — The program (Chrome, Firefox, Safari, Edge) that requests files and turns them into the page you see.

server — A computer whose job is to send files when a browser asks for them. While you are learning, your own laptop plays this part.

MDN Web Docs — How the web works — Clients and servers

6. One page load, four steps

Picture it

This is everything that happens when you press Enter.

Figure (svg): A pipeline of four steps: the browser asks, the server finds files, the files come back, the browser draws the page

Today you skip the first three: you open the file straight from your own folder.

7. Three languages, three jobs

Concept

Every page you have ever visited is built from the same three languages, and each one has exactly one job.

languageits jobit answers the question
HTMLstructurewhat is on the page?
CSSstylehow does it look?
JavaScriptbehaviourwhat happens when I do something?

Keeping the jobs separate is the most useful habit in web development. When something is wrong, the first question is always: which of the three is responsible?

MDN Web Docs — How the web works

8. Nouns, adjectives, verbs

Picture it

A handy way to remember the split.

Figure (svg): Three panels: HTML is structure and the nouns, CSS is style and the adjectives, JavaScript is behaviour and the verbs

HTML says there is a button. CSS says it is round and teal. JavaScript says what it does when clicked.

9. Which language is responsible?

Sorting

Think of any web page you use every day.

Sort into buckets

HTML, CSS, or JavaScript?

HTML
There is a search box at the top; The page has a heading and three paragraphs
CSS
The search box has rounded corners; The heading is dark blue and centred
JavaScript
Suggestions appear as you type; A menu slides open when you tap the icon
html
Whether a thing exists on the page at all is structure. A search box and a heading are elements, so HTML puts them there.
css
Corners, colours and alignment change how an existing thing looks without changing what it is. That is CSS.
js
Anything that reacts to the user after the page has loaded, such as typing or tapping, needs code that runs. That is JavaScript.

Notice the slide-open menu: the menu itself is HTML, the sliding animation can be CSS, and the decision to open it on a tap is JavaScript. Real features usually use all three.

10. What happens with only HTML?

Prediction

Suppose a page has an HTML file but the CSS and JavaScript files fail to load.

Predict first

What do you see?

  • A blank white page
  • All the content, plain and unstyled, and buttons that do nothing
  • An error message
  • The page, styled normally

Correct: All the content, plain and unstyled.

Why: HTML alone is a complete, readable page: black text, blue links, default buttons. CSS and JavaScript are layers on top of it. This is why the HTML always comes first, and why a page with good HTML still works when the rest breaks.

11. HTML: Structure

Section

Section 2

12. Elements, tags and attributes

Concept

HTML marks up content by wrapping it in tags. A tag is a name inside angle brackets, and most come in pairs: an opening tag and a closing tag with a slash.

element — An opening tag, the content inside it, and the matching closing tag, taken together.

attribute — Extra information written inside the opening tag, as a name, an equals sign, and a value in quotes.

MDN Web Docs — Basic HTML syntax — Anatomy of an HTML element

13. Reading one element

Picture it

This is a link. Every element follows the same shape.

Figure (svg): An HTML link element with labels pointing at the opening tag, the href attribute, the content, and the closing tag

The href attribute is where the link goes. The content is the clickable text.

Read it aloud as: an a element, whose href is cv.html, containing the words my CV.

14. The elements you will use most

Concept

There are over a hundred HTML elements, but a beginner page needs about eight.

<h1>Main heading</h1>
<h2>Smaller heading</h2>
<p>A paragraph of text.</p>
<a href="page.html">A link</a>
<img src="photo.jpg" alt="What the photo shows">
<button>Click me</button>
<ul>
  <li>A list item</li>
</ul>
elementmeansnote
h1 to h6headings, biggest to smallestone h1 per page
pa paragraphthe default for text
aa linkneeds href
imgan imageno closing tag; needs src and alt
buttonsomething to clickdoes nothing until JavaScript
ul and lia list and its itemsli must sit inside ul

MDN Web Docs — Basic HTML syntax

15. Match the element to the job

Matching

Five things your page needs.

Match the pairs

  • l1. the biggest title on the page
  • l2. a sentence of description
  • l3. a picture of you
  • l4. something that goes to another page
  • l5. something the user presses to make things happen
  • r1. h1
  • r2. p
  • r3. img
  • r4. a
  • r5. button

Why: Choosing the element by its meaning, not its appearance, is the rule. A link and a button can be styled to look identical, but a link goes somewhere and a button does something, and screen readers and search engines rely on that difference.

16. Every page has the same skeleton

Concept

Whatever the page is about, the outer frame never changes. You will type it so often that it becomes automatic.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>My page</title>
  </head>
  <body>
    <!-- everything visible goes here -->
  </body>
</html>
linewhat it does
<!DOCTYPE html>tells the browser this is modern HTML
<html lang="en">the root: wraps everything, says the language
<head>information about the page
<meta charset="utf-8">lets accents and emoji display correctly
<title>the text on the browser tab
<body>everything the user actually sees

MDN Web Docs — Basic HTML syntax

17. The head is about the page; the body is the page

Picture it

The single most common beginner confusion, in one picture.

Figure (svg): Two panels contrasting the head, which holds information about the page such as the tab title and stylesheet link and is never shown, with the body, which holds everything visible

If you can see it on the page, it belongs in the body.

18. Trap: putting visible content in the head

Trap

The trap

A first page, written in a hurry.

Annotate

  • A heading is visible content. The head is for information about the page.
  • Only this paragraph is where it should be.
browserwhat it does with the misplaced h1
Chromequietly moves it into the body
an HTML validatorreports an error
you, next weekcannot work out why your CSS layout is odd

Rely on the browser to guess

Why: Browsers repair broken HTML silently, so the mistake never shows up as an error. It shows up later, as confusing behaviour.

The fix

Visible content goes in the body. Always.

<head>
  <title>Jordan Lee</title>
</head>
<body>
  <h1>Jordan Lee</h1>
  <p>CS student.</p>
</body>
elementwherewhy
titleheadit labels the tab, it is not on the page
h1bodyit is on the page
pbodyit is on the page

Write it where it belongs

Why: Then the page you wrote is the page the browser builds, and nothing is being silently repaired behind your back.

19. Nesting: elements inside elements

Concept

Elements go inside other elements, like boxes inside boxes. The rule is strict: whatever opens last must close first.

<!-- correct: the a closes before the p does -->
<p>See <a href="cv.html">my CV</a> for more.</p>

<!-- wrong: the tags cross over -->
<p>See <a href="cv.html">my CV</p></a>
versionorder of closingvalid?
firsta, then pyes: last opened, first closed
secondp, then ano: the tags overlap
any pagemirror image of the opening orderthe rule to check

Indenting each nested level by two spaces makes this rule visible at a glance. That is the only reason code is indented.

MDN Web Docs — Basic HTML syntax — Nesting elements

20. Which statement about nesting holds?

Two truths and a lie

Three claims about HTML nesting.

Eliminate the wrong options

Which one is true?

  • A. An li element must sit directly inside a ul or ol element.
  • B. Indentation changes how the browser reads the HTML.
  • C. Overlapping tags cause the page to fail to load.
  • D. Every element needs a closing tag.

Survives elimination: A

Why: A list item only means something inside a list, so the specification requires it. The other three are among the most common beginner misconceptions: whitespace is ignored, broken HTML is repaired rather than rejected, and void elements never close.

21. The page is a tree

Concept

When the browser reads your HTML, it builds a family tree out of the nesting. Every element is a parent of the elements inside it.

DOM — The Document Object Model: the tree of elements the browser builds from your HTML. CSS styles it, JavaScript changes it, and DevTools shows it to you.

MDN Web Docs — JavaScript: adding interactivity

22. The profile page, as the browser sees it

Picture it

This is the page you are about to build, drawn as its tree.

Figure (svg): A DOM tree with html at the root, head and body beneath it, a title inside head, a main element with class card inside body, and an img, h1, p and button inside the main element

The highlighted main element is the card. Everything visible hangs underneath it.

Every later section works on this tree. CSS picks out nodes to style; JavaScript picks out nodes to change.

23. Pattern: writing any page

Pattern

Whatever the page is, build the HTML in the same three passes.

  1. Skeleton first: doctype, html, head with a title, and an empty body.
  2. Content next: choose each element by what it means, and nest it inside its parent.
  3. Labels last: add a class to anything you will style as a group, and an id to anything JavaScript must find.

Skeleton, content, labels. Doing them in that order means you never style or script something before you know it exists.

MDN Web Docs — Basic HTML syntax

24. Worked example: the complete profile page

Worked example

Here is the whole page, built from the skeleton plus the elements you have just met. Save it as index.html in a new folder, then double-click it.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Jordan Lee</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <main class="card">
      <img src="me.jpg" alt="Photo of Jordan">
      <h1>Jordan Lee</h1>
      <p class="greeting">CS student. Algorithms and coffee.</p>
      <button id="hello">Say hello</button>
    </main>
    <script src="script.js"></script>
  </body>
</html>
lineswhat they add
1-7the skeleton and head, including the link to style.css
9a main element with a class, so CSS can find the card
10-12the photo, the name and the description
13a button with an id, so JavaScript can find it
15the script tag, placed last so the elements exist before the code runs

Give the card a class and the button an id

Why: These are names. On their own they do nothing; they exist so CSS and JavaScript can point at these elements later.

Verify: by opening the file in a browser

Why: You should see a photo, a heading, a sentence and a plain grey button. If the photo is a broken icon, the file name in src does not match the file in the folder.

25. What you see right now

Picture it

Plain, but complete. Every piece of content is there.

Figure (svg): A browser window showing an unstyled page: an image placeholder, the heading Jordan Lee, a sentence, and a plain grey button

This is the HTML-only page. Nothing is wrong with it; it just has no style yet.

26. Finish the image tag

Fill the middle

The image needs two attributes to be correct.

Fill in the blanks

<img src="me.jpg" alt="Photo of Jordan">

Why: The src attribute tells the browser which file to load. The alt attribute describes the image for screen-reader users and appears if the file fails to load. An img without alt is treated as an accessibility error.

27. Check: where does the tab title come from?

Check

Solve it on paper before you click.

Check your understanding

You want the browser tab to say Jordan Lee. Which line does that?

  • A. <title>Jordan Lee</title> inside the head (correct)
  • B. <h1>Jordan Lee</h1> inside the body
  • C. <title>Jordan Lee</title> inside the body
  • D. <head>Jordan Lee</head>

Answer: A

Why: The title element labels the page itself, which makes it information about the page, which puts it in the head. The h1 is the heading people see on the page; the two often say the same thing but do different jobs.

Why B tempts people
The h1 is the visible heading inside the page. It has no effect on the tab.
Why C tempts people
Right element, wrong place. Title belongs in the head, and a browser will not reliably use one placed in the body.
Why D tempts people
The head is a container, not a label. Text typed straight into it is not a title.

28. CSS: Style

Section

Section 3

29. A stylesheet is a list of rules

Concept

CSS lives in its own file, usually called style.css, and the link element in your head connects it to the page. The file is nothing but rules.

Each rule says: find these elements, and set these properties to these values.

rule — A selector, followed by curly braces containing one or more property-colon-value pairs, each ending in a semicolon.

MDN Web Docs — CSS styling basics — What is CSS?

30. Reading one rule

Picture it

Three parts. Every CSS rule ever written has exactly this shape.

Figure (svg): A CSS rule for the card class with labels on the selector, the padding property, the 24px value and the closing semicolon

Read it aloud as: for elements with class card, set padding to 24 pixels.

31. Three ways to select

Concept

The selector is how a rule finds its elements. Beginners need three kinds, and they match the three ways you labelled the HTML.

p        { color: gray; }    /* every p element */
.card    { padding: 24px; }  /* every element with class="card" */
#hello   { cursor: pointer; } /* the one element with id="hello" */
selectorwritten asmatchesuse it for
elementpevery p on the pagesite-wide defaults
class.cardanything with class="card"almost everything
id#helloexactly one elementJavaScript hooks

The dot means class. The hash means id. Forgetting the dot is the single most common reason a rule does nothing.

MDN Web Docs — CSS styling basics — Basic selectors

32. What does each selector match?

Discrimination

Use the profile page from the worked example.

Sort into buckets

One element, or several?

exactly one, by design
#hello
every one of that kind
p; button; img
one
An id must be unique on the page, so an id selector can only ever match one element. That guarantee is why JavaScript likes ids.
many
An element selector matches every element of that type. On this page there happens to be one button and one img, but add a second and the rule styles both.

33. The box model: all spacing is boxes

Concept

The browser treats every element as a rectangle with four layers. Every spacing problem you will ever have is a question about one of these layers.

padding — Space inside the box, between the content and the border. It takes the box's background colour.

margin — Space outside the box, between this element and its neighbours. It is always transparent.

MDN Web Docs — The box model — The box model

34. Content, padding, border, margin

Picture it

From the inside out.

Figure (svg): Four nested rectangles: content in the centre, padding around it, a border around that, and margin outermost

Padding pushes the border away from the content. Margin pushes other elements away from the border.

A memory hook: padding is the stuffing inside the parcel; margin is the gap between parcels on the shelf.

35. Padding or margin?

Prediction

The card has a dark background. You want more dark space between the card's edge and the text inside it.

Predict first

Which property do you increase?

  • padding
  • margin
  • border
  • width

Correct: padding.

Why: The space you want is inside the box, between the content and the edge, and it should be the card's own dark colour. That is exactly what padding is. Margin would push the whole card away from other things and stay transparent.

36. Worked example: styling the card

Worked example

Create style.css next to index.html. Because the head already links it, the page picks it up the moment you save and refresh.

body {
  font-family: system-ui, sans-serif;
  background: #0f1420;
}

.card {
  max-width: 320px;
  margin: 60px auto;
  padding: 24px;
  border-radius: 16px;
  background: #1b2433;
  color: white;
  text-align: center;
}

button {
  padding: 8px 20px;
  border: none;
  border-radius: 999px;
}
propertyoneffect
font-familybodyreplaces the default serif font everywhere
max-width.cardstops the card stretching across a wide screen
margin: 60px auto.card60px above and below; auto left and right centres it
padding.carddark space between the card edge and its text
border-radius.card and buttonrounds the corners; 999px makes a pill
text-align.cardcentres the text and the inline image inside

Style from the outside in

Why: Body first for site-wide defaults, then the card, then the small pieces. Each rule only has to deal with what the rule above it left.

Verify: by saving and refreshing

Why: The card should be centred, rounded and dark. If nothing changed at all, the link in the head is wrong or the file is not called style.css.

37. The same HTML, now styled

Picture it

Not one character of the HTML changed.

Figure (svg): A browser window showing the profile as a centred dark card with a round photo, the name, a short description and a teal pill-shaped button

Every visual change came from style.css. That separation is the point.

38. Watch margin auto centre the card

Invariant

The screen gets wider. The card stays in the middle.

Step through it

What stays the same in every frame?

  1. The browser takes the leftover width, 80px, and splits it evenly.
  2. More leftover width, still split evenly. The card does not grow past its max-width.
  3. Same rule, same result: the two margins are always equal.

The card's width and the equality of the two margins. That is what auto means here: share the leftover space equally.

39. When two rules disagree

Concept

Two rules can target the same element and set the same property. The browser picks one winner, and the rule is called specificity: the more precisely a selector points, the stronger it is.

p        { color: gray; }
.greeting { color: white; }

/* <p class="greeting"> is white: a class beats an element */
selectorstrengthso
pweakloses to a class
.greetingmediumwins here
#hellostrongbeats any class

If two selectors are equally strong, the one written later in the file wins.

MDN Web Docs — CSS styling basics — Cascade and specificity

40. Who wins, ranked

Picture it

Longer bar beats shorter bar.

Figure (svg): Four bars ranking CSS selector strength: the style attribute strongest, then id, then class, then element

Live in the green bar. Classes are strong enough to override defaults and weak enough to override each other.

41. Trap: the rule that does nothing

Trap

The trap

The card refuses to change, no matter what you set.

Annotate

  • No dot: this looks for an element called card, and there is none.
  • Missing semicolon: this line and the next run together and both are thrown away.
mistakewhat the browser doeserror shown
missing dotmatches nothingnone
missing semicolondrops the broken declarationsnone
misspelt propertyignores itnone

Keep changing values and refreshing

Why: CSS never reports an error on the page. It skips what it cannot understand and carries on, so changing values just repeats the same silent failure.

The fix

Check the shape before the values.

.card {
  padding: 24px;
  background: #1b2433;
  color: white;
}
checklooks for
selectora dot for a class, a hash for an id
every lineends with a semicolon
bracesevery opening brace is closed

Read the rule's shape first, then open DevTools

Why: DevTools shows invalid lines crossed out with a warning icon, which turns a silent failure into a visible one.

42. Why is the button still grey?

Elimination

You wrote the rule below, saved, and refreshed. The button did not change.

Eliminate the wrong options

Which explanation is the one that fits?

  • A. The rule says .button, but the HTML element is a button with no class
  • B. CSS cannot style buttons
  • C. The browser needs to be restarted
  • D. The rule must be written in the HTML file instead

Survives elimination: A

Why: The dot makes .button a class selector, so it looks for class="button". The element has no such class. Either remove the dot to select every button element, or add the class to the HTML. This is the missing-dot trap in reverse.

43. Check: centring a box

Check

Solve it on paper before you click.

Check your understanding

The card has max-width: 320px. Which line centres it horizontally on the page?

  • A. margin: 0 auto; (correct)
  • B. text-align: center;
  • C. padding: auto;
  • D. align: center;

Answer: A

Why: Auto left and right margins share the leftover width equally, which centres a box that has a width. text-align centres the content inside a box, not the box itself.

Why B tempts people
This centres the text inside the card. The card itself stays on the left.
Why C tempts people
Padding does not accept auto. The declaration is invalid and is silently dropped.
Why D tempts people
There is no align property in CSS. It is ignored without an error.

44. JavaScript: Behaviour

Section

Section 4

45. JavaScript changes the tree

Concept

HTML builds the tree once, when the page loads. JavaScript is how the page changes after that: it finds nodes in the tree and alters them while the user watches.

Almost every beginner script has the same three steps: find an element, wait for something to happen to it, then change something.

event — Something that happens on the page that code can respond to: a click, a key press, the mouse moving, a form being submitted.

MDN Web Docs — JavaScript: adding interactivity — Adding interactivity

46. Step one: find the element

Concept

document.querySelector takes a CSS selector, the same kind you just wrote, and returns the first element that matches.

const button = document.querySelector('#hello');
const greeting = document.querySelector('.greeting');
piecemeans
const buttonmake a name, button, that will always refer to the same thing
documentthe whole page, as JavaScript sees it
querySelector('#hello')find the element with id hello
'.greeting'the dot still means class, exactly as in CSS

You already know the hard part. The selector language is the one from the CSS section.

MDN Web Docs — JavaScript: adding interactivity

47. Step two and three: listen, then change

Concept

addEventListener tells an element: when this event happens to you, run this function. The function is the change you want.

button.addEventListener('click', function () {
  greeting.textContent = 'Hi there! Thanks for visiting.';
});
piecemeans
button.addEventListenerattach a listener to the button
'click'the event to listen for
function () { ... }the code to run when it happens; not now, later
greeting.textContent = ...replace the paragraph's text

MDN Web Docs — Introduction to events — Using addEventListener

48. From click to change

Picture it

Five steps, and you write only one of them.

Figure (svg): A five step flow: the user clicks, the browser fires a click event, the listener catches it, the function runs and changes the page, and the browser redraws

The browser does steps one, two and five. Your code is the listener and its function.

49. When does the function run?

Prediction

The page has just loaded. Nobody has touched the button.

Predict first

Has the greeting text changed yet?

  • Yes, the function ran when the page loaded
  • No, the function runs only when the button is clicked
  • Only if the page is refreshed
  • It depends on the browser

Correct: No.

Why: addEventListener does not run the function. It hands the function to the browser to keep until the event happens. This is the central idea of interactive pages: you write code now that runs later, in response to the user.

50. Worked example: the working button

Worked example

Create script.js in the same folder. The script tag at the bottom of the body already loads it.

const button = document.querySelector('#hello');
const greeting = document.querySelector('.greeting');

button.addEventListener('click', function () {
  greeting.textContent = 'Hi there! Thanks for visiting.';
});
lineruns whendoes
1page loadfinds the button and names it
2page loadfinds the paragraph and names it
4page loadattaches the listener, but does not run it
5each clickreplaces the paragraph's text

Find, listen, change

Why: Lines 1 and 2 find. Line 4 listens. Line 5 changes. Every small interactive feature you build for a while will have this exact shape.

Verify: by clicking the button

Why: The sentence under the name should change. If nothing happens, open the Console: the error there will name the line.

51. What each line did to the page

Invariant

Step through the script, from page load to the first click.

Step through it

In which frame does the user first see a difference?

  1. The button is found and named. Nothing visible has happened.
  2. The paragraph is found and named. Still nothing visible.
  3. The listener is attached and waiting. The text has still not changed.
  4. Only now, on the click, does the function run and the text change.

The last one. Three lines of setup, all invisible, so that one line can run at the right moment.

52. Trap: the script that runs too early

Trap

The trap

The script tag is moved into the head, next to the stylesheet.

Annotate

  • The script runs here, as soon as the browser reaches it.
  • The button has not been built yet when the script looks for it.
momentbutton exists?querySelector returns
script runsnonull
addEventListener callednoerror: cannot read properties of null
page finishesyestoo late

Load the script before the page is built

Why: The browser reads top to bottom. Code that looks for an element must run after that element has been read.

The fix

Put the script at the end of the body.

<body>
  <button id="hello">Say hello</button>
  <script src="script.js"></script>
</body>
momentbutton exists?querySelector returns
button readyes-
script runsyesthe button
clickyesthe listener fires

Let the HTML finish first

Why: By the time the browser reaches the script, every element above it is already in the tree. Adding defer to a script in the head achieves the same thing.

53. Put the script's three steps in order

Ranking

Any small feature: a button that shows a hidden message.

Put in order

  1. Find the button and the message with querySelector
  2. Attach a click listener to the button
  3. Inside the listener's function, change the message
  4. Click the button and check the page

Why: Find, listen, change, then verify. You cannot listen on an element you have not found, and the change has to live inside the listener or it runs immediately instead of on the click.

54. Pattern: find, listen, change

Pattern

Every small interactive feature you build for the next few weeks has the same three-part shape.

  1. Find the elements involved, with querySelector and the same selectors you use in CSS.
  2. Listen for the event that should trigger the feature, with addEventListener.
  3. Change the page inside the listener's function, and only there.

When a feature does not work, ask which of the three steps failed. The Console almost always tells you: null means find failed; nothing at all means listen or change did.

MDN Web Docs — Introduction to events

55. CSS selectors and JavaScript selectors

Comparison

Same language, two places. Fill in the gaps.

Comparison matrix

you wantin CSSin JavaScript
every pp { ... }document.querySelectorAll('p')
the element with id hello#hello { ... }document.querySelector('#hello')
the first element with class card.card { ... } (styles them all)document.querySelector('.card')

One difference worth remembering: a CSS rule applies to every match, but querySelector returns only the first. Use querySelectorAll when you want them all.

56. Check: what does this click do?

Check

Solve it on paper before you click.

Check your understanding

button.addEventListener('click', function () { greeting.textContent = 'Bye'; }); runs when the page loads. What is on the page right after it runs, before any click?

  • A. The original greeting text (correct)
  • B. The word Bye
  • C. An empty paragraph
  • D. An error, because nobody has clicked

Answer: A

Why: Attaching a listener changes nothing on the page. The function is stored until a click happens, so the original text stays until then.

Why B tempts people
That would be true only if the assignment were outside the function. Inside it, the line waits for the click.
Why C tempts people
Nothing in the code empties the paragraph. Only the function changes the text, and it has not run.
Why D tempts people
Waiting for a click is the normal state of a listener, not an error.

57. Putting It Together

Section

Section 5

58. The finished folder

Picture it

Four files, three languages, one page.

Figure (svg): A file listing of the profile folder: index.html, style.css, script.js and me.jpg, each with a note on what it is for

index.html is the only file you open. It pulls in the other three.

59. How the three files find each other

Concept

The HTML is in charge. It names the other files, and the browser fetches whatever it names.

<link rel="stylesheet" href="style.css">   <!-- in the head -->
<img src="me.jpg" alt="Photo of Jordan"> <!-- in the body -->
<script src="script.js"></script>          <!-- end of the body -->
filelinked byattribute
style.csslinkhref
me.jpgimgsrc
script.jsscriptsrc

These are file paths. They must match the file names exactly, including capital letters, or the browser finds nothing and says nothing.

MDN Web Docs — Basic HTML syntax

60. DevTools: see what the browser understood

Concept

Right-click anything on a page and choose Inspect. DevTools opens, and it shows you the page as the browser actually built it, which is not always the page you meant to write.

panelshows youuse it when
Elementsthe live DOM tree and every CSS rule on the selected elementsomething looks wrong
ConsoleJavaScript errors, and a place to type JavaScriptsomething does not happen
Networkevery file the page asked for, and whether it arriveda file seems not to load

Chrome DevTools documentation

61. The Console answers questions

Picture it

Type a selector into the Console before putting it in your script.

Figure (svg): A Console session in which querySelector with a hash selector returns null, and the same query with a dot selector returns the paragraph element

null means nothing matched. The paragraph has a class, not an id, so it needs a dot.

If querySelector returns null in the Console, it will return null in your script too. Fix the selector here first.

62. Why does the button do nothing?

Error analysis

A student's script. The page loads, the button is there, clicking it does nothing, and the Console shows an error.

Annotate

  • No hash: this looks for an element called hello. There is none, so button is null.
  • A hash: but greeting is a class on this page, not an id. Also null.
  • The Console error points here: cannot read properties of null, reading addEventListener.

The error is reported on line 4, but the mistake is on line 1. That is normal: an error shows where the program fell over, not where it tripped.

Fix both selectors to '#hello' and '.greeting' and the button works.

63. What would you check first?

Missing information

A friend says: my page has no styling at all, and I am sure my CSS is right.

Discussion prompt

Before reading a single line of their CSS, what three things would you check?

Hint: If every single rule failed at once, what do all the rules have in common?

Answer:

Whether the link element is in the head and its href matches the file name exactly, including capitals.

Whether the CSS file is saved in the same folder as the HTML file, since a bare file name means the same folder.

Whether the Network panel in DevTools shows style.css loading, or failing with a not-found error.

No styling at all is almost never a CSS problem. It is a connection problem, and those three checks find it in under a minute.

64. Why keep the three languages in separate files?

Socratic

You could put everything in one file. Professionals almost never do.

Discussion prompt

What do you gain by keeping HTML, CSS and JavaScript in separate files?

Hint: Imagine the site grows to twenty pages that all share the same look.

Answer:

Each file has one job, so when something is wrong you know which file to open.

One stylesheet can style a hundred pages. Change a colour once and the whole site updates.

Browsers save linked files after the first visit, so every later page loads faster.

MDN Web Docs — How the web works

65. Where should a style go?

Trade off

Three places CSS can live. Fill in what each costs.

Comparison matrix

wherewhat it gives youwhat it costs
a linked style.cssone place for the whole site's lookan extra file to keep linked correctly
a style element in the headquick for a single pageother pages cannot reuse it
a style attribute on one elementinstant, no selector neededthe strongest specificity, so it overrides everything and is hard to change later

Default to the linked file. Use the others only when you have a specific reason.

66. How sure are you?

Commit first

Answer, then rate your confidence.

Predict first

You rename style.css to Style.css but leave the link as href="style.css". On a web server, does the page still get its styles?

  • Yes, file names are not case sensitive
  • No, the names no longer match
  • Only in Chrome
  • Only after a refresh

Correct: No, on most web servers.

Why: Most web servers treat Style.css and style.css as two different files, so the link finds nothing. It may still work on your own Windows or Mac laptop, which is exactly why this bug appears only after the site is published. Lowercase file names everywhere avoids it entirely.

67. Explain the page to a friend

Explain it

Two or three sentences, out loud.

Discussion prompt

When you click Say hello, what part did HTML play, what part did CSS play, and what part did JavaScript play?

Hint: Use the three words: structure, style, behaviour.

Answer:

HTML put the button and the paragraph on the page and gave them an id and a class so they could be found.

CSS made the button a teal pill and the card a centred dark box. It has nothing to do with what happens on the click.

JavaScript found both elements, waited for the click, then replaced the paragraph's text.

68. Check: which file has the bug?

Check

Solve it on paper before you click.

Check your understanding

The button is the right colour and shape, but clicking it does nothing. Which file do you open first?

  • A. script.js (correct)
  • B. style.css
  • C. index.html, to change the button text
  • D. me.jpg

Answer: A

Why: The button looks right, so structure and style are working. What is missing is behaviour, and behaviour is JavaScript's job. Open the Console first: it will usually name the exact line.

Why B tempts people
CSS controls the look, and the look is correct. Nothing in a stylesheet makes a click do something.
Why C tempts people
The button exists and displays, so the HTML has done its part. The text on the button is not why the click fails.
Why D tempts people
An image file cannot affect a button's behaviour.

69. Exit ticket

Exit ticket

One honest answer. It decides where next session starts.

Predict first

Which of these still feels the shakiest?

  • Which language does which job
  • Writing HTML that nests correctly
  • CSS selectors and the box model
  • querySelector and addEventListener
  • Using DevTools to find a problem

Correct: Whichever you chose is where the next session begins.

Why: All five build on each other, so a gap early on makes everything after it feel harder than it is. Naming it now is the fastest way to close it.

70. Build your own card

Connect it up

Before next session, about thirty minutes.

Draw it

Make your own version of the profile card with your name, a photo, and three things you are interested in as a list. Then add a second button that changes the heading's colour when clicked. Write down every error you hit and how you found it.

Bring the list of errors. They are the most useful thing you will make this week.

71. What you can do now

Recap

You built a complete page from an empty folder. Everything else in web development is more of these same three things.

you want towrite
add a heading<h1>Text</h1>
link a stylesheet<link rel="stylesheet" href="style.css">
style every element with a class.name { property: value; }
centre a box with a widthmargin: 0 auto;
find an elementdocument.querySelector('#id')
react to a clickel.addEventListener('click', function () { ... })

MDN Web Docs — Basic HTML syntax — keep MDN open in a tab while you build

Sources

  1. MDN Web Docs — How the web works
  2. MDN Web Docs — Basic HTML syntax
  3. MDN Web Docs — CSS styling basics
  4. MDN Web Docs — The box model
  5. MDN Web Docs — JavaScript: adding interactivity
  6. MDN Web Docs — Introduction to events
  7. Chrome DevTools documentation

Want this taught 1-on-1? Alexander tutors Web Development — $55/session, free consultation.

Book on Wyzant · Text (657) 465-8108