Advanced Web APIs — JavaScript

Web APIs are the browser's built-in tools, which JavaScript can call directly. new IntersectionObserver(callback) makes an observer, and observer.observe(el)…

A "Copy link" button puts the link on your clipboard (the place where copied text is kept for a while). A ride-hailing map knows where you are. Images load only when you scroll down to them. Nobody writes these from zero: the browser already provides the tools.

Besides the DOM, the browser gives JavaScript many ready-made tools: watching elements come onto the screen, copying text to the clipboard, reading the user's location, and many more. These built-in browser tools are called Web APIs. You don't need to install anything. You only call them.

IntersectionObserver: knowing when an element is visible

Images that load only as you scroll, or cards that appear slowly, need to know when an element enters the screen. An IntersectionObserver is a watcher (an observer) that tells you as soon as that element enters the screen. This example marks every photo that is visible:

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add('shown')
    }
  })
})

document.querySelectorAll('.photo').forEach((photo) => {
  observer.observe(photo)
})

The result: photos already on the screen get the class shown right away. Photos far down the page only get that class when you scroll to them. You don't need a setInterval that checks the scroll position every few milliseconds, because the browser tells you. When you no longer need the observer, observer.disconnect() stops all of its watching.

Other options for images. If you only want to delay loading an image until it is almost visible, you need no JavaScript: <img src="photo.jpg" alt="Class photo" loading="lazy">. With loading="lazy", the browser itself delays that image. Use IntersectionObserver when you need more, such as adding a class when an element appears, as in the example above.

Other observers: size and DOM content

Two other observers follow the same pattern: make an observer with a callback, then call observe for the element.

const ro = new ResizeObserver((entries) => {
  console.log('Width:', entries[0].contentRect.width)
})
ro.observe(document.querySelector('#box'))

const mo = new MutationObserver((records) => {
  console.log('List changed:', records.length, 'change(s)')
})
mo.observe(document.querySelector('#list'), { childList: true })

Clipboard: copying text

This code copies a text to the clipboard when the Copy button is clicked, then prints whether it worked or failed:

button.addEventListener('click', () => {
  navigator.clipboard.writeText('Hello!')
    .then(() => console.log('Copied'))
    .catch((err) => console.log('Failed:', err.message))
})

On phones there is also navigator.share({ title: 'JS Class', url: location.href }), which opens the phone's own share menu (location.href is the address of the current page). The rules: HTTPS only, only inside a click listener, and check first with if (navigator.share), because not every browser has it yet.

Geolocation: the user's location

This code asks for the user's location, with two callbacks:

navigator.geolocation.getCurrentPosition(
  (pos) => console.log(pos.coords.latitude, pos.coords.longitude),
  (err) => console.log('Failed:', err.message)
)

The browser asks the user for permission first. The first callback runs if the user allows it, and receives the coordinates (latitude and longitude). The second callback runs if the user refuses or reading the location fails.

⚠️ Observers set up wrong, and permission that gets refused

TL;DR: Web APIs are the browser's built-in tools, which JavaScript can call directly. new IntersectionObserver(callback) makes an observer, and observer.observe(el) registers an element to watch. The browser then calls the callback every time that element enters or leaves the screen. Each element gets one report (entry): check entry.isIntersecting (true when it is visible), then use entry.target (the element). ResizeObserver watches an element's size, MutationObserver watches DOM content, and disconnect() stops an observer. navigator.clipboard.writeText(text) copies text to the clipboard. navigator.geolocation.getCurrentPosition(...) reads the location once the user allows it.

⚡ Know when an element is visible

Write:

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add('shown')
    }
  })
})

document.querySelectorAll('.photo').forEach((photo) => {
  observer.observe(photo)
})
Guess first: isIntersecting is true when a photo is visible. What happens if that check is removed?

Every photo gets the class shown right away, including the ones far below. The browser calls the callback once at the start for every watched element, including those that are not visible yet.

Meaning: An IntersectionObserver is a watcher built into the browser. observer.observe(photo) registers each photo to be watched. The browser then calls the callback every time a photo enters or leaves the screen. entries is the list of reports, entry.isIntersecting is true when the element is visible, and entry.target is the element being reported. observer.disconnect() stops the watching.

⚡ Copy text to the clipboard

Write:

button.addEventListener('click', () => {
  navigator.clipboard.writeText('Hello!')
    .then(() => console.log('Copied'))
    .catch((err) => console.log('Failed:', err.message))
})

Meaning: The clipboard is the place where copied text is kept for a while. In JavaScript it is at navigator.clipboard (navigator is an object that holds tools from the browser), not on document or window. writeText returns a Promise, because the browser may refuse. button is the Copy button on the page. Firefox and Safari allow writeText only inside a click listener. The clipboard only works on HTTPS pages or on localhost (your own computer).

⚡ Location needs permission

Write:

navigator.geolocation.getCurrentPosition(
  (pos) => console.log(pos.coords.latitude, pos.coords.longitude),
  (err) => console.log('Failed:', err.message)
)

Meaning: The browser asks the user for permission first. The first callback runs if the user allows it, and receives the coordinates. The second callback runs if the user refuses or reading the location fails.

What you will learn