Web APIs: observers, clipboard, canvas and more
Tour the browser's built-in toolbox: IntersectionObserver, clipboard, URL, canvas, files and other APIs.
In this lesson you will
- Reveal elements on scroll with IntersectionObserver
- Copy, share and build URLs
- Draw on a canvas
- Use new APIs safely with feature checks
About 21 minutes
The browser is a toolbox
Beyond the DOM and fetch, browsers ship with dozens of built-in capabilities, collectively called Web APIs. They let your page do things that once needed apps: copy to the clipboard, share a link, notice when an element scrolls into view, draw graphics, read a file, and more. You use them just like fetch: they are already there. This lesson tours the most useful ones, with patterns you can drop into real projects.
Some APIs need a secure page (HTTPS), a user action such as a click, or the visitor’s permission. The live editors on this page run in a sandbox that blocks some of them, so a few examples below are shown as code to copy into your own pages.
1. IntersectionObserver: know when something is visible
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
observer.unobserve(entry.target); // only once
}
});
}, { threshold: 0.2 }); // 20% visible
document.querySelectorAll(".reveal").forEach(el => observer.observe(el));
This replaces old, slow scroll handlers. The browser tells you when an element enters the viewport. It is the modern way to fade in sections, load images only when needed, and trigger an infinite scroll.
Scroll the result: each box fades in when it enters view. Change the threshold to 0.8 to make the effect wait until more of the box is visible.
<style>
body{font-family:Arial;margin:0;padding:10px}
.spacer{height:140px;color:#9A95BC;text-align:center;padding-top:50px}
.reveal{opacity:0;transform:translateY(24px);transition:.6s;background:#EFEAFD;border-radius:12px;padding:30px;margin:10px 0;text-align:center;font-weight:700;color:#5A28C8}
.reveal.visible{opacity:1;transform:none}
</style>
<div class="spacer">Scroll down</div>
<div class="reveal">Box one</div>
<div class="spacer"></div>
<div class="reveal">Box two</div>
<div class="spacer"></div>
<div class="reveal">Box three</div>
<div class="spacer"></div>
<script>
const observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
observer.unobserve(entry.target);
}
});
}, { threshold: 0.2 });
document.querySelectorAll('.reveal').forEach(function (el) { observer.observe(el); });
</script>
Change { threshold: 0.2 } to { threshold: 0.8 }.
<style>
body{font-family:Arial;margin:0;padding:10px}
.spacer{height:140px;color:#9A95BC;text-align:center;padding-top:50px}
.reveal{opacity:0;transform:translateY(24px);transition:.6s;background:#EFEAFD;border-radius:12px;padding:30px;margin:10px 0;text-align:center;font-weight:700;color:#5A28C8}
.reveal.visible{opacity:1;transform:none}
</style>
<div class="spacer">Scroll down</div>
<div class="reveal">Box one</div>
<div class="spacer"></div>
<div class="reveal">Box two</div>
<div class="spacer"></div>
<div class="reveal">Box three</div>
<div class="spacer"></div>
<script>
const observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
observer.unobserve(entry.target);
}
});
}, { threshold: 0.8 });
document.querySelectorAll('.reveal').forEach(function (el) { observer.observe(el); });
</script>
2. Clipboard and Share
copyButton.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText("https://skillsinminutes.com");
copyButton.textContent = "Copied!";
} catch {
copyButton.textContent = "Press Ctrl+C";
}
});
shareButton.addEventListener("click", async () => {
if (navigator.share) {
await navigator.share({ title: "Skills in Minutes", url: location.href });
}
});
3. URL and URLSearchParams
const url = new URL("https://site.com/search?q=css&page=2#results");
console.log(url.hostname, url.pathname); // site.com /search
console.log(url.searchParams.get("q")); // css
url.searchParams.set("page", 3);
url.searchParams.append("sort", "new");
console.log(url.toString());
const params = new URLSearchParams({ q: "learn js", level: "beginner" });
console.log(params.toString()); // q=learn+js&level=beginner
Build a search address from a base URL and an object of options using URLSearchParams, then read one value back.
const base = 'https://api.example.com/lessons';
const options = { topic: 'css grid', level: 'advanced', page: 2 };
// build the full URL string and print it
const url = new URL(base); for (const [k, v] of Object.entries(options)) url.searchParams.set(k, v);
const base = 'https://api.example.com/lessons';
const options = { topic: 'css grid', level: 'advanced', page: 2 };
const url = new URL(base);
for (const [k, v] of Object.entries(options)) url.searchParams.set(k, v);
console.log(url.toString());
console.log(url.searchParams.get('topic'));
4. Canvas: drawing with code
Draw a rectangle and a circle on the canvas, then add a line of text. Try changing the colours and positions.
<canvas id="c" width="300" height="160" style="border:1px solid #E6E1F5;border-radius:12px"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.fillStyle = '#5A28C8';
ctx.fillRect(20, 20, 100, 60);
ctx.beginPath();
ctx.arc(200, 60, 36, 0, Math.PI * 2);
ctx.fillStyle = '#F06CC2';
ctx.fill();
// add text with ctx.font and ctx.fillText
</script>
ctx.font = ’20px Arial’; ctx.fillStyle = ‘#14112E’; ctx.fillText(‘Hello canvas’, 20, 130);
<canvas id="c" width="300" height="160" style="border:1px solid #E6E1F5;border-radius:12px"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.fillStyle = '#5A28C8';
ctx.fillRect(20, 20, 100, 60);
ctx.beginPath();
ctx.arc(200, 60, 36, 0, Math.PI * 2);
ctx.fillStyle = '#F06CC2';
ctx.fill();
ctx.font = '20px Arial';
ctx.fillStyle = '#14112E';
ctx.fillText('Hello canvas', 20, 130);
</script>
The <canvas> element is a blank bitmap that you paint on with JavaScript. It powers games, charts, image editors and visual effects. Shapes, paths, text, images and pixel manipulation are all available through the 2D context.
5. Reading files the user chooses
fileInput.addEventListener("change", () => {
const file = fileInput.files[0];
if (!file) return;
console.log(file.name, file.size, file.type);
const reader = new FileReader();
reader.onload = () => { preview.src = reader.result; }; // data URL for images
reader.readAsDataURL(file);
// or simply, for a preview:
// preview.src = URL.createObjectURL(file);
});
6. Other useful APIs at a glance
| API | What it does |
|---|---|
ResizeObserver |
Tells you when an element changes size |
MutationObserver |
Tells you when the DOM changes |
matchMedia |
Runs media queries from JavaScript: matchMedia("(prefers-color-scheme: dark)").matches |
navigator.geolocation |
Gets the visitor’s location, with permission |
Notification |
Shows system notifications, with permission |
History API |
Changes the address without reloading, used by single-page apps |
BroadcastChannel |
Talks between tabs |
Web Workers |
Runs heavy work on another thread so the page stays smooth |
IndexedDB |
A large in-browser database |
requestIdleCallback |
Runs low-priority work when the browser is free |
AbortController |
Cancels fetch requests |
// cancel a slow request
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
try {
const res = await fetch("/slow", { signal: controller.signal });
} catch (e) {
if (e.name === "AbortError") console.log("Request cancelled");
}
// react to the visitor's colour scheme
const dark = matchMedia("(prefers-color-scheme: dark)");
console.log(dark.matches);
dark.addEventListener("change", e => console.log("Dark now?", e.matches));
How to use a new API safely
- Check support:
if ("IntersectionObserver" in window)or look it up on MDN’s compatibility table. - Provide a fallback: your page should still work without it (progressive enhancement).
- Respect permissions: ask only when the visitor does something that needs it, and explain why.
- Handle denial: wrap in try/catch and carry on when the visitor says no.
- Mind privacy: location, camera and notifications are personal. Request the minimum.
Asking for permission as soon as the page loads, such as location or notifications. Visitors reflexively click “Block”, and the browser then remembers the refusal. Ask only after a clear action, like pressing a “Use my location” button.
Search the API name plus “MDN”. Every page has a short description, a code example and a browser compatibility table. Reading these pages is a core professional skill.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is IntersectionObserver best for?
- Sorting arrays
- Parsing JSON
- Changing fonts
- Knowing when an element becomes visible
It reports visibility without scroll listeners.
Which API copies text to the clipboard?
document.copynavigator.clipboardwindow.pasteclipboard.save
The Clipboard API writes text.
What does new URL(...).searchParams.get("q") do?
- Deletes q
- Opens a page
- Reads the q query parameter
- Builds a table
searchParams reads query values.
Why ask for permissions only after a user action?
- Visitors are more likely to accept, and it respects privacy
- It is faster
- The API requires JavaScript
- To avoid CSS
Early prompts get blocked.
What is AbortController used for?
- Aborting the browser
- Stopping CSS
- Cancelling a fetch request
- Deleting arrays
Pass its signal to fetch and call abort().
Summary
- Web APIs are built-in browser capabilities.
- IntersectionObserver replaces scroll listeners.
- URL and URLSearchParams build addresses safely.
- Check support, add fallbacks and ask permission politely.
Questions
Do Web APIs work in every browser?
Most popular ones do in current browsers. Check MDN's compatibility table and add fallbacks for the rest.
Why does the clipboard fail on my page?
It needs HTTPS and usually a user click. It also fails in sandboxed frames.
Is canvas the same as SVG?
No. Canvas paints pixels with code and suits games and effects. SVG describes shapes as elements and scales cleanly.
