# JavaScript libraries

Finding code somebody else wrote, loading it with a script tag or with import, and knowing when to walk away.

Multimedia & Creative Technology · 2.1 Webcoding · Lesson 9 · version 2.0.0 · 2026-11-30

Tags: javascript, libraries, cdn, modules

Slides: <https://slides.mctantwerp.be/en/webcoding/07-javascript-libraries-self-study>

<!-- slide 2 -->

## After this lesson you can

- Search for a library with the right words, on Google, on GitHub, on a CDN site or with an AI
- Judge from its GitHub page whether a library is any good and still maintained
- Turn a README into a link tag, a script tag and the HTML the library expects
- Pin the version of a library in a CDN url
- Load a library that ships as a module, with import and a CDN url
- Recognise what went wrong from the console: a 404, not defined, or an unexpected token export

> **Explanation:** Every exercise at the end of this deck needs a few of these. Most tutorials you find online only show the script tag, while most docs written lately start with import. So chapter 5, about import, and example 4 are the parts to take your time for.

<!-- slide 3 -->

## How this week works

- **01 Concepts and examples**: Five chapters on where libraries live and how you load them, then four examples from "I want this" to a working page.
- **02 Five exercises**: Homework. We go over them together at the start of the next lesson, on 7 December.

Every example runs on the slide: press Run, change something, run again. Stuck? Ask in the #help-needed forum on [Discord](https://kdgmt.be/discord), with a screenshot of your code and of the console.

> **Explanation:** Do the chapters in order the first time, they build on each other: the examples use everything from chapters 1 to 5. The exercises are the real lesson, the chapters give you what you need for them. Bring what you made to the next lesson, also when it does not work yet. A half working exercise with a red line in the console is the best thing to go over together.

<!-- slide 4 -->

## Agenda

1. Why libraries
2. Where libraries live
3. Inside a library
4. A script tag
5. import
6. Example: an accordion
7. Example: a lightbox
8. Example: a carousel
9. Example: numbers that count up
10. Exercises

> **Explanation:** Chapters 1 to 5 are the concepts. The four examples each add one new thing: the accordion is the full walk from search to working page, the lightbox is about searching in other places, the carousel about asking an AI, and the counter about a library that only comes as a module. The exercises follow the examples: lightbox, accordion and carousel come back, the date picker and your own pick are new.

<!-- slide 5 -->

## 1. Why libraries

> **Explanation:** Every site you build will need something that HTML and CSS do not give you: a slider, a map, a chart. Building that yourself is a fine exercise once. On a client project it is weeks of work that somebody already did, and tested on more devices than you own.

<!-- slide 6 -->

**Somebody already built it.**

A carousel that works with a mouse, a finger and a keyboard, on every screen size, takes weeks to get right. Somebody did that already, tested it on a thousand sites and gave it away.

> **Explanation:** Think about what a decent image slider has to do: swipe on a phone, arrows on a keyboard, loop at the end, load the pictures only when they are needed, and tell a screen reader which slide is showing. Every one of those is a small project of its own. Open the demo page of Swiper (swiperjs.com) and count the features, then imagine writing them.

<!-- slide 7 -->

### Warm water

