Chapter 6. Observing DOM Elements
Introduction
This chapter looks at three types of observers that the browser gives you for watching DOM elements: MutationObserver
, IntersectionObserver
, and ResizeObserver
. These observer objects can watch DOM elements and notify you of certain changes or events.
Observers are created with a callback function. This function is called whenever relevant events occur in the page. It’s called with one or more entries that contain information about what occurred. This just creates the observer. To actually start watching an element, you need to call observe
on the observer, passing the element you want to observe and an optional set of options.
MutationObserver
MutationObserver
watches for changes in the DOM for an element. You can watch for changes to:
-
Child elements
-
Attributes
-
Text content
What the browser observes is defined in an options object passed to the observe
function. You can also give an optional subtree
option when observing an element. This extends the monitoring of child elements, attributes, and/or text content to all descendant nodes (instead of just the element and its direct children).
When a mutation occurs that you are interested in, your callback gets executed with an array of MutationEntry
objects that describe the mutation that just occurred.
ResizeObserver
As its name suggests, ResizeObserver
notifies you when an element’s size changes. When the size changes, your callback is called with information about what ...
Get Web API Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.