- **[Swiper](https://swiperjs.com)**: Carousels and sliders
- **[GLightbox](https://biati-digital.github.io/glightbox/)**: Pictures and videos in a lightbox
- **[flatpickr](https://flatpickr.js.org)**: A date picker
- **[Chart.js](https://www.chartjs.org)**: Charts from an array of numbers
- **[GSAP](https://gsap.com)**: Animation, also on scroll
- **[Leaflet](https://leafletjs.com)**: Maps
- **[SortableJS](https://sortablejs.github.io/Sortable/)**: Drag and drop in a list
- **[canvas-confetti](https://www.kirilv.com/canvas-confetti/)**: Confetti. Obviously

Every card links to the site of the library, most of them with a demo on the front page.

> **Explanation:** Don't reinvent warm water. One library per kind of problem, the ones I would reach for today. GSAP is free since Webflow bought it, also for client work. A library is code you call: you decide when confetti() runs. A framework like React works the other way around, it decides how your page is built and calls your code. That is why a library fits in any page and a framework does not.

<!-- slide 8 -->

### Four steps

1. **Search**: Google, GitHub, a CDN site or an AI. Find a library that does what you want.
2. **Download or link**: A file in your project folder, or a url to a CDN.
3. **Integrate**: The CSS, the script and the HTML the library expects.
4. **Use**: Start it from your own script, with the options you need.

> **Explanation:** Most of the time goes to the first step: finding something that is good. The other three are reading and copying, if you read carefully. Every example in chapters 6 to 9 walks through these steps in this order, so you can always tell where you are.

<!-- slide 9 -->

### Check HTML first

| You need | HTML has |
| --- | --- |
| An accordion | `<details>` |
| A date picker | `<input type="date">` |
| A modal | `<dialog>` |
| A colour picker | `<input type="color">` |
| A slider | `<input type="range">` |

Ten years ago each of these needed a plugin. Now they are an element or an input type, with the keyboard and the screen reader for free. Sometimes you still pick a library, because it looks better. But you pick it on purpose.

> **Explanation:** The details element is the one to remember: an accordion was one of the most installed jQuery plugins ever, and the browser has done it for years. dialog gives you a modal that closes with Esc and keeps the focus inside, which is hard to get right in JavaScript. The date picker of the browser looks different in Chrome, in Safari and on every phone, and you cannot style it much. That is the usual price: free and accessible, but plain.

<!-- slide 10 -->

### Zero lines of JavaScript

Run it and open both. Then add `name="faq"` to both details elements and run again: now only one of them can be open at a time.

```html
<details>
  <summary>What is an accordion?</summary>
  <p>This. Without a line of JavaScript.</p>
</details>
<details>
  <summary>And a date picker?</summary>
  <input type="date">
</details>
```

> **Explanation:** The name attribute on details is fairly new, it works in every browser since 2024, and it is exactly what most accordion libraries sell you. On a phone the date input opens the date wheel of the phone itself, which is usually nicer than any library. You need both for the accordion exercise.

<!-- slide 11 -->

## 2. Where libraries live

> **Explanation:** A library lives in three places at once: the source code on GitHub, the published package on npm, and the files on a CDN that your page loads. It is the same code, seen from three sides. You use all three to decide whether a library is worth it.

<!-- slide 12 -->

### GitHub

- [github.com](https://github.com) holds the source code of nearly every open source library.
- One library is one repository: its files, its history and its bug reports.
- Googling for code lands you here more often than anywhere else.
- No account needed to read it or to download it.

**[github.com/michu2k/Accordion](https://github.com/michu2k/Accordion)**: The accordion library of example 1, in chapter 6.

> **Explanation:** A repository is a project: the code, its history, and a front page with the README. You end up there from Google all the time, so it pays to know how to read one quickly. Bug reports are called issues, and you can read them without an account too.

<!-- slide 13 -->

### Reading a GitHub page

Screenshot: The GitHub page of michu2k/Accordion
1. **Stars**: How many people like it
2. **Issues**: The bug reports. Read a few
3. **Last change**: Does anybody still work on it?
4. **dist**: The files you load
5. **README**: How to install and use it
6. **Latest release**: The version for your url

> **Explanation:** The front page of accordion-js. Stars: a few hundred is fine for a small library, Swiper has forty thousand. The date next to the last commit says whether anybody still works on it. Two thousand open issues without answers is a warning. GitHub shows the README below the list of files, so scroll down. The latest release, on the right, gives the version number you put in your url.

<!-- slide 14 -->

### npm

- [npmjs.com](https://www.npmjs.com) is the registry: nearly every JavaScript library is published there.
- Every package has a page with its version, weekly downloads and the date it was last published.
- Docs often start with `npm install`. That is for projects with a build tool, not for a plain HTML page.
- **We never run npm install in this course.** We read past it, chapter 5 shows how.

**[npmjs.com/package/accordion-js](https://www.npmjs.com/package/accordion-js)**: The newest version, the downloads per week and every file in the package.

> **Explanation:** npm is two things: the registry, the website with every published package, and the tool on your laptop that installs them. In this course you only use the website, to look things up. Weekly downloads say how many projects use a package. A package with a handful of downloads and a name close to a popular one is a red flag: that is how fake packages trick people.

<!-- slide 15 -->

### CDN

- **C**ontent **D**elivery **N**etwork.
- Servers all over the world that host the same files, so a visitor gets them from close by, fast.
- The big ones host every library on npm, for free.
- You never upload the library yourself: you put its url in your page.

> **Explanation:** Somebody in Antwerp gets the file from a server in Brussels or Amsterdam, somebody in Tokyo from one in Tokyo. The flip side: your page now depends on somebody else's server. The big CDNs are very reliable, but for a client site some developers still download the files and host them next to the page.

<!-- slide 16 -->

### The big ones

| CDN | Good for |
| --- | --- |
| [jsDelivr](https://www.jsdelivr.com) | Every npm package and every GitHub repo. Fast, with a search on the site |
| [unpkg](https://unpkg.com) | Every npm package, simple urls |
| [cdnjs](https://cdnjs.com) | A curated list, lots of older libraries too |
| [esm.sh](https://esm.sh) | Any npm package as a module you can import |

All four have a search on their site. Example 2, the lightbox, uses it.

> **Explanation:** jsDelivr is my default, unpkg is the same idea with simpler urls, cdnjs is a list somebody keeps by hand, with a lot of older libraries. esm.sh is the odd one out: it turns a package into a module, which you need in chapter 5.

<!-- slide 17 -->

### Download or link

```html
<!-- Downloaded: the file sits in your own folder -->
<script src="js/accordion.min.js"></script>

<!-- Linked: the same file, on a CDN -->
<script src="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.js"></script>
```

To download: on GitHub, the green Code button, Download ZIP, and copy the files from dist into your own folder. To link: the url of the same file on a CDN.

> [!TIP]
> Same tag, same file. Only the src is different.

> **Explanation:** Both work. For this course I link, because it is one line and there is nothing to copy around. Downloading makes sense when your site has to work without internet, like a kiosk at a fair, or when you do not want to depend on a CDN. The ZIP of GitHub also holds the src and the tests, you only need what is in dist.

<!-- slide 18 -->

### Reading a CDN url

```text
https://cdn.jsdelivr.net/npm/accordion-js@4.0.0/dist/accordion.min.js
```

| Part | Means |
| --- | --- |
| `cdn.jsdelivr.net/npm` | The CDN, serving a package from npm |
| `accordion-js` | The name of the package, the same as on npm |
| `@4.0.0` | The version |
| `/dist/accordion.min.js` | The file inside the package |

Change the version and you load another release.

> **Explanation:** On jsdelivr.com you search the package and get a list of every file, with the version already in the url. unpkg uses the same parts: unpkg.com/accordion-js@4.0.0/dist/accordion.min.js. It works like the location table of lesson 4: every part of the url means something.

<!-- slide 19 -->

## 3. Inside a library

> **Explanation:** Open the files of a library on jsDelivr or GitHub and you find versions, several copies of the same code, and folders with names like dist and src. Knowing which file goes in your page, and how heavy it is, saves you a lot of guessing.

<!-- slide 20 -->

### Versions

| In the url | You get |   |
| --- | --- | --- |
| `accordion-js@4.0.0` | Exactly that version, forever | Safest |
| `accordion-js@4` | The newest 4.x.x | Fine for an exercise |
| `accordion-js` | The newest, whatever it is | **Never** |

accordion-js went from 3 to 4 this autumn, and some option names changed. With @3 in the url, nothing happened to your FAQ. Without a version, you got 4 the day it came out.

> [!NOTE]
> `major.minor.patch`. Only a new major may break the code that uses it.

> **Explanation:** Semantic versioning: 4.0.0 is major 4, minor 0, patch 0. Whoever publishes a library promises that only a new major can break your code. So @4 gets every fix and feature of version 4, but never 5. On a client site the exact version is safest: nothing changes until you change it. When you do move to a new major, read its release notes first, they list what breaks.

<!-- slide 21 -->

### Your page loads https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.js. What happens the day Swiper 15 comes out?

- A. Nothing, the url keeps pointing at version 14
- B. Your page loads version 15, breaking changes included
- C. The url stops working
- D. The CDN asks you to update

**Answer:** B. Your page loads version 15, breaking changes included

Without a version the CDN serves the newest one, so your page follows every release, the breaking ones too. The url keeps working, and that is the problem: nothing warns you. Pin at least the major, @14, and you decide when to move to 15.

> **Explanation:** The same idea comes back in every project with npm: a version range in package.json decides what an update may pull in. Major, minor and patch mean the same thing everywhere.

<!-- slide 22 -->

### Minified

*dist*

```text
accordion.js
accordion.min.js
```

- Two versions of the **same** file.
- `.min.js` is the minified one: the same code, compressed.
- The small one goes in your page. The other one is for reading.

> **Explanation:** Open the dist folder of nearly any library and you see the same file twice. Sometimes there is a third one next to them, ending in .map: a source map. It lets the DevTools show the readable code when something breaks inside the library, even though the page loaded the minified one.

<!-- slide 23 -->

### What minifying does

- Removes every comment.
- Removes every space and new line the code can do without.
- Renames variables and functions to a single letter, where nobody outside can see it.
- Removes semicolons it does not need, and joins code where it can.
- The result: often **a third of the size**. Nobody can read it, and it is not meant to be read.

> **Explanation:** Why it matters for a page and not for a server: every visitor downloads the file, often on a phone with a bad connection. On top of that the server compresses the file with gzip or brotli while it sends it, and the browser unpacks it. Later a build tool like Vite minifies your own code too.

<!-- slide 24 -->

### Before and after

*lightbox.js*

```js
// Show the image number when there is more than one
Lightbox.prototype.imageCountLabel = function (currentImageNum, totalImages) {
  return this.options.albumLabel
    .replace(/%1/g, currentImageNum)
    .replace(/%2/g, totalImages);
};
```

*lightbox.min.js*

```js
b.prototype.imageCountLabel=function(a,b){return this.options.albumLabel.replace(/%1/g,a).replace(/%2/g,b)},
```

Comments gone, spaces gone, short names, everything on one line. Same behaviour.

> **Explanation:** A few lines of the old lightbox2 library, before and after minifying. The parameter names became a and b, because nobody outside the function can see them anyway. The name imageCountLabel stays: other code calls it by that name, so renaming it would break the library.

<!-- slide 25 -->

### How big is it

[Bundlephobia](https://bundlephobia.com): type the name of a package and you get how many kB it adds to your page.

![Bundlephobia: accordion-js 4.0.0 is 6.2 kB minified, 1.9 kB gzipped](https://slides.mctantwerp.be/decks/en/webcoding/07-javascript-libraries/bundle-accordion.jpg)

*accordion-js: 1.9 kB*

![Bundlephobia: swiper 14.5.0 is 65.8 kB minified, 20.1 kB gzipped](https://slides.mctantwerp.be/decks/en/webcoding/07-javascript-libraries/bundle-swiper.jpg)

*Swiper: 20.1 kB*

> **Explanation:** Minified is the size of the file, gzipped is what actually goes over the wire. accordion-js is tiny, Swiper is ten times bigger, which is still fine for a carousel. A 300 kB library for one button is not. Bundlephobia also shows the download time on a slow phone connection, which is a good way to feel what a kB means.

<!-- slide 26 -->

### dist and src

*Accordion*

```text
Accordion/
├── dist/
│   ├── accordion.min.css
│   └── accordion.min.js
├── src/
├── tests/
├── LICENSE
├── package.json
└── README.md
```

| Folder or file | What is in it |
| --- | --- |
| `dist` | The built files, **ready to use**. Short for distribution |
| `src` | The source code the authors work on |
| `examples` or `demo` | Working pages to copy from, when there are any |
| `README.md` | How to install and use it. Read it |
| `LICENSE` | What you may do with it |

> **Explanation:** The files of accordion-js on GitHub. Most libraries look like this, some call it build instead of dist. An examples or demo folder is gold when there is one: a working page you can copy and change. LICENSE says what you may do with the code. Nearly always that is MIT, which means: use it, also for clients, and keep the notice in the file.

<!-- slide 27 -->

### Which file of a library goes in the script tag of your page?

- A. src/accordion.ts
- B. dist/accordion.min.js
- C. package.json
- D. README.md

**Answer:** B. dist/accordion.min.js

dist holds what is built to be used, and the .min.js is the small version of it. src is for reading and for the people who work on the library: a .ts file is TypeScript, which the browser cannot even run.

> **Explanation:** When in doubt, the CDN url in the README tells you which file to load. Example 1 shows a case where the CDN site suggests another file than the README, and the README is right.

<!-- slide 28 -->

### Some libraries need jQuery

- jQuery is a library too, the most used one ever. Next lesson.
- A jQuery plugin calls jQuery itself, so jQuery has to be there first.
- The docs tell you: "requires jQuery", a script tag for `jquery.min.js`, or `$` in every example.
- Forget it and the console says **$ is not defined**.

*The order*

```html
<script src="https://code.jquery.com/jquery-4.1.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lightbox2@2.12.0/dist/js/lightbox.min.js"></script>
<script src="script.js"></script>
```

> **Explanation:** jQuery is the topic of the next lesson. Many older libraries are jQuery plugins: they call jQuery themselves, so jQuery has to be in the page first. When the docs show a script tag for jQuery, or $ in every example, you load jQuery first. Or you pick a library that does not need it, which is what I usually do.

<!-- slide 29 -->

## 4. A script tag

> **Explanation:** The way libraries were loaded for twenty years, and still the first thing most docs show. Three of the four examples work like this, and jQuery next lesson too.

<!-- slide 30 -->

### The classic way

```html
<head>
  <link rel="stylesheet" href="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.css">
</head>
<body>
  <div class="accordion-container">...</div>

  <script src="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.js"></script>
  <script src="script.js"></script>
</body>
```

1. The CSS of the library, in the head like any stylesheet.
2. The library itself.
3. Your own code, after the library, so the library exists when your code runs.

> **Explanation:** Nothing new here: lesson 4 already had a script tag with a full url. The order of the script tags is the whole trick. The browser runs them top to bottom, so the library has to come before the code that uses it. Both tags in the head with defer works too: defer keeps the order.

<!-- slide 31 -->

### The library leaves a name behind

Press Party and read the console. Then load `library last`, run again and compare.

```html
<button id="party">Party</button>

<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/dist/confetti.browser.min.js"></script>
<script>
  console.log(typeof confetti);

  document.querySelector('#party').addEventListener('click', function () {
    confetti();
  });
</script>
```

*library first*

```html
<button id="party">Party</button>

<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/dist/confetti.browser.min.js"></script>
<script>
  console.log(typeof confetti);

  document.querySelector('#party').addEventListener('click', function () {
    confetti();
  });
</script>
```

*library last*

```html
<button id="party">Party</button>

<script>
  console.log(typeof confetti);
  confetti();
</script>
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/dist/confetti.browser.min.js"></script>
```

> **Explanation:** A classic library puts one name on window, here confetti, and every script after it can use that name. accordion-js does the same with Accordion, jQuery with $. In the second version your script runs before the library exists, so typeof says undefined and the call gives 'confetti is not defined'. You see that error the first time you get the order wrong, and also when the url of the library gives a 404.

<!-- slide 32 -->

### Your script.js calls new Accordion('.faq') and the console says Accordion is not defined. What is the first thing to check?

- A. Whether the FAQ has the right classes
- B. Whether the script tag of the library comes before script.js, and loads without a 404
- C. Whether the library supports your browser
- D. Whether the CSS file is linked

**Answer:** B. Whether the script tag of the library comes before script.js, and loads without a 404

'Not defined' means the name was never put on window when your code ran. Either the library came later in the page, or its url failed. A red 404 in the console tells you which.

> **Explanation:** Wrong classes and a missing CSS file never give this error: the library runs, it just finds nothing or looks broken. The Network tab of the DevTools lists every file the page loaded with its status, filter on JS and look for the red ones.

<!-- slide 33 -->

## 5. import

> **Explanation:** The chapter to take your time for. More and more docs only show npm install and import, and some newer libraries only ship as a module. Once you can translate those lines for a plain HTML page, nearly every library is open to you. Example 4 puts all of it to work.

<!-- slide 34 -->

### What the docs look like now

*README.md*

```md
npm install accordion-js

import Accordion from 'accordion-js';
import 'accordion-js/accordion.min.css';
```

- `npm install` downloads the package into your project.
- `import` pulls it into your script.
- A build tool then packs it all into one file for the browser.
- **A plain HTML page has no build tool.** So you need another way to the same lines.

> **Explanation:** npm install puts the package in a folder called node_modules in your project. A build tool like Vite finds it there and packs everything into the files the browser gets, the CSS import included. That setup comes in a later course. A plain HTML page has neither, so the npm install line becomes nothing, and the import points at a url instead of a name.

<!-- slide 35 -->

### What a module is

#### party.js

```js
export function cheer(name) {
  return 'Hip hip hooray for ' + name;
}

const secret = 'nobody sees this';
```

`export` shares `cheer`. `secret` has no export, so it stays inside this file.

#### main.js

```js
import { cheer } from './party.js';

console.log(cheer('Sam'));
console.log(secret); // ReferenceError
```

1. Takes cheer from party.js. The ./ means a file next to this one, and the .js is required: the browser does not guess.
2. cheer works here as if you wrote it in this file.
3. secret was never exported, so main.js cannot see it.

> **Explanation:** Start with your own files: a library is the same thing, written by somebody else. Without export nothing leaves a module, and that is a feature. Two modules can both have a variable called count without getting in each other's way, which was a classic bug with plain scripts that all share window. To see this run, make the two files in a folder of your own and open it with Live Server: a sandbox only has one file.

<!-- slide 36 -->

### type="module"

```html
<body>
  <button id="party">Party</button>

  <script type="module" src="script.js"></script>
</body>
```

- `import` and `export` only work in a module.
- A module waits for the page, like `defer`.
- A module in its own file needs a server. **Live Server**, never a double click.
- Its variables and functions stay in the file. They are not put on window.

> **Explanation:** Open index.html with a double click and the address bar says file://. A module in its own file then fails with a CORS error: the browser refuses to load it from your disk. A module written inside the HTML that only imports from a CDN does work from a double click, but on the exam you work with separate files, so: Live Server, always. A module also runs in strict mode, which turns a few silent mistakes into real errors.

<!-- slide 37 -->

### Straight from a CDN

The import from the docs, with the package name replaced by a url. Press Party and compare the two lines in the console.

```html
<button id="party">Party</button>

<script type="module">
  import confetti from 'https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/+esm';

  console.log(typeof confetti);
  console.log(typeof window.confetti);

  document.querySelector('#party').addEventListener('click', function () {
    confetti({ particleCount: 150, spread: 90 });
  });
</script>
```

> **Explanation:** jsDelivr turns any package into a module when you put /+esm at the end of its url, with everything it needs bundled in. The version after the @ works like before, so pin it. The imports of a module load before any of its code runs, which makes the order trouble of chapter 4 disappear.

<!-- slide 38 -->

### A name is not an address

The import from the docs, copied as it is. Run it and read the error: the browser has no idea where `canvas-confetti` lives.

```html
<button id="party">Party</button>

<script type="module">
  import confetti from 'canvas-confetti';

  document.querySelector('#party').addEventListener('click', function () {
    confetti();
  });
</script>
```

> **Explanation:** The error reads: Failed to resolve module specifier 'canvas-confetti', followed by a hint that relative references must start with /, ./ or ../. A build tool would look for canvas-confetti in node_modules. The browser only follows addresses, and a name on npm is not one. You will see this exact error every time you copy an import from the docs as it is. The fix is the slide before: a full CDN url in the import.

<!-- slide 39 -->

### Default or named

Run `named`, then `braces missing`, and read the error.

```html
<script type="module">
  import { format, addDays } from 'https://cdn.jsdelivr.net/npm/date-fns@4/+esm';

  const today = new Date();
  console.log(format(today, 'dd/MM/yyyy'));
  console.log(format(addDays(today, 7), 'EEEE d MMMM'));
</script>
```

*named*

```html
<script type="module">
  import { format, addDays } from 'https://cdn.jsdelivr.net/npm/date-fns@4/+esm';

  const today = new Date();
  console.log(format(today, 'dd/MM/yyyy'));
  console.log(format(addDays(today, 7), 'EEEE d MMMM'));
</script>
```

*braces missing*

```html
<script type="module">
  import format from 'https://cdn.jsdelivr.net/npm/date-fns@4/+esm';

  console.log(format(new Date(), 'dd/MM/yyyy'));
</script>
```

> **Explanation:** A default export is the main thing of a module: no braces, and you choose the name. Named exports go in braces under their own name, and a module can have dozens of them (date-fns has hundreds). The braces are not your choice, the docs decide. The error in the second preset says it plainly: the module does not provide an export named default.

<!-- slide 40 -->

### Three ways to import

| You read | You get |
| --- | --- |
| `import Accordion from '...'` | The default export, under a name you pick |
| `import { CountUp } from '...'` | One or more named exports, under their own name |
| `import * as THREE from '...'` | Every export, as one object |

Copy the shape the docs show and only change what comes after `from`. Mixing them up gives the error of the slide before.

> **Explanation:** The third one you meet in three.js examples and not much elsewhere: THREE.Scene, THREE.Mesh, everything hangs on one object. You can also rename a named export when two packages use the same name: import { format as formatDate } from '...'.

<!-- slide 41 -->

### From the docs to your page

| The docs say | Your page says |
| --- | --- |
| `npm install accordion-js` | Nothing. Skip it |
| `import Accordion from 'accordion-js'` | `import Accordion from 'https://cdn.jsdelivr.net/npm/accordion-js@4.0.0/+esm'` |
| `import 'accordion-js/accordion.min.css'` | a `<link>` to the CSS file on the CDN |
| `<script src="main.js">` | `<script type="module" src="main.js">` |

The name in the import becomes a url: the module file from dist when the library ships one, or `/+esm` on jsDelivr for any package.

> **Explanation:** This recipe works for nearly every package. When a package also needs CSS, that is still a link tag in the head: an import of a .css file only works with a build tool. And watch the file you pick: a file meant for a script tag and a file meant for import are not the same thing, example 1 runs into that.

<!-- slide 42 -->

### onclick cannot find it

Run it, press Party and read the error. Then load `addEventListener` and run again.

```html
<button onclick="party()">Party</button>

<script type="module">
  import confetti from 'https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/+esm';

  function party() {
    confetti();
  }
</script>
```

*onclick*

```html
<button onclick="party()">Party</button>

<script type="module">
  import confetti from 'https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/+esm';

  function party() {
    confetti();
  }
</script>
```

*addEventListener*

```html
<button id="party">Party</button>

<script type="module">
  import confetti from 'https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.4/+esm';

  function party() {
    confetti();
  }

  document.querySelector('#party').addEventListener('click', party);
</script>
```

> **Explanation:** The onclick attribute in the HTML looks for party on window, and a function in a module is never put there. So you get 'party is not defined' while the function is right there. One more reason to stick to addEventListener, like in the DOM lessons: it takes the function itself, no name has to be looked up.

<!-- slide 43 -->

### Script tag or import

|   | Script tag | Module with import |
| --- | --- | --- |
| You get the library | As a name on window | In an import, only where you ask for it |
| The order | Library first, your script after it | Does not matter, imports load first |
| Double click on the file | Works | A module in its own file fails. Live Server |
| Your functions | On window, onclick finds them | In the module, use addEventListener |
| You meet it in | Older libraries and tutorials | Nearly every doc written lately |

> **Explanation:** Both are fine, for this course and for small sites. The library decides which one you get: an old one only has the script tag, a new one only the module, most have both. In a real project you install with npm and a build tool like Vite takes care of the urls, and everything in this table still counts there. The npm and Vite deck of Extra Webdev (year 3) shows how that works, if you are curious.

<!-- slide 44 -->

### Your module says import confetti from 'canvas-confetti', and the console says: Failed to resolve module specifier. What fixes it?

- A. npm install canvas-confetti
- B. Add type="module" to the script tag
- C. A full CDN url in the import
- D. Load the library with a script tag first

**Answer:** C. A full CDN url in the import

The browser only follows addresses. npm install would put the package in node_modules, which the browser never looks in without a build tool. type="module" is already there, or the import would give another error. A url tells the browser where the package lives.

> **Explanation:** The script tag answer is tempting, because it does make confetti exist: the library puts its name on window. But the import line still fails and stops the whole module. You would have to remove the import, and then you are back at chapter 4.

<!-- slide 45 -->

### A module defines function party(). A button has onclick="party()". What happens on a click?

- A. The function runs
- B. ReferenceError: party is not defined
- C. Nothing, without an error
- D. The module is loaded again

**Answer:** B. ReferenceError: party is not defined

Functions in a module are not put on window, and the onclick attribute only looks there. Select the button in the module and use addEventListener, which takes the function itself.

> **Explanation:** You can force it with window.party = party in the module, and you will find that in some tutorials. It works, but it puts the name back on window, which is exactly what a module is meant to avoid.

<!-- slide 46 -->

## 6. Example: an accordion

> **Explanation:** From here on it is always the same story: I want something, I search, I pick, I read, I load, I use. Four times, each time with one new thing. This first one is the full walk, slowly, so take your time on every step.

<!-- slide 47 -->

**I want an accordion on my website.**

A list of questions where a click on a question opens its answer. Every FAQ page has one.

> **Explanation:** The four steps of chapter 1 in practice. The accordion is a good first one: you already know the HTML version with details, so you can judge what the library adds.

<!-- slide 48 -->

### Search

Google: **html javascript simple accordion library**

What the thing is, where it runs, and that you want something to load instead of something to build.

> **Explanation:** Say it in your head before you type: what is it, where does it run, and that you want something to load, not something to build. This query has worked for years and still does.

<!-- slide 49 -->

### Every word counts

Google: **html javascript simple accordion library**
- `html`: For a web page, not for an app.
- `javascript`: Not PHP, not a CSS trick.
- `simple`: Keeps the huge frameworks out.
- `accordion`: What you want. Know the name of the thing.
- `library`: Something to load. Plugin or package work too.

> **Explanation:** Every word throws a part of the results out. Leave out library and you get tutorials that make you type 80 lines. Leave out javascript and you get pure CSS tricks. Learning the name of the thing is half the work: accordion, collapsible, lightbox, carousel, toast. When you don't know the name, ask somebody, or an AI: what is this thing called?

<!-- slide 50 -->

### Words that help, words that hurt

- `vanilla` means plain JavaScript, no framework and no jQuery. Exactly what you want.
- `no dependencies` or `lightweight` keep the big ones out.
- A result with **React, Vue or Svelte** in the name is for that framework, not for your page.
- `jquery` in the name means a jQuery plugin. Fine, if you load jQuery too.
- Words in English. There are a hundred times more answers than in any local language.

> **Explanation:** Add vanilla to the query of the slide before, and half of the jQuery plugins and React components drop out of the results. On GitHub you can sort results by recently updated instead of best match, so the abandoned ones sink.

<!-- slide 51 -->

### Which result

- **[w3schools: How TO, Accordion](https://www.w3schools.com/howto/howto_js_accordion.asp)**: A tutorial. **You write it yourself.**
- **[jQuery UI Accordion](https://jqueryui.com/accordion/)**: Needs jQuery and jQuery UI.
- **[react-accessible-accordion](https://www.npmjs.com/package/react-accessible-accordion)**: Only works in React.
- **[michu2k/Accordion on GitHub](https://github.com/michu2k/Accordion)**: A library. **This one.**

> **Explanation:** Four kinds of results you get for this query, every time, and all four links are real. w3schools is fine to learn how an accordion works, but then you build and maintain it yourself, and that is not what you are after here. jQuery UI and the React one are libraries, for something you are not using. The GitHub repo is the one: a README, a dist folder, a CDN url.

<!-- slide 52 -->

### Is it any good

- Is there a demo that does what I want?
- When was the last release?
- Does it need anything else, like jQuery?
- Can I load it from a CDN?
- Which license?
- How big is it?

**accordion-js**: A demo on its site, version 4.0.0 this autumn, no dependencies, a CDN in the README, MIT, 1.9 kB.

> **Explanation:** The six places on the GitHub page from chapter 2, now as questions. All green for accordion-js. Ninety seconds of checking, and you know you are not going to spend the afternoon on a dead library. Use the same six questions on every library in the exercises.

<!-- slide 53 -->

### Read the README

*README.md*

```md
###### Package manager
npm install accordion-js
import Accordion from "accordion-js";
import "accordion-js/accordion.min.css";

###### CDN
https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.css
https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.js
<link rel="stylesheet" href="[CDN CSS URL]" />
<script src="[CDN JS URL]"></script>
```

1. Package manager: npm and import. That needs a build tool, so not this time.
2. CDN: two urls, and two tags with a placeholder where the url goes. This is the way for a plain HTML page.

> **Explanation:** The installation part of the README, with the blank lines and a sentence or two taken out. Note the [CDN CSS URL] placeholders: the README expects you to fill those in yourself, with the two urls right above them. The package manager way is what chapter 5 translated, it comes back in example 4.

<!-- slide 54 -->

### Fill in the blanks

*README*

```html
<link rel="stylesheet" href="[CDN CSS URL]" />
<script src="[CDN JS URL]"></script>
```

*index.html*

```html
<head>
  <link rel="stylesheet" href="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.css">
</head>
<body>
  ...
  <script src="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.js"></script>
  <script src="script.js"></script>
</body>
```

> **Explanation:** The link goes in the head, the script at the bottom of the body, before your own script.js: the same order as chapter 4. The README uses unpkg, the CDN url in chapter 2 used jsDelivr. Same file, other CDN, both fine.

<!-- slide 55 -->

### The HTML it expects

```html
<div class="accordion-container">
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Do I need a laptop?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">Yes, every lesson.</p>
    </div>
  </div>
</div>
```

1. The container: the whole accordion.
2. One item, with the class `ac`. Repeat it per question.
3. The question, a button inside a heading.
4. The answer, hidden until you click the question.

> **Explanation:** The README gives the layout. The class names are how the library finds its pieces. Copy the structure and change the text. Rename a class and the library no longer finds it, unless you tell it the new name in the options. The button inside a heading is not random: a screen reader can jump from heading to heading, and the button works with the keyboard.

<!-- slide 56 -->

### Start it

*script.js*

```js
new Accordion('.accordion-container');
```

- `Accordion` is the name the library left behind.
- `new` makes one accordion. Libraries use it a lot.
- `'.accordion-container'` is a selector, like in `querySelector`.

> **Explanation:** One line in script.js, the way the README says it. You will see new a lot in library docs: read it as 'make me an Accordion on this element'. When a page has two accordions, you write the line twice, with two different selectors.

<!-- slide 57 -->

### Together

The link, the HTML, the library and the line that starts it, in one page. Run it and click the questions: opening one closes the other.

```html
<link rel="stylesheet" href="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.css">

<div class="accordion-container">
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Do I need a laptop?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">Yes, every lesson.</p>
    </div>
  </div>
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Is the exam open book?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">Yes, and Google is allowed.</p>
    </div>
  </div>
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Can I use a library?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">That is the whole point of this lesson.</p>
    </div>
  </div>
</div>

<script src="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.js"></script>
<script>
  new Accordion('.accordion-container');
</script>
```

> **Explanation:** This is the whole page: the CSS from the CDN, the HTML from the README, the library and the line that starts it. The script tag with your own code is inline here because a sandbox has one file. On your laptop that line goes in script.js.

<!-- slide 58 -->

### Options

Two options: several items open at once, and a faster animation. Change `showMultiple` to `false` and run again.

```html
<link rel="stylesheet" href="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.css">

<div class="accordion-container">
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Do I need a laptop?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">Yes, every lesson.</p>
    </div>
  </div>
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Is the exam open book?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">Yes, and Google is allowed.</p>
    </div>
  </div>
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Can I use a library?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">That is the whole point of this lesson.</p>
    </div>
  </div>
</div>

<script src="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.js"></script>
<script>
  new Accordion('.accordion-container', {
    showMultiple: true,
    duration: 200,
  });
</script>
```

> **Explanation:** Every library takes an object with options, and the README lists them all in a table, with their default value. Take the option names from the README, never from memory: an option the library does not know is ignored without a word, so a typo gives no error at all.

<!-- slide 59 -->

### Copied from the CDN site instead

![The jsDelivr page of accordion-js, suggesting a script tag for dist/index.min.js](https://slides.mctantwerp.be/decks/en/webcoding/07-javascript-libraries/jsdelivr-accordion.jpg)

- jsDelivr suggests `dist/index.min.js`.
- The README says `dist/accordion.min.js`.
- **The CDN site guesses. The README knows.**

> **Explanation:** A real trap. The jsDelivr page of accordion-js offers a script tag with dist/index.min.js, which is the module version of the library. jsDelivr picks that file from the package settings, it does not read the README. When the CDN site and the README disagree, follow the README.

<!-- slide 60 -->

### Unexpected token 'export'

The same page, with the file jsDelivr suggests. Run it and read both errors in the console.

```html
<link rel="stylesheet" href="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.css">

<div class="accordion-container">
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Do I need a laptop?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">Yes, every lesson.</p>
    </div>
  </div>
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Is the exam open book?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">Yes, and Google is allowed.</p>
    </div>
  </div>
  <div class="ac">
    <h2 class="ac-header">
      <button type="button" class="ac-trigger">Can I use a library?</button>
    </h2>
    <div class="ac-panel">
      <p class="ac-text">That is the whole point of this lesson.</p>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/accordion-js@4.0.0/dist/index.min.js"></script>
<script>
  new Accordion('.accordion-container');
</script>
```

> **Explanation:** The first error: the file is a module, it ends with export, and a classic script tag does not understand that word. The second is the consequence: the library never ran, so Accordion is not defined. When you see export in an error, you are loading a module the old way. Either take the other file, or import it like in chapter 5.

<!-- slide 61 -->

### Getting it to work

- **Read the instructions.** The README or the getting started page, top to bottom.
- Start from their example, get it working, and only then make it yours.
- The CSS file is not optional. Without it most libraries look broken.
- Nothing happens? The console says why: a 404, a name that is not defined, an unexpected token.
- Some work right away. Some need fiddling. Some never work. Give it half an hour, then pick another.
- Being on the internet does not make it good, or even working.

> **Explanation:** The 404 is the most common one: a url copied with a typo, or a file path that changed between versions. Keep this list next to you for the exercises: nearly every problem you will have is one of these.

<!-- slide 62 -->

## 7. Example: a lightbox

> **Explanation:** The new thing in this example is searching. Google is not the only place: GitHub and the CDN sites have a search of their own, and each one shows you something the others do not.

<!-- slide 63 -->

**I want a lightbox on my website.**

Click a thumbnail and the picture opens big, on top of the page. Arrows to the next one, Esc to close.

> **Explanation:** You have used a lightbox a hundred times, on every webshop and in every photo gallery, probably without knowing it is called that. Knowing the name is half the search.

<!-- slide 64 -->

### Search

Google: **html javascript simple lightbox library**

The same pattern as the accordion. Only the thing changed.

> **Explanation:** Only one word changed compared to the accordion. Keep the rest of the query as a template: html javascript simple [the thing] library.

<!-- slide 65 -->

### Or search GitHub

github.com: **lightbox**

GitHub has its own search box, at the top of every page. Pick Repositories and sort by most stars.

> **Explanation:** On GitHub you search for the thing itself, without html or javascript: everything there is code anyway. The filter on the left lets you pick a language, JavaScript or TypeScript, when a search returns too much.

<!-- slide 66 -->

### Sorted by stars

![GitHub search results for lightbox, sorted by stars: PhotoSwipe, Magnific-Popup, fancybox, lightGallery, lightbox2](https://slides.mctantwerp.be/decks/en/webcoding/07-javascript-libraries/github-search.jpg)

Look at the tags and the dates, not only at the stars.

> **Explanation:** PhotoSwipe on top, then Magnific Popup and fancybox. The stars say what was popular, not what is good today: fancybox is archived and says jQuery, Magnific Popup is a jQuery plugin too, last updated in 2024.

<!-- slide 67 -->

### Or search the CDN

![cdnjs search results for lightbox: photoswipe, magnific-popup, lightgallery, fancybox, lightbox2](https://slides.mctantwerp.be/decks/en/webcoding/07-javascript-libraries/cdnjs-lightbox.jpg)

A library you find on a CDN site is on a CDN by definition, so step 2 is done.

> **Explanation:** cdnjs shows the version and a line of description per library. Read the descriptions: 'plugin for jQuery' three times on the first screen.

<!-- slide 68 -->

### Read the labels

![jsDelivr search results for lightbox, with lightbox2 marked Deprecated and 'Uses jQuery' in its description](https://slides.mctantwerp.be/decks/en/webcoding/07-javascript-libraries/jsdelivr-search.jpg)

jsDelivr labels every result: ESM ships as a module, JS as a classic script, Styles has CSS. And Deprecated means: walk away.

> **Explanation:** lightbox2 is the library of the old slides of this course. It is in maintenance mode now: 81 million downloads, and still a no. Its description says why: it uses jQuery.

<!-- slide 69 -->

### The candidates

| Library | Needs | Status |   |
| --- | --- | --- | --- |
| PhotoSwipe | Nothing, but a module setup | Release in 2024 | Good, harder start |
| lightbox2 | jQuery | Deprecated | No |
| fancybox | jQuery | Archived on GitHub | No |
| GLightbox | Nothing | Release in 2025 | **This one** |

> [!TIP]
> The most stars is not always the easiest start. Building it with [GLightbox](https://biati-digital.github.io/glightbox/) is the first exercise.

> **Explanation:** Four names that came back in all three searches. PhotoSwipe is excellent, but its docs start with import and a second module that loads the first one, a lot for a first lightbox. GLightbox has no dependencies, a script tag in the README and a release in 2025.

<!-- slide 70 -->

## 8. Example: a carousel

> **Explanation:** The new thing in this example is asking an AI. It is good at some parts of the search and bad at others, and what you ask decides which one you get.

<!-- slide 71 -->

**I want an image carousel on my website.**

A row of pictures that slides, with arrows, dots and a swipe on a phone.

> **Explanation:** Also called a slider. The libraries use both words mixed, so search for both.

<!-- slide 72 -->

### Search

Google: **html javascript library simple image slider carousel**

Carousel and slider both, because the libraries use both words.

> **Explanation:** Two names for the same thing in one query. Google is fine with that, it finds pages with either word.

<!-- slide 73 -->

**Or ask an AI.**

GPTutor, ChatGPT, Claude or Gemini. What you ask decides what you get.

> **Explanation:** Allowed for everything while you learn. On the exam only GPTutor, and only for questions. The next four slides are prompts and the answer you get back, summarised. Try them yourself: the answers differ a little every time, the pattern does not.

<!-- slide 74 -->

### Asking for code

**You:** I want to make an image carousel in javascript

**AI:** Sure! Here is a simple image carousel. A div with three images, two buttons, forty lines of CSS and thirty of JavaScript. No swipe, no keyboard, no dots.

👎 You asked for code, so you got code. Now it is yours to fix. You wanted a library.

> **Explanation:** The prompt most people type first. The AI does exactly what you asked: it writes a carousel. Your own carousel, from scratch, that you now have to fix and maintain. It has no swipe and no keyboard, and it breaks with pictures of different sizes.

<!-- slide 75 -->

### Asking for libraries

**You:** Do you know any good image carousel libraries I can use in JavaScript?

**AI:** Slick, Swiper, Owl Carousel, Flickity and Glide.js. Each with a line on how popular and flexible it is.

👍 A list of names to check. That is what AI is good at. Now check every one of them.

> **Explanation:** Same question, but for libraries. This is what an AI is good at: a list of names to check. These five come back nearly every time.

<!-- slide 76 -->

### The list, checked

| Library | Needs | Last release | License |
| --- | --- | --- | --- |
| Slick | jQuery | 2026 | MIT |
| Owl Carousel | jQuery | **2018** | MIT |
| Flickity | Nothing | 2022 | **GPL, paid for clients** |
| Glide.js | Nothing | 2024 | MIT |
| **Swiper** | Nothing | 2026 | MIT |

Two need jQuery, one has not moved since 2018, one costs money on a client site. Swiper is the pick.

> **Explanation:** Five minutes on GitHub and npm. Owl Carousel had no release since 2018 and needs jQuery, and the AI still recommends it. Slick got a version 2 this year, but still needs jQuery. Flickity is GPL: free for open source, a paid licence for a client site. Glide.js is fine. Swiper is the one I would pick: no dependencies, recent releases, and its docs have a CDN page.

<!-- slide 77 -->

### Asking with your checklist

**You:** Give me three vanilla JavaScript carousel libraries that are still maintained, need no jQuery and load from a CDN. Link to their docs.

**AI:** Swiper, Glide.js and Splide. Each with a link to its docs and a CDN script tag.

👍 Your checklist is in the question. Still check the answer: Splide had no release since 2022.

> **Explanation:** Put the checklist in the question and you get fewer old favourites in the answer. And still: Splide had no release since 2022, so maintained is a stretch. The AI does not check, you do.

<!-- slide 78 -->

### Asking for an example

**You:** Show me the smallest working example of Swiper 14 with a script tag from jsDelivr: three images and arrows.

**AI:** A link tag for the CSS and a script tag for Swiper. The swiper, swiper-wrapper and swiper-slide divs. new Swiper('.swiper', { ... }) with loop and navigation.

👍 The version, the way you load it and what you want, all in the question. Compare it with the Get started page.

> **Explanation:** Once you picked one, ask for the smallest working example, with the version and the way you load it in the question. Then compare it with the Get started page of Swiper. Version numbers and option names are where an AI gets it wrong most: it learned from old pages.

<!-- slide 79 -->

### Ask the AI, check the answer

- Good at a list of candidates, and at a first example for your case.
- Likes old favourites. **Owl Carousel** still shows up: last release 2018, needs jQuery.
- Versions, option names and urls are sometimes made up. Copy them from the docs.
- Every suggestion goes past the same checks as a result from Google.

**[GPTutor](https://app.gptutor.be)**: The one allowed on the exam, with your KdG account. For questions, not for whole solutions.

> **Explanation:** The links are often right, sometimes a version is invented, now and then the whole package. That last one is dangerous: people register the package names that AIs make up and put malware in them. So every name goes past npmjs.com before it goes in your page.

<!-- slide 80 -->

### The result

The Get started page of Swiper: the CSS, the HTML, the script and `new Swiper` with two options. Run it and drag with the mouse.

```html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@14/swiper-bundle.min.css">
<style>
  .swiper { height: 300px; }
  .swiper img { width: 100%; height: 100%; object-fit: cover; }
</style>

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide"><img src="https://picsum.photos/id/1015/900/450" alt="A river in a valley"></div>
    <div class="swiper-slide"><img src="https://picsum.photos/id/1016/900/450" alt="Rocks in a canyon"></div>
    <div class="swiper-slide"><img src="https://picsum.photos/id/1018/900/450" alt="Mountains"></div>
  </div>
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/swiper@14/swiper-bundle.min.js"></script>
<script>
  new Swiper('.swiper', {
    loop: true,
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
  });
</script>
```

> **Explanation:** Same pattern as the accordion: a container with classes, one line to start it, an object with options. The style block only gives the carousel a height, Swiper needs one to know how big the slides are. The carousel exercise builds on this, with dots and autoplay, and Swiper loaded with import.

<!-- slide 81 -->

### The install steps of a carousel library start with a script tag for jquery.min.js. What does that mean for your page?

- A. Nothing, it is a suggestion
- B. You load jQuery too, before the library
- C. The library only works in old browsers
- D. You need npm

**Answer:** B. You load jQuery too, before the library

The library is a jQuery plugin and calls jQuery itself. Without it, the console says $ is not defined. Next lesson is about jQuery, and from then on you can read those plugins too.

> **Explanation:** You recognise a jQuery plugin by examples that look like $('.carousel').slick(). Slick, Owl Carousel and lightbox2 all are. They still work, they just bring about 30 KB of jQuery along.

<!-- slide 82 -->

## 9. Example: numbers that count up

> **Explanation:** The new thing in this example: a library whose README only shows import. Everything from chapter 5 comes back, in a real case.

<!-- slide 83 -->

**I want numbers that count up.**

1200 students, 35 nationalities, 4 campuses: counting up from zero when you scroll to them.

> **Explanation:** Every agency site has this somewhere. A good one for import, because the library behind it is a module first.

<!-- slide 84 -->

### Search

Google: **javascript count up number animation library**

No short name for this one, so describe it.

> **Explanation:** When there is no short name for the thing, describe what it does and add library. The results teach you the name: count up, counter, number animation.

<!-- slide 85 -->

### countUp.js

- A demo page that does exactly this.
- A release this year, no dependencies, MIT.
- The README: **"CountUp is distributed as an ES module"**.

**[github.com/inorganik/countUp.js](https://github.com/inorganik/countUp.js)**: The README with the install steps.

**[The demo](https://inorganik.github.io/countUp.js/)**: Every option, to try out.

> **Explanation:** The first result, every time. The same six questions as for the accordion, and all green. The demo page lets you change every option and see the result, which is a quick way to find the options you want before you read the README.

<!-- slide 86 -->

### The README says module

*README.md*

```md
CountUp is distributed as an ES module.

npm i countup.js

import { CountUp } from './js/countUp.min.js';

Include in your html. Notice the type attribute:
<script src="./main.js" type="module"></script>
```

1. A module: no script tag of its own, you import it.
2. npm needs a build tool. Skip it.
3. An import with braces: CountUp is a named export.
4. Your own script needs type="module", or the import fails.

> **Explanation:** From the README, shortened. Everything from chapter 5 in eight lines. The import points at a file in their own js folder: they expect you to download the library. That path is the part you change.

<!-- slide 87 -->

### The old way first

Treated like the accordion: a script tag with the file from dist. Run it and read the console.

```html
<p><span id="students">0</span> students</p>

<script src="https://cdn.jsdelivr.net/npm/countup.js@2.10.1/dist/countUp.min.js"></script>
<script>
  const counter = new CountUp('students', 1200);
  counter.start();
</script>
```

> **Explanation:** The same two errors as the wrong accordion file in example 1. This time there is no other file to pick: this library is a module and nothing else, so it needs an import.

<!-- slide 88 -->

### Translate the README

| The README says | Your page says |
| --- | --- |
| `npm i countup.js` | Nothing. Skip it |
| `from './js/countUp.min.js'` | `from 'https://cdn.jsdelivr.net/npm/countup.js@2.10.1/dist/countUp.min.js'` |
| `<script type="module">` | `<script type="module">` |
| `{ CountUp }` | The same, **with the braces** |

> **Explanation:** Three lines from the README, three changes. Skip the npm line. The path in the import becomes the CDN url of the same file. And type module on the script, which the README already said. The file ships as a module of its own, so you do not need /+esm here: the file from dist is the module.

<!-- slide 89 -->

### With import

Run `braces`: the number counts to 1200. Then `no braces`, and read the error.

```html
<p><span id="students">0</span> students</p>

<script type="module">
  import { CountUp } from 'https://cdn.jsdelivr.net/npm/countup.js@2.10.1/dist/countUp.min.js';

  const counter = new CountUp('students', 1200);
  counter.start();
</script>
```

*braces*

```html
<p><span id="students">0</span> students</p>

<script type="module">
  import { CountUp } from 'https://cdn.jsdelivr.net/npm/countup.js@2.10.1/dist/countUp.min.js';

  const counter = new CountUp('students', 1200);
  counter.start();
</script>
```

*no braces*

```html
<p><span id="students">0</span> students</p>

<script type="module">
  import CountUp from 'https://cdn.jsdelivr.net/npm/countup.js@2.10.1/dist/countUp.min.js';

  const counter = new CountUp('students', 1200);
  counter.start();
</script>
```

> **Explanation:** The module has no default export, so without the braces the browser says so, word for word. The docs decide about the braces, not you.

<!-- slide 90 -->

### When you scroll to it

Options from the README. Run it and scroll down in the page on the right.

```html
<p style="height: 500px">Scroll down</p>
<p><span id="students">0</span> students</p>

<script type="module">
  import { CountUp } from 'https://cdn.jsdelivr.net/npm/countup.js@2.10.1/dist/countUp.min.js';

  new CountUp('students', 1200, {
    separator: '.',
    duration: 3,
    autoAnimate: true,
  });
</script>
```

> **Explanation:** autoAnimate starts the counter when the number scrolls into view, so there is no start() any more. separator is a dot, because we write 1.200 in Belgium. Every other option is in the README and on the demo page.

<!-- slide 91 -->

### In your own files

*script.js*

```js
import { CountUp } from 'https://cdn.jsdelivr.net/npm/countup.js@2.10.1/dist/countUp.min.js';

new CountUp('students', 1200, { autoAnimate: true });
```

*index.html*

```html
<p><span id="students">0</span> students</p>

<script type="module" src="script.js"></script>
```

> [!TIP]
> **Live Server**
>
> It counts.

> [!WARNING]
> **Double click**
>
> Blocked by CORS policy: the browser does not load a module from a file on your disk.

> **Explanation:** On your laptop the code goes in script.js, like always, and the script tag gets type module. The README of countUp warns about the CORS error too. When you see it, check the address bar: file:// means you double clicked, http://127.0.0.1 means Live Server.

<!-- slide 92 -->

### A library's README only shows import { Chart } from 'chart.js'. You have a plain HTML page. What do you write?

- A. npm install chart.js, then the same import
- B. import { Chart } from 'https://cdn.jsdelivr.net/npm/chart.js@4/+esm' in a script with type="module"
- C. import Chart from 'chart.js' in a classic script tag
- D. Nothing, a library with import does not work without a build tool

**Answer:** B. import { Chart } from 'https://cdn.jsdelivr.net/npm/chart.js@4/+esm' in a script with type="module"

The name becomes a CDN url, the braces stay because the docs use them, and import only works in a module. npm install needs a build tool, which a plain page does not have. The third answer goes wrong three times: no url, no braces, and import in a classic script.

> **Explanation:** /+esm is the way when a package does not ship a module file of its own, or when you do not know which file it is. When the README or the dist folder does name a module file, like countUp.min.js, that file works too.

<!-- slide 93 -->

## 10. Exercises

> **Explanation:** Five exercises, homework for the next lesson on 7 December, where we go over them together. Do the lightbox, the date picker and the accordion with a script tag, and the carousel with import, so you have done both once. The last one is your own pick.

<!-- slide 94 -->

### How it works

- **One folder per exercise**, each with its own index.html, style.css and script.js.
- Find the library yourself. The library in the solution is one option, not the answer.
- Every library url carries a version.
- Opened with Live Server, with the console open. A module does not work any other way.
- Stuck for more than ten minutes? Ask a classmate or ask on Discord, then look at the solution behind the 😵.
- We go over every exercise together on 7 December. Bring what you have, also when it does not work yet.

> **Explanation:** The solutions sit behind the dizzy face at the bottom of each exercise, with a 'sure?' first. They use the library I would pick. If you found another one that works, even better, bring it along. Questions go to the #help-needed forum on Discord, with a screenshot of your code and of the console.

<!-- slide 95 -->

### Task: Lightbox

Done when six thumbnails open big on a click, with arrows between them and a caption under each one.

1. A gallery of six thumbnails. A click opens the picture big, on top of the page.
2. Arrows or a swipe go to the next and the previous picture, Esc closes it.
3. A caption under every picture.
4. Pictures: [picsum.photos](https://picsum.photos), or your own.

> [!TIP]
> **Lightbox**
>
> *GLightbox*
>
> Every link with the class glightbox opens in the lightbox. The same data-gallery puts them in one set with arrows.
>
> *index.html*
>
> ```html
> <head>
>   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/glightbox@3.3.1/dist/css/glightbox.min.css">
> </head>
> <body>
>   <a href="https://picsum.photos/id/1015/1600/1000" class="glightbox" data-gallery="trip" data-title="The fjord">
>     <img src="https://picsum.photos/id/1015/300/200" alt="A river in a valley">
>   </a>
>   <!-- five more like this -->
>
>   <script src="https://cdn.jsdelivr.net/npm/glightbox@3.3.1/dist/js/glightbox.min.js"></script>
>   <script src="script.js"></script>
> </body>
> ```
>
> *script.js*
>
> ```js
> GLightbox({ selector: '.glightbox' });
> ```

> **Explanation:** Chapter 7 already did the search, 'The candidates' has the pick. Start from the example in the README, with two pictures, and get that working before you add the rest. picsum.photos/id/1015/300/200 gives the same picture every time at that size, so change the last two numbers for the big version. Nothing happens on a click? Look at 'Getting it to work' at the end of chapter 6.

<!-- slide 96 -->

### Task: Date picker

Done when Mondays and past dates cannot be picked, the calendar speaks Dutch, and a submit shows the booking in the page.

1. A booking form for a table in a restaurant: a name, a date and a number of guests.
2. Only dates from tomorrow on, never on a Monday (closed).
3. The calendar in Dutch, and the date shown as 24/12/2026.
4. On submit, the booking in a sentence in the page. The forms lesson still counts.

> [!TIP]
> **Date picker**
>
> *flatpickr*
>
> The Dutch texts are a second file from the same package. disable takes a function that returns true for every date that cannot be picked.
>
> *index.html*
>
> ```html
> <script src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js"></script>
> <script src="https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/l10n/nl.js"></script>
> <script src="script.js"></script>
> ```
>
> *script.js*
>
> ```js
> flatpickr('#date', {
>   locale: 'nl',
>   dateFormat: 'd/m/Y',
>   minDate: new Date().fp_incr(1),
>   disable: [
>     function (date) {
>       return date.getDay() === 1;
>     },
>   ],
> });
> ```

> **Explanation:** This one starts with a search of your own: the four steps of chapter 1, like the examples. flatpickr is on the Warm water slide in chapter 1. Look for options with names like minDate, disable and locale in the docs of your date picker. The Dutch texts are often a separate file of the same package, loaded after the library. For the submit: preventDefault, then read the values, like in the forms lesson.

<!-- slide 97 -->

### Task: Accordion

Done when both versions work, and a comment at the top of script.js says which one you would put on a client site.

1. An FAQ with five questions. A click on a question opens its answer.
2. First build it without a library, with `<details>` and `<summary>`.
3. Then with a library, where opening one question closes the one that was open.
4. Compare: which one would you pick, and why? One sentence in that comment.

> [!TIP]
> **Accordion**
>
> *details*
>
> Give every details the same name and the browser keeps only one open. Supported everywhere since 2024, so the library is barely needed for this.
>
> *index.html*
>
> ```html
> <details name="faq">
>   <summary>Do I need a laptop?</summary>
>   <p>Yes, every lesson.</p>
> </details>
> <details name="faq">
>   <summary>Is the exam open book?</summary>
>   <p>Yes, and Google is allowed.</p>
> </details>
> ```
>
> *accordion-js*
>
> *index.html*
>
> ```html
> <link rel="stylesheet" href="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.css">
>
> <div class="accordion-container">
>   <div class="ac">
>     <h2 class="ac-header">
>       <button type="button" class="ac-trigger">Do I need a laptop?</button>
>     </h2>
>     <div class="ac-panel"><p class="ac-text">Yes, every lesson.</p></div>
>   </div>
>   <!-- four more like this -->
> </div>
>
> <script src="https://unpkg.com/accordion-js@4.0.0/dist/accordion.min.js"></script>
> <script src="script.js"></script>
> ```
>
> *script.js*
>
> ```js
> new Accordion('.accordion-container');
> ```

> **Explanation:** The first version needs no JavaScript at all, see 'Zero lines of JavaScript' in chapter 1. The library version is example 1 step by step: chapter 6 has the README, the HTML and the line that starts it. The comparison is the point of the exercise: weigh the bytes, the keyboard, the styling and how much work each one was.

<!-- slide 98 -->

### Task: Carousel with import

Done when the carousel moves on by itself, stops under the mouse, and Swiper is loaded with an import, without a script tag.

1. A carousel of five pictures, with arrows, dots under it and a loop at the end.
2. Load the library as a module: `<script type="module">` and an import, no script tag for the library.
3. It moves on by itself every 4 seconds, and stops when the mouse is on it.
4. Extra: numbers under the carousel that count up when you scroll to them, also with an import.

> [!TIP]
> **Carousel with import**
>
> *index.html*
>
> *index.html*
>
> ```html
> <head>
>   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@14/swiper-bundle.min.css">
> </head>
> <body>
>   <div class="swiper">
>     <div class="swiper-wrapper">
>       <div class="swiper-slide"><img src="https://picsum.photos/id/1015/1200/600" alt="A river"></div>
>       <!-- four more like this -->
>     </div>
>     <div class="swiper-pagination"></div>
>     <div class="swiper-button-prev"></div>
>     <div class="swiper-button-next"></div>
>   </div>
>   <p><span id="pictures">0</span> pictures taken</p>
>
>   <script type="module" src="script.js"></script>
> </body>
> ```
>
> *script.js*
>
> *script.js*
>
> ```js
> import Swiper from 'https://cdn.jsdelivr.net/npm/swiper@14/swiper-bundle.min.mjs';
> import { CountUp } from 'https://cdn.jsdelivr.net/npm/countup.js@2.10.1/dist/countUp.min.js';
>
> new Swiper('.swiper', {
>   loop: true,
>   autoplay: { delay: 4000, pauseOnMouseEnter: true },
>   pagination: { el: '.swiper-pagination', clickable: true },
>   navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev' },
> });
>
> new CountUp('pictures', 2400, { separator: '.', autoAnimate: true });
> ```

> **Explanation:** 'The result' in chapter 8 is your starting point, loaded with a script tag. Swiper also ships a module file of its own, swiper-bundle.min.mjs, so turning it into an import works like countUp in chapter 9. Get the import working with an empty carousel first and check the console, before you add any options. Dots and autoplay are options in the Swiper docs.

<!-- slide 99 -->

### Task: Your own pick

Search for something you want on your own site, and get it working. Done when it runs without a red line in the console. A few ideas:

1. A chart of your screen time this week.
2. A map with the five best fries shops of Antwerp.
3. Text that types itself, letter by letter.
4. Extra challenge: a page with a parallax effect on scroll.

> **Explanation:** No solution here, every pick is different. Chart.js, Leaflet and Typed.js are the obvious picks for the first three, GSAP with ScrollTrigger or plain CSS for the parallax. Run every candidate past the six questions of 'Is it any good' in chapter 6 before you spend an evening on it. Post a link or a screen recording in the class channel on Discord.

<!-- slide 100 -->

### Next up

- **30/11** JavaScript libraries: Self-study
- **07/12** jQuery: And the exercises of this deck, together
- **14/12** JavaScript & AI
- **04/01** Mock exam

> **Explanation:** The next lesson starts with the five exercises of this deck, then jQuery. It showed up four times in this deck already: a lightbox that needs it, two carousels that need it, and the AI that keeps recommending plugins for it. It is old, it is everywhere, and you will meet it on every second WordPress site.

## Glossary

- **Library**: Code somebody else wrote and shares, so you can use a carousel, a date picker or a chart without building it. You call the library, it does not decide how your page works. (slide 7)
- **GitHub**: The site that holds the source code of nearly every open source library. The front page of a repository shows the files, the README, the stars and the latest release. (slide 12)
- **README**: The file on the front page of a library that says what it does, how to load it and how to use it. Read it before anything else. (slide 53)
- **npm**: The registry where nearly every JavaScript library is published, and the tool that installs them. Its page per package shows the version, the weekly downloads and the last publish date. (slide 14)
- **CDN**: Content Delivery Network. Servers all over the world that host files close to the visitor. jsDelivr, unpkg and cdnjs host the libraries on npm, so a script tag with their url is enough. (slide 15)
- **Semantic versioning**: A version as three numbers, major.minor.patch. A patch fixes bugs, a minor adds features, a major may break the code that uses it. (slide 20)
- **Minified**: A copy of a file without comments, spaces and long names, so it downloads faster. Usually ends in .min.js. Not meant to be read: you read the original in src. (slide 22)
- **Bundle size**: How many kilobytes a library adds to your page. Every visitor downloads them. Bundlephobia shows it for any package on npm. (slide 25)
- **dist**: Short for distribution: the folder of a library with the built files that are ready to use. src holds the source code the authors work on. (slide 26)
- **jQuery plugin**: A library built on top of jQuery. It only works when jQuery is loaded first. Without it the console says $ is not defined. (slide 28)
- **Global variable**: A name on window that any script on the page can use. A library loaded with a classic script tag hands you its function that way, like confetti or Accordion. (slide 31)
- **Module**: A JavaScript file that says what it needs with import and what it shares with export. Its variables stay inside the file. Loaded with type="module". (slide 35)
- **import**: Pulls a function, an object or a value from another module into yours. Only at the top level of a module, and only in a script with type="module". (slide 35)
- **Bare specifier**: An import of a package by its name only, like 'canvas-confetti'. A build tool knows where to find it, a browser does not. Replace it with a full CDN url. (slide 38)
- **Default export**: The one main thing a module shares, imported without braces under a name you choose. A named export is imported in braces, under its own name. (slide 39)

## Links and sources

### In the deck

- [Discord](https://kdgmt.be/discord) (slide 3, slide 101)
- [Swiper](https://swiperjs.com) (slide 7)
- [GLightbox](https://biati-digital.github.io/glightbox/) (slide 7, slide 69)
- [flatpickr](https://flatpickr.js.org) (slide 7)
- [Chart.js](https://www.chartjs.org) (slide 7)
- [GSAP](https://gsap.com) (slide 7)
- [Leaflet](https://leafletjs.com) (slide 7)
- [SortableJS](https://sortablejs.github.io/Sortable/) (slide 7)
- [canvas-confetti](https://www.kirilv.com/canvas-confetti/) (slide 7)
- [github.com](https://github.com) (slide 12)
- [accordion-js on GitHub](https://github.com/michu2k/Accordion) (slide 12, slide 51): Example 1, its README shows both the CDN and the import way
- [npmjs.com](https://www.npmjs.com) (slide 14)
- [npmjs.com/package/accordion-js](https://www.npmjs.com/package/accordion-js) (slide 14)
- [jsDelivr](https://www.jsdelivr.com) (slide 16)
- [unpkg](https://unpkg.com) (slide 16)
- [cdnjs](https://cdnjs.com) (slide 16)
- [esm.sh](https://esm.sh) (slide 16): Turns any npm package into a module the browser can import
- [Bundlephobia](https://bundlephobia.com) (slide 25): How many kB a package adds to your page
- [w3schools: How TO, Accordion](https://www.w3schools.com/howto/howto_js_accordion.asp) (slide 51)
- [jQuery UI Accordion](https://jqueryui.com/accordion/) (slide 51)
- [react-accessible-accordion](https://www.npmjs.com/package/react-accessible-accordion) (slide 51)
- [GPTutor](https://app.gptutor.be) (slide 79)
- [countUp.js on GitHub](https://github.com/inorganik/countUp.js) (slide 85): Example 4, distributed as an ES module first
- [The demo](https://inorganik.github.io/countUp.js/) (slide 85)
- [picsum.photos](https://picsum.photos) (slide 95)

### Sources

- [Swiper, get started](https://swiperjs.com/get-started)
- [JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules): The MDN guide on import and export
- [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
- [jsDelivr documentation](https://www.jsdelivr.com/documentation): The /+esm url that turns a package into a module
- [Semantic versioning](https://semver.org)
