IntersectionObserver: observe() method - Web APIs

IntersectionObserver: observe() method
======================================

 The `IntersectionObserver` method
 **`observe()`** adds an element to the set of target elements
 being watched by the `IntersectionObserver`. One observer has one set of
 thresholds and one root, but can watch multiple target elements for visibility changes
 in keeping with those.

 To stop observing the element, call
 `IntersectionObserver.unobserve()`.

 When the visibility of the specified element crosses over one of the observer's
 visibility thresholds (as listed in `IntersectionObserver.thresholds`), the
 observer's callback is executed with an array of
 `IntersectionObserverEntry` objects representing the intersection changes
 which occurred. Note that this design allows multiple elements' intersection changes to
 be processed by a single call to the callback.

**Note:** the observer callback will always fire the first render cycle after `observe()` is called, even if the observed element has not yet moved with respect to the viewport.
 This means that, for example, an element that is outside the viewport when `observe()` is called on it will result in the callback being immediately called with at least one entry with `intersecting` set to `false`.
 An element inside the viewport will result in the callback being immediately called with at least one entry with `intersecting` set to `true`.

Syntax
------

```js
observe(targetElement)
```

### Parameters

`targetElement`

 An `element` whose visibility within the root is to be monitored. This
 element must be a descendant of the root element (or contained within the current
 document, if the root is the document's viewport).

### Return value

None (`undefined`).

Examples
--------

```js
// Register IntersectionObserver
const io = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.intersectionRatio > 0) {
      // Add 'active' class if observation target is inside viewport
      entry.target.classList.add("active");
    } else {
      // Remove 'active' class otherwise
      entry.target.classList.remove("active");
    }
  });
});

// Declares what to observe, and observes its properties.
const boxElList = document.querySelectorAll(".box");
boxElList.forEach((el) => {
  io.observe(el);
});
```

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserver-observe |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `IntersectionObserver.unobserve()`


IntersectionObserver: IntersectionObserver() constructor - Web APIs

IntersectionObserver: IntersectionObserver() constructor
========================================================

The **`IntersectionObserver()`** constructor creates and returns a new `IntersectionObserver` object.

 The `rootMargin`, if specified, is checked to ensure it's syntactically correct.
 If not specified, or an empty string, the default is `0px 0px 0px 0px`.

 The `threshold`s, if specified, are checked to ensure that they're all in the range 0.0 and 1.0 inclusive, and the threshold list is sorted in ascending numeric order.
 If the threshold list is empty, it's set to the array `[0.0]`.

Syntax
------

```js
new IntersectionObserver(callback)
new IntersectionObserver(callback, options)
```

### Parameters

`callback`

 A function which is called when the percentage of the target element is visible crosses a threshold.
 The callback receives as input two parameters:

`entries`

An array of `IntersectionObserverEntry` objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.

`observer`

The `IntersectionObserver` for which the callback is being invoked.

`options` Optional

 An optional object which customizes the observer. All properties are optional.
 You can provide any combination of the following options:

`root`

 An `Element` or `Document` object which is an ancestor of the intended target, whose bounding rectangle will be considered the viewport.
 Any part of the target not visible in the visible area of the `root` is not considered visible. If not specified, the observer uses the document's
 viewport as the root, with no margin, and a 0% threshold (meaning that even a one-pixel change is enough to trigger a callback).

`rootMargin`

 A string which specifies a set of offsets to add to the root's bounding\_box when calculating intersections, effectively shrinking
 or growing the root for calculation purposes.
 The syntax is approximately the same as that for the CSS `margin` property;
 see The intersection root and root margin for more information on how the margin works and the syntax.
 The default is "0px 0px 0px 0px".

`threshold`

 Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target.
 A value of 0.0 means that even a single visible pixel counts as the target being visible.
 1.0 means that the entire target element is visible.
 See Thresholds for a more in-depth description of how thresholds are used.
 The default is a threshold of 0.0.

### Return value

 A new `IntersectionObserver` which can be used to watch for the visibility of a target element within the specified `root` crossing through any of the
 specified visibility `threshold`s.
 Call its `observe()` method to begin watching for the visibility changes on a given target.

### Exceptions

`SyntaxError` `DOMException`

The specified `rootMargin` is invalid.

`RangeError`

One or more of the values in `threshold` is outside the range 0.0 to 1.0.

Examples
--------

This example creates a new intersection observer which calls the function `myObserverCallback` every time the visible area of the element being observed changes by at least 10%.

```js
let observer = new IntersectionObserver(myObserverCallback, { threshold: 0.1 });
```

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserver-intersectionobserver |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


IntersectionObserver: unobserve() method - Web APIs

IntersectionObserver: unobserve() method
========================================

 The `IntersectionObserver` method
 **`unobserve()`** instructs the
 `IntersectionObserver` to stop observing the specified target
 element.

Syntax
------

```js
unobserve(target)
```

### Parameters

`target`

 The `Element` to cease observing. If the specified element isn't being
 observed, this method does nothing and no exception is thrown.

### Return value

None (`undefined`).

Examples
--------

 This snippet shows an observer being created, an element being observed, and then being
 unobserved.

```js
const observer = new IntersectionObserver(callback);
observer.observe(document.getElementById("elementToObserve"));

// …

observer.unobserve(document.getElementById("elementToObserve"));
```

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserver-unobserve |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Intersection Observer API
* `IntersectionObserver.observe()`


EventTarget: addEventListener() method - Web APIs

EventTarget: addEventListener() method
======================================

 The **`addEventListener()`** method of the `EventTarget` interface
 sets up a function that will be called whenever the specified event is delivered to the target.

 Common targets are `Element`, or its children, `Document`, and `Window`,
 but the target may be any object that supports events (such as `IDBRequest`).

**Note:** The `addEventListener()` method is the *recommended* way to register an event listener. The benefits are as follows:

* It allows adding more than one handler for an event. This is particularly
 useful for libraries, JavaScript modules, or any other kind of
 code that needs to work well with other libraries or extensions.
* In contrast to using an `onXYZ` property, it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
* It works on any event target, not just HTML or SVG elements.

 The method `addEventListener()` works by adding a function, or an object that implements a `handleEvent()` function, to the list of event listeners for the specified event type
 on the `EventTarget` on which it's called. If the function or object is already in the list of event listeners for this target, the function or object is not added a second time.

**Note:** If a particular anonymous function is in the list of event listeners registered for a certain target, and then later in the code, an identical anonymous function is given in an `addEventListener` call, the second function will *also* be added to the list of event listeners for that target.

 Indeed, anonymous functions are not identical even if defined using
 the *same* unchanging source-code called repeatedly, **even if in a loop**.

 Repeatedly defining the same unnamed function in such cases can be
 problematic. (See Memory issues, below.)

 If an event listener is added to an `EventTarget` from inside another listener —
 that is, during the processing of the event —
 that event will not trigger the new listener.
 However, the new listener may be triggered during a later stage of event flow,
 such as during the bubbling phase.

Syntax
------

```js
addEventListener(type, listener)
addEventListener(type, listener, options)
addEventListener(type, listener, useCapture)
```

### Parameters

`type`

A case-sensitive string representing the event type to listen for.

`listener`

 The object that receives a notification (an object that implements the
 `Event` interface) when an event of the specified type occurs. This must
 be `null`, an object with a `handleEvent()` method, or a JavaScript
 function. See
 The event listener callback for details on the callback itself.

`options` Optional

 An object that specifies characteristics about the event listener. The available
 options are:

`capture` Optional

 A boolean value indicating that events of this type will be dispatched
 to the registered `listener` before being dispatched to any
 `EventTarget` beneath it in the DOM tree. If not specified, defaults to `false`.

`once` Optional

 A boolean value indicating that the `listener`
 should be invoked at most once after being added. If `true`, the
 `listener` would be automatically removed when invoked. If not specified, defaults to `false`.

`passive` Optional

A boolean value that, if `true`, indicates that the function specified by `listener` will never call `preventDefault()`. If a passive listener does call `preventDefault()`, the user agent will do nothing other than generate a console warning.

If this option is not specified it defaults to `false` – except that in browsers other than Safari, it defaults to `true` for `wheel`, `mousewheel`, `touchstart` and `touchmove` events. See Using passive listeners to learn more.

`signal` Optional

An `AbortSignal`. The listener will be removed when the given `AbortSignal` object's `abort()` method is called. If not specified, no `AbortSignal` is associated with the listener.

`useCapture` Optional

 A boolean value indicating whether events of this type will be dispatched to
 the registered `listener` *before* being dispatched to
 any `EventTarget` beneath it in the DOM tree. Events that are bubbling
 upward through the tree will not trigger a listener designated to use capture. Event
 bubbling and capturing are two ways of propagating events that occur in an element
 that is nested within another element, when both elements have registered a handle for
 that event. The event propagation mode determines the order in which elements receive
 the event. See DOM Level 3 Events and JavaScript Event order for a detailed explanation.
 If not specified, `useCapture` defaults to `false`.

**Note:** For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases.
 Event listeners in the *capturing* phase are called before event listeners in any non-capturing phases.

`wantsUntrusted` Optional
Non-standard

 A Firefox (Gecko)-specific parameter. If `true`, the listener receives
 synthetic events dispatched by web content (the default is `false` for
 browser chrome and `true` for regular web pages). This
 parameter is useful for code found in add-ons, as well as the browser itself.

### Return value

None (`undefined`).

Usage notes
-----------

### The event listener callback

 The event listener can be specified as either a callback function or
 an object whose `handleEvent()` method serves as the callback function.

 The callback function itself has the same parameters and return value as the
 `handleEvent()` method; that is, the callback accepts a single parameter: an
 object based on `Event` describing the event that has occurred, and it
 returns nothing.

 For example, an event handler callback that can be used to handle both
 `fullscreenchange` and
 `fullscreenerror` might look like this:

```js
function handleEvent(event) {
  if (event.type === "fullscreenchange") {
    /\* handle a full screen toggle \*/
  } else {
    /\* handle a full screen toggle error \*/
  }
}
```

### Safely detecting option support

 In older versions of the DOM specification, the third parameter of
 `addEventListener()` was a Boolean value indicating whether or not to use
 capture. Over time, it became clear that more options were needed. Rather than adding
 more parameters to the function (complicating things enormously when dealing with
 optional values), the third parameter was changed to an object that can contain various
 properties defining the values of options to configure the process of removing the event
 listener.

 Because older browsers (as well as some not-too-old browsers) still assume the third
 parameter is a Boolean, you need to build your code to handle this scenario
 intelligently. You can do this by using feature detection for each of the options you're
 interested in.

For example, if you want to check for the `passive` option:

```js
let passiveSupported = false;

try {
  const options = {
    get passive() {
      // This function will be called when the browser
      // attempts to access the passive property.
      passiveSupported = true;
      return false;
    },
  };

  window.addEventListener("test", null, options);
  window.removeEventListener("test", null, options);
} catch (err) {
  passiveSupported = false;
}
```

 This creates an `options` object with a getter function for the
 `passive` property; the getter sets a flag,
 `passiveSupported`, to `true` if it gets called. That
 means that if the browser checks the value of the `passive` property on the
 `options` object, `passiveSupported` will be
 set to `true`; otherwise, it will remain `false`. We then call
 `addEventListener()` to set up a fake event handler, specifying those
 options, so that the options will be checked if the browser recognizes an object as the
 third parameter. Then, we call `removeEventListener()` to clean up after
 ourselves. (Note that `handleEvent()` is ignored on event listeners that
 aren't called.)

 You can check whether any option is supported this way. Just add a getter for that
 option using code similar to what is shown above.

 Then, when you want to create an actual event listener that uses the options in
 question, you can do something like this:

```js
someElement.addEventListener(
  "mouseup",
  handleMouseUp,
  passiveSupported ? { passive: true } : false,
);
```

 Here we're adding a listener for the `mouseup`
 event on the element `someElement`. For the third parameter, if
 `passiveSupported` is `true`, we're specifying an
 `options` object with `passive` set to
 `true`; otherwise, we know that we need to pass a Boolean, and we pass
 `false` as the value of the `useCapture` parameter.

 You can learn more in the Implementing feature detection documentation and the explainer about
 `EventListenerOptions`
 from the Web Incubator Community Group.

### The value of "this" within the handler

 It is often desirable to reference the element on which the event handler was fired,
 such as when using a generic handler for a set of similar elements.

 When attaching a handler function to an element using `addEventListener()`,
 the value of `this` inside the handler will be a reference to
 the element. It will be the same as the value of the `currentTarget` property of
 the event argument that is passed to the handler.

```js
my_element.addEventListener("click", function (e) {
  console.log(this.className); // logs the className of my\_element
  console.log(e.currentTarget === this); // logs `true`
});
```

As a reminder, arrow functions do not have their own `this` context.

```js
my_element.addEventListener("click", (e) => {
  console.log(this.className); // WARNING: `this` is not `my\_element`
  console.log(e.currentTarget === this); // logs `false`
});
```

 If an event handler (for example, `onclick`) is specified on an element in the HTML source, the JavaScript code in the
 attribute value is effectively wrapped in a handler function that binds the value of
 `this` in a manner consistent with the `addEventListener()`; an
 occurrence of `this` within the code represents a reference to the element.

```html
<table id="my\_table" onclick="console.log(this.id);">
  <!-- `this` refers to the table; logs 'my\_table' -->
  …
</table>
```

 Note that the value of `this` inside a function, *called by* the code
 in the attribute value, behaves as per standard rules. This is
 shown in the following example:

```html
<script>
 function logID() {
 console.log(this.id);
 }
</script>
<table id="my\_table" onclick="logID();">
  <!-- when called, `this` will refer to the global object -->
  …
</table>
```

 The value of `this` within `logID()` is a reference to the global
 object `Window` (or `undefined` in the case of strict mode.

#### Specifying "this" using bind()

 The `Function.prototype.bind()` method lets you establish a fixed
 `this` context for all subsequent calls — bypassing problems where it's unclear what `this` will be, depending on
 the context from which your function was called. Note, however, that you'll need to keep
 a reference to the listener around so you can remove it later.

This is an example with and without `bind()`:

```js
class Something {
  name = "Something Good";
  constructor(element) {
    // bind causes a fixed `this` context to be assigned to `onclick2`
    this.onclick2 = this.onclick2.bind(this);
    element.addEventListener("click", this.onclick1, false);
    element.addEventListener("click", this.onclick2, false); // Trick
  }
  onclick1(event) {
    console.log(this.name); // undefined, as `this` is the element
  }
  onclick2(event) {
    console.log(this.name); // 'Something Good', as `this` is bound to the Something instance
  }
}

const s = new Something(document.body);
```

 Another solution is using a special function called `handleEvent()` to catch
 any events:

```js
class Something {
  name = "Something Good";
  constructor(element) {
    // Note that the listeners in this case are `this`, not this.handleEvent
    element.addEventListener("click", this, false);
    element.addEventListener("dblclick", this, false);
  }
  handleEvent(event) {
    console.log(this.name); // 'Something Good', as this is bound to newly created object
    switch (event.type) {
      case "click":
        // some code here…
        break;
      case "dblclick":
        // some code here…
        break;
    }
  }
}

const s = new Something(document.body);
```

Another way of handling the reference to `this` is to use an arrow function, which doesn't create a separate `this` context.

```js
class SomeClass {
  name = "Something Good";

  register() {
    window.addEventListener("keydown", (e) => {
      this.someMethod(e);
    });
  }

  someMethod(e) {
    console.log(this.name);
    switch (e.keyCode) {
      case 5:
        // some code here…
        break;
      case 6:
        // some code here…
        break;
    }
  }
}

const myObject = new SomeClass();
myObject.register();
```

### Getting data into and out of an event listener

 It may seem that event listeners are like islands, and that it is extremely difficult
 to pass them any data, much less to get any data back from them after they execute.
 Event listeners only take one argument,
 the Event Object,
 which is automatically passed to the listener, and the return value is ignored.
 So how can we get data in and back out of them? There are a number of
 good methods for doing this.

#### Getting data into an event listener using "this"

 As mentioned above, you can use
 `Function.prototype.bind()` to pass a value to an event listener via the
 `this` reference variable.

```js
const myButton = document.getElementById("my-button-id");
const someString = "Data";

myButton.addEventListener("click", passIntoEvtListener.bind(someString));

//function declaration for event listener
function passIntoEvtListener(e) {
  console.log("Expected Value:", this); // Expected Value: 'Data'
  console.log("current target:", e.currentTarget.id); // current target: my-button-id
}
```

 This method is suitable when you don't need to know which HTML element the event
 listener fired on programmatically from within the event listener. The primary benefit
 to doing this is that the event listener receives the data in much the same way that it
 would if you were to actually pass it through its argument list.

#### Getting data into an event listener using the outer scope property

 When an outer scope contains a variable declaration (with `const`,
 `let`), all the inner functions declared in that scope have access to that
 variable (look here for
 information on outer/inner functions, and here
 for information on variable scope). Therefore, one of the simplest ways to access data
 from outside of an event listener is to make it accessible to the scope in which the
 event listener is declared.

```js
const myButton = document.getElementById("my-button-id");
let someString = "Data";

myButton.addEventListener("click", () => {
  console.log(someString); // Expected Value: 'Data'

  someString = "Data Again";
});

console.log(someString); // Expected Value: 'Data' (will never output 'Data Again')
```

**Note:** Although inner scopes have access to `const`,
 `let` variables from outer scopes, you cannot expect any changes to these
 variables to be accessible after the event listener definition, within the same outer
 scope. Why? Because by the time the event listener would execute, the scope in which
 it was defined would have already finished executing.

#### Getting data into and out of an event listener using objects

 Unlike most functions in JavaScript, objects are retained in memory as long as a
 variable referencing them exists in memory. This, and the fact that objects can have
 properties, and that they can be passed around by reference, makes them likely
 candidates for sharing data among scopes. Let's explore this.

**Note:** Functions in JavaScript are actually objects. (Hence they too
 can have properties, and will be retained in memory even after they finish executing
 if assigned to a variable that persists in memory.)

 Because object properties can be used to store data in memory as long as a variable
 referencing the object exists in memory, you can actually use them to get data into an
 event listener, and any changes to the data back out after an event handler executes.
 Consider this example.

```js
const myButton = document.getElementById("my-button-id");
const someObject = { aProperty: "Data" };

myButton.addEventListener("click", () => {
  console.log(someObject.aProperty); // Expected Value: 'Data'

  someObject.aProperty = "Data Again"; // Change the value
});

setInterval(() => {
  if (someObject.aProperty === "Data Again") {
    console.log("Data Again: True");
    someObject.aProperty = "Data"; // Reset value to wait for next event execution
  }
}, 5000);
```

 In this example, even though the scope in which both the event listener and the
 interval function are defined would have finished executing before the original value of
 `someObject.aProperty` would have changed, because `someObject`
 persists in memory (by *reference*) in both the event listener and interval
 function, both have access to the same data (i.e. when one changes the data, the other
 can respond to the change).

**Note:** Objects are stored in variables by reference, meaning only the
 memory location of the actual data is stored in the variable. Among other things, this
 means variables that "store" objects can actually affect other variables that get
 assigned ("store") the same object reference. When two variables reference the same
 object (e.g., `let a = b = {aProperty: 'Yeah'};`), changing the data in
 either variable will affect the other.

**Note:** Because objects are stored in variables by reference, you can
 return an object from a function to keep it alive (preserve it in memory so you don't
 lose the data) after that function stops executing.

### Memory issues

```js
const elts = document.getElementsByTagName("\*");

// Case 1
for (const elt of elts) {
  elt.addEventListener(
    "click",
    (e) => {
      // Do something
    },
    false,
  );
}

// Case 2
function processEvent(e) {
  // Do something
}

for (const elt of elts) {
  elt.addEventListener("click", processEvent, false);
}
```

 In the first case above, a new (anonymous) handler function is created with each
 iteration of the loop. In the second case, the same previously declared function is used
 as an event handler, which results in smaller memory consumption because there is only
 one handler function created. Moreover, in the first case, it is not possible to call
 `removeEventListener()` because no
 reference to the anonymous function is kept (or here, not kept to any of the multiple
 anonymous functions the loop might create.) In the second case, it's possible to do
 `myElement.removeEventListener("click", processEvent, false)`
 because `processEvent` is the function reference.

 Actually, regarding memory consumption, the lack of keeping a function reference is not
 the real issue; rather it is the lack of keeping a *static* function reference.

### Using passive listeners

If an event has a default action — for example, a `wheel` event that scrolls the container by default — the browser is in general unable to start the default action until the event listener has finished, because it doesn't know in advance whether the event listener might cancel the default action by calling `Event.preventDefault()`. If the event listener takes too long to execute, this can cause a noticeable delay, also known as jank, before the default action can be executed.

By setting the `passive` option to `true`, an event listener declares that it will not cancel the default action, so the browser can start the default action immediately, without waiting for the listener to finish. If the listener does then call `Event.preventDefault()`, this will have no effect.

The specification for `addEventListener()` defines the default value for the `passive` option as always being `false`. However, to realize the scroll performance benefits of passive listeners in legacy code, browsers other than Safari have changed the default value of the `passive` option to `true` for the `wheel`, `mousewheel`, `touchstart` and `touchmove` events on the document-level nodes `Window`, `Document`, and `Document.body`. That prevents the event listener from canceling the event, so it can't block page rendering while the user is scrolling.

**Note:** See the compatibility table below if you need to know which
 browsers (and/or which versions of those browsers) implement this altered behavior.

Because of that, when you want to override that behavior and ensure the `passive` option is `false` in all browsers, you must explicitly set the option to `false` (rather than relying on the default).

 You don't need to worry about the value of `passive` for the basic `scroll` event.
 Since it can't be canceled, event listeners can't block page rendering anyway.

See Improving scroll performance using passive listeners for an example showing the effect of passive listeners.

### Older browsers

 In older browsers that don't support the `options` parameter to
 `addEventListener()`, attempting to use it prevents the use of the
 `useCapture` argument without proper use of feature detection.

Examples
--------

### Add a simple listener

 This example demonstrates how to use `addEventListener()` to watch for mouse
 clicks on an element.

#### HTML

```html
<table id="outside">
  <tr>
    <td id="t1">one</td>
  </tr>
  <tr>
    <td id="t2">two</td>
  </tr>
</table>
```

#### JavaScript

```js
// Function to change the content of t2
function modifyText() {
  const t2 = document.getElementById("t2");
  const isNodeThree = t2.firstChild.nodeValue === "three";
  t2.firstChild.nodeValue = isNodeThree ? "two" : "three";
}

// Add event listener to table
const el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);
```

 In this code, `modifyText()` is a listener for `click` events
 registered using `addEventListener()`. A click anywhere in the table bubbles
 up to the handler and runs `modifyText()`.

#### Result

### Add an abortable listener

This example demonstrates how to add an `addEventListener()` that can be aborted with an `AbortSignal`.

#### HTML

```html
<table id="outside">
  <tr>
    <td id="t1">one</td>
  </tr>
  <tr>
    <td id="t2">two</td>
  </tr>
</table>
```

#### JavaScript

```js
// Add an abortable event listener to table
const controller = new AbortController();
const el = document.getElementById("outside");
el.addEventListener("click", modifyText, { signal: controller.signal });

// Function to change the content of t2
function modifyText() {
  const t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue === "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
    controller.abort(); // remove listener after value reaches "three"
  }
}
```

In the example above, we modify the code in the previous example such that after the second row's content changes to "three", we call `abort()` from the `AbortController` we passed to the `addEventListener()` call. That results in the value remaining as "three" forever because we no longer have any code listening for a click event.

#### Result

### Event listener with anonymous function

 Here, we'll take a look at how to use an anonymous function to pass parameters into the
 event listener.

#### HTML

```html
<table id="outside">
  <tr>
    <td id="t1">one</td>
  </tr>
  <tr>
    <td id="t2">two</td>
  </tr>
</table>
```

#### JavaScript

```js
// Function to change the content of t2
function modifyText(new\_text) {
  const t2 = document.getElementById("t2");
  t2.firstChild.nodeValue = new_text;
}

// Function to add event listener to table
const el = document.getElementById("outside");
el.addEventListener(
  "click",
  function () {
    modifyText("four");
  },
  false,
);
```

 Notice that the listener is an anonymous function that encapsulates code that is then,
 in turn, able to send parameters to the `modifyText()` function, which is
 responsible for actually responding to the event.

#### Result

### Event listener with an arrow function

 This example demonstrates a simple event listener implemented using arrow function
 notation.

#### HTML

```html
<table id="outside">
  <tr>
    <td id="t1">one</td>
  </tr>
  <tr>
    <td id="t2">two</td>
  </tr>
</table>
```

#### JavaScript

```js
// Function to change the content of t2
function modifyText(new\_text) {
  const t2 = document.getElementById("t2");
  t2.firstChild.nodeValue = new_text;
}

// Add event listener to table with an arrow function
const el = document.getElementById("outside");
el.addEventListener(
  "click",
  () => {
    modifyText("four");
  },
  false,
);
```

#### Result

 Please note that while anonymous and arrow functions are similar, they have different
 `this` bindings. While anonymous (and all traditional JavaScript functions)
 create their own `this` bindings, arrow functions inherit the
 `this` binding of the containing function.

 That means that the variables and constants available to the containing function are
 also available to the event handler when using an arrow function.

### Example of options usage

#### HTML

```html
<div class="outer">
  outer, once & none-once
  <div class="middle" target="\_blank">
    middle, capture & none-capture
    <a class="inner1" href="https://www.mozilla.org" target="\_blank">
      inner1, passive & preventDefault(which is not allowed)
    </a>
    <a class="inner2" href="https://developer.mozilla.org/" target="\_blank">
      inner2, none-passive & preventDefault(not open new page)
    </a>
  </div>
</div>
```

#### CSS

```css
.outer,
.middle,
.inner1,
.inner2 {
  display: block;
  width: 520px;
  padding: 15px;
  margin: 15px;
  text-decoration: none;
}
.outer {
  border: 1px solid red;
  color: red;
}
.middle {
  border: 1px solid green;
  color: green;
  width: 460px;
}
.inner1,
.inner2 {
  border: 1px solid purple;
  color: purple;
  width: 400px;
}
```

#### JavaScript

```js
const outer = document.querySelector(".outer");
const middle = document.querySelector(".middle");
const inner1 = document.querySelector(".inner1");
const inner2 = document.querySelector(".inner2");

const capture = {
  capture: true,
};
const noneCapture = {
  capture: false,
};
const once = {
  once: true,
};
const noneOnce = {
  once: false,
};
const passive = {
  passive: true,
};
const nonePassive = {
  passive: false,
};

outer.addEventListener("click", onceHandler, once);
outer.addEventListener("click", noneOnceHandler, noneOnce);
middle.addEventListener("click", captureHandler, capture);
middle.addEventListener("click", noneCaptureHandler, noneCapture);
inner1.addEventListener("click", passiveHandler, passive);
inner2.addEventListener("click", nonePassiveHandler, nonePassive);

function onceHandler(event) {
  alert("outer, once");
}
function noneOnceHandler(event) {
  alert("outer, none-once, default");
}
function captureHandler(event) {
  //event.stopImmediatePropagation();
  alert("middle, capture");
}
function noneCaptureHandler(event) {
  alert("middle, none-capture, default");
}
function passiveHandler(event) {
  // Unable to preventDefault inside passive event listener invocation.
  event.preventDefault();
  alert("inner1, passive, open new page");
}
function nonePassiveHandler(event) {
  event.preventDefault();
  //event.stopPropagation();
  alert("inner2, none-passive, default, not open new page");
}
```

#### Result

Click the outer, middle, inner containers respectively to see how the options work.

 Before using a particular value in the `options` object, it's a
 good idea to ensure that the user's browser supports it, since these are an addition
 that not all browsers have supported historically. See Safely detecting option support for details.

### Event listener with multiple options

You can set more than one of the options in the `options` parameter. In the following example we are setting two options:

* `passive`, to assert that the handler will not call `preventDefault()`
* `once`, to ensure that the event handler will only be called once.

#### HTML

```html
<button id="example-button">You have not clicked this button.</button>
<button id="reset-button">Click this button to reset the first button.</button>
```

#### JavaScript

```js
const buttonToBeClicked = document.getElementById("example-button");

const resetButton = document.getElementById("reset-button");

// the text that the button is initialized with
const initialText = buttonToBeClicked.textContent;

// the text that the button contains after being clicked
const clickedText = "You have clicked this button.";

// we hoist the event listener callback function
// to prevent having duplicate listeners attached
function eventListener() {
  buttonToBeClicked.textContent = clickedText;
}

function addListener() {
  buttonToBeClicked.addEventListener("click", eventListener, {
    passive: true,
    once: true,
  });
}

// when the reset button is clicked, the example button is reset,
// and allowed to have its state updated again
resetButton.addEventListener("click", () => {
  buttonToBeClicked.textContent = initialText;
  addListener();
});

addListener();
```

#### Result

### Improving scroll performance using passive listeners

The following example shows the effect of setting `passive`. It includes a `<div>` that contains some text, and a check box.

#### HTML

```html
<div id="container">
  <p>
    But down there it would be dark now, and not the lovely lighted aquarium she
    imagined it to be during the daylight hours, eddying with schools of tiny,
    delicate animals floating and dancing slowly to their own serene currents
    and creating the look of a living painting. That was wrong, in any case. The
    ocean was different from an aquarium, which was an artificial environment.
    The ocean was a world. And a world is not art. Dorothy thought about the
    living things that moved in that world: large, ruthless and hungry. Like us
    up here.
  </p>
</div>

<div>
  <input type="checkbox" id="passive" name="passive" checked />
  <label for="passive">passive</label>
</div>
```

```
#container {
  width: 150px;
  height: 200px;
  overflow: scroll;
  margin: 2rem 0;
  padding: 0.4rem;
  border: 1px solid black;
}
```

#### JavaScript

The code adds a listener to the container's `wheel` event, which by default scrolls the container. The listener runs a long-running operation. Initially the listener is added with the `passive` option, and whenever the checkbox is toggled, the code toggles the `passive` option.

```js
const passive = document.querySelector("#passive");
passive.addEventListener("change", (event) => {
  container.removeEventListener("wheel", wheelHandler);
  container.addEventListener("wheel", wheelHandler, {
    passive: passive.checked,
    once: true,
  });
});

const container = document.querySelector("#container");
container.addEventListener("wheel", wheelHandler, {
  passive: true,
  once: true,
});

function wheelHandler() {
  function isPrime(n) {
    for (let c = 2; c <= Math.sqrt(n); ++c) {
      if (n % c === 0) {
        return false;
      }
    }
    return true;
  }

  const quota = 1000000;
  const primes = [];
  const maximum = 1000000;

  while (primes.length < quota) {
    const candidate = Math.floor(Math.random() \* (maximum + 1));
    if (isPrime(candidate)) {
      primes.push(candidate);
    }
  }

  console.log(primes);
}
```

#### Result

The effect is that:

* Initially, the listener is passive, so trying to scroll the container with the wheel is immediate.
* If you uncheck "passive" and try to scroll the container using the wheel, then there is a noticeable delay before the container scrolls, because the browser has to wait for the long-running listener to finish.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-eventtarget-addeventlistener③ |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `EventTarget.removeEventListener()`
* Creating and triggering custom events
* More details on the use of `this` in event handlers


EventTarget: EventTarget() constructor - Web APIs

EventTarget: EventTarget() constructor
======================================

The **`EventTarget()`** constructor creates a new `EventTarget` object instance.

**Note:** It is fairly rare to explicitly call this constructor. Most of the time, this constructor is used inside the constructor of an object extending the `EventTarget` interface, using the `super` keyword.

Syntax
------

```js
new EventTarget()
```

### Parameters

None.

### Return value

A new instance of the `EventTarget` object.

Examples
--------

### Implementing a counter

This example implements a `Counter` class, with `increment()` and `decrement()` methods. It fires a custom `"valuechange"` event when either of these methods is called.

#### HTML

```html
<button id="dec" aria-label="Decrement">-</button>
<span id="currentValue">0</span>
<button id="inc" aria-label="Increment">+</button>
```

#### JavaScript

```js
class Counter extends EventTarget {
  constructor(initialValue = 0) {
    super();
    this.value = initialValue;
  }

  #emitChangeEvent() {
    this.dispatchEvent(new CustomEvent("valuechange", { detail: this.value }));
  }

  increment() {
    this.value++;
    this.#emitChangeEvent();
  }

  decrement() {
    this.value--;
    this.#emitChangeEvent();
  }
}

const initialValue = 0;
const counter = new Counter(initialValue);
document.querySelector("#currentValue").innerText = initialValue;

counter.addEventListener("valuechange", (event) => {
  document.querySelector("#currentValue").innerText = event.detail;
});

document.querySelector("#inc").addEventListener("click", () => {
  counter.increment();
});

document.querySelector("#dec").addEventListener("click", () => {
  counter.decrement();
});
```

#### Result

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-eventtarget-eventtarget① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `EventTarget`


EventTarget: dispatchEvent() method - Web APIs

EventTarget: dispatchEvent() method
===================================

 The **`dispatchEvent()`** method of the `EventTarget` sends an `Event` to the object, (synchronously) invoking the affected
 event listeners in the appropriate order. The normal event processing
 rules (including the capturing and optional bubbling phase) also apply to events
 dispatched manually with `dispatchEvent()`.

 Calling `dispatchEvent()` is the last step to *firing an event*. The event
 should have already been created and initialized using an `Event()` constructor.

**Note:** When calling this method, the `Event.target` property is initialized to the current `EventTarget`.

 Unlike "native" events, which are fired by the browser and invoke event handlers
 asynchronously via the event loop,
 `dispatchEvent()` invokes event handlers *synchronously*. All applicable event
 handlers are called and return before `dispatchEvent()` returns.

Syntax
------

```js
dispatchEvent(event)
```

### Parameter

`event`

The `Event` object to dispatch. Its `Event.target` property will be set to the current `EventTarget`.

### Return value

`false` if `event` is cancelable, and at least one of the event handlers which received `event` called `Event.preventDefault()`. Otherwise `true`.

### Exceptions

`InvalidStateError` `DomException`

Thrown if the event's type was not specified during event initialization.

**Warning:** Exceptions thrown by event handlers are reported as uncaught exceptions. The event
 handlers run on a nested callstack; they block the caller until they complete, but
 exceptions do not propagate to the caller.

Example
-------

See Creating and triggering events.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-eventtarget-dispatchevent③ |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The Event object reference


EventTarget: removeEventListener() method - Web APIs

EventTarget: removeEventListener() method
=========================================

 The **`removeEventListener()`** method of the `EventTarget` interface
 removes an event listener previously registered with `EventTarget.addEventListener()` from the target.
 The event listener to be removed is identified using a combination of the event type,
 the event listener function itself, and various optional options that may affect the matching process;
 see Matching event listeners for removal.

 Calling `removeEventListener()` with arguments that do not identify any
 currently registered event listener on the `EventTarget` has no
 effect.

If an event listener is removed from an `EventTarget` while another listener of the target is processing an event, it will not be triggered by the event. However, it can be reattached.

**Warning:** If a listener is registered twice, one with the *capture* flag set and one without, you must remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.

Event listeners can also be removed by passing an `AbortSignal` to an `addEventListener()` and then later calling `abort()` on the controller owning the signal.

Syntax
------

```js
removeEventListener(type, listener)
removeEventListener(type, listener, options)
removeEventListener(type, listener, useCapture)
```

### Parameters

`type`

A string which specifies the type of event for which to remove an event listener.

`listener`

 The event listener function of the event handler to remove from the
 event target.

`options` Optional

An options object that specifies characteristics about the event listener.

The available options are:

* `capture`: A boolean value that specifies whether the event listener to be removed is registered as a capturing listener or not. If this parameter is absent, the default value `false` is assumed.

`useCapture` Optional

 A boolean value that specifies whether the event listener to be removed is registered as a
 capturing listener or not. If this parameter is absent, the default value `false` is assumed.

### Return value

None.

### Matching event listeners for removal

 Given an event listener previously added by calling
 `addEventListener()`, you may eventually
 come to a point at which you need to remove it. Obviously, you need to specify the same
 `type` and `listener` parameters to
 `removeEventListener()`. But what about the `options`
 or `useCapture` parameters?

 While `addEventListener()` will let you add the same listener more than once
 for the same type if the options are different, the only option
 `removeEventListener()` checks is the
 `capture`/`useCapture` flag. Its value must
 match for `removeEventListener()` to match, but the other values don't.

For example, consider this call to `addEventListener()`:

```js
element.addEventListener("mousedown", handleMouseDown, true);
```

Now consider each of these two calls to `removeEventListener()`:

```js
element.removeEventListener("mousedown", handleMouseDown, false); // Fails
element.removeEventListener("mousedown", handleMouseDown, true); // Succeeds
```

 The first call fails because the value of `useCapture` doesn't match. The
 second succeeds, since `useCapture` matches up.

Now consider this:

```js
element.addEventListener("mousedown", handleMouseDown, { passive: true });
```

 Here, we specify an `options` object in which
 `passive` is set to `true`, while the other options are left to
 the default value of `false`.

 Now look at each of these calls to `removeEventListener()` in turn. Any of
 them in which `capture` or `useCapture` is
 `true` fail; all others succeed.

Only the `capture` setting matters to `removeEventListener()`.

```js
element.removeEventListener("mousedown", handleMouseDown, { passive: true }); // Succeeds
element.removeEventListener("mousedown", handleMouseDown, { capture: false }); // Succeeds
element.removeEventListener("mousedown", handleMouseDown, { capture: true }); // Fails
element.removeEventListener("mousedown", handleMouseDown, { passive: false }); // Succeeds
element.removeEventListener("mousedown", handleMouseDown, false); // Succeeds
element.removeEventListener("mousedown", handleMouseDown, true); // Fails
```

 It's worth noting that some browser releases have been inconsistent on this, and unless
 you have specific reasons otherwise, it's probably wise to use the same values used for
 the call to `addEventListener()` when calling
 `removeEventListener()`.

Example
-------

 This example shows how to add a `mouseover`-based event listener that
 removes a `click`-based event listener.

```js
const body = document.querySelector("body");
const clickTarget = document.getElementById("click-target");
const mouseOverTarget = document.getElementById("mouse-over-target");

let toggle = false;
function makeBackgroundYellow() {
  body.style.backgroundColor = toggle ? "white" : "yellow";

  toggle = !toggle;
}

clickTarget.addEventListener("click", makeBackgroundYellow, false);

mouseOverTarget.addEventListener("mouseover", () => {
  clickTarget.removeEventListener("click", makeBackgroundYellow, false);
});
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-eventtarget-removeeventlistener② |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `EventTarget.addEventListener()`


CSSMathInvert: CSSMathInvert() constructor - Web APIs

CSSMathInvert: CSSMathInvert() constructor
==========================================

 The **`CSSMathInvert()`** constructor creates a
 new `CSSMathInvert` object which represents a CSS
 `calc()` used as `calc(1 / value)`

Syntax
------

```js
new CSSMathInvert(arg)
```

### Parameters

`arg`

A `CSSNumericValue`.

### Exceptions

`RangeError`

Raised if the arg is 0 or -0.

Examples
--------

To do

Specifications
--------------

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssmathinvert-cssmathinvert |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


CSSMathInvert: value property - Web APIs

CSSMathInvert: value property
=============================

 The CSSMathInvert.value read-only property of the
 `CSSMathInvert` interface returns a `CSSNumericValue` object.

Value
-----

A `CSSNumericValue`.

Examples
--------

To do

Specifications
--------------

| Specification |
| --- |
| CSS Typed OM Level 1 # dom-cssmathinvert-value |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


NDEFReadingEvent: NDEFReadingEvent() constructor - Web APIs

NDEFReadingEvent: NDEFReadingEvent() constructor
================================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`NDEFReadingEvent()`** constructor creates a new `NDEFReadingEvent` object which represents events dispatched on new NFC readings obtained by `NDEFReader`.

Syntax
------

```js
new NDEFReadingEvent(type, options)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `reading`.

`options`

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`serialNumber` Optional

The serial number of the device a message was read from. It default to `""`, and can be set to `null`.

`message`

An object with the following members:

`data` Optional

Contains the data to be transmitted. It can be a string object or literal, an `ArrayBuffer`, a `TypedArray`, a `DataView`, or an array of nested records.

`encoding` Optional

A string specifying the record's encoding.

`id` Optional

A developer-defined identifier for the record.

`lang` Optional

A valid language tag according to RFC 5646: Tags for Identifying Languages (also known as BCP 47).

`mediaType` Optional

A valid MIME type.

`recordType`

A string indicating the type of data stored in `data`. It must be one of the following values:

`"absolute-url"`

An absolute URL to the data.

`"empty"`

An empty `NDEFRecord`.

`"mime"`

A valid MIME type.

`"smart-poster"`

A smart poster as defined by the NDEF-SMARTPOSTER specification.

`"text"`

Text as defined by the NDEF-TEXT specification.

`"unknown"`

The record type is not known.

`"URL"`

A URL as defined by the NDEF-URI specification.

### Return value

A new `NDEFReadingEvent` object.

Specifications
--------------

| Specification |
| --- |
| Web NFC API # dom-ndefreadingevent-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


NDEFReadingEvent: message property - Web APIs

NDEFReadingEvent: message property
==================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`message`** property of the `NDEFReadingEvent` interface returns an `NDEFMessage` object containing the received message.

Value
-----

An `NDEFMessage` object.

Examples
--------

This example shows how to create a convenience function that reads a single tag and then stops polling, saving battery life by cutting unneeded work. The example could easily be extended to time out after a given amount of milliseconds.

```js
const ndefReader = new NDEFReader();

function read() {
  return new Promise((resolve, reject) => {
    const ctlr = new AbortController();
    ctlr.signal.onabort = reject;
    ndefReader.addEventListener(
      "reading",
      (event) => {
        ctlr.abort();
        resolve(event);
      },
      { once: true },
    );
    ndefReader.scan({ signal: ctlr.signal }).catch((err) => reject(err));
  });
}

read().then(({ serialNumber }) => {
  console.log(serialNumber);
});
```

Specifications
--------------

| Specification |
| --- |
| Web NFC API # dom-ndefreadingevent-message |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


NDEFReadingEvent: serialNumber property - Web APIs

NDEFReadingEvent: serialNumber property
=======================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`serialNumber`** property of the `NDEFReadingEvent` interface returns the serial number of the device, which is used for anti-collision and identification, or an empty string if no serial number is available.

Value
-----

A string containing the device's serial number.

Examples
--------

This example shows how to create a convenience function that reads a single tag and then stops polling, saving battery life by cutting unneeded work. The example could easily be extended to time out after a given amount of milliseconds.

```js
const ndefReader = new NDEFReader();

function read() {
  return new Promise((resolve, reject) => {
    const ctlr = new AbortController();
    ctlr.signal.onabort = reject;
    ndefReader.addEventListener(
      "reading",
      (event) => {
        ctlr.abort();
        resolve(event);
      },
      { once: true },
    );
    ndefReader.scan({ signal: ctlr.signal }).catch((err) => reject(err));
  });
}

read().then(({ serialNumber }) => {
  console.log(serialNumber);
});
```

Specifications
--------------

| Specification |
| --- |
| Web NFC API # dom-ndefreadingevent-serialnumber |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PeriodicWave: PeriodicWave() constructor - Web APIs

PeriodicWave: PeriodicWave() constructor
========================================

 The **`PeriodicWave()`** constructor of the Web Audio API creates a new
 `PeriodicWave` object instance.

Syntax
------

```js
new PeriodicWave(context)
new PeriodicWave(context, options)
```

### Parameters

`context`

 A `BaseAudioContext` representing the audio context you want the node
 to be associated with.

`options` Optional

 A
 `PeriodicWaveOptions`
 dictionary object defining the properties you want the `PeriodicWave` to
 have (It also inherits the options defined in the PeriodicWaveConstraints
 dictionary.):

`real`

 A `Float32Array` containing the cosine terms
 that you want to use to form the wave (equivalent to the `real`
 parameter of `BaseAudioContext.createPeriodicWave`).

`imag`

 A `Float32Array` containing the sine terms that
 you want to use to form the wave (equivalent to the `imag` parameter of
 `BaseAudioContext.createPeriodicWave`).

`channelCount`

 Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. (See
 `AudioNode.channelCount` for more information.) Its usage and precise
 definition depend on the value of `channelCountMode`.

`channelCountMode`

 Represents an enumerated value describing the way channels must be matched between
 the node's inputs and outputs. (See `AudioNode.channelCountMode` for more
 information including default values.)

`channelInterpretation`

 Represents an enumerated value describing the meaning of the channels. This
 interpretation will define how audio up-mixing and down-mixing will happen.
 The possible values are `"speakers"` or `"discrete"`. (See
 `AudioNode.channelCountMode` for more information including default
 values.)

### Return value

A new `PeriodicWave` object instance.

Examples
--------

```js
const real = new Float32Array(2);
const imag = new Float32Array(2);
const ac = new AudioContext();

real[0] = 0;
imag[0] = 0;
real[1] = 1;
imag[1] = 0;

const wave = new PeriodicWave(ac, {
  real,
  imag,
  disableNormalization: false,
});
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-periodicwave-periodicwave |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


GPUValidationError: GPUValidationError() constructor - Web APIs

GPUValidationError: GPUValidationError() constructor
====================================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`GPUValidationError()`** constructor creates a new
 `GPUValidationError` object instance.

Syntax
------

```js
new GPUValidationError(message)
```

### Parameters

`message`

A string providing a human-readable message that explains why the error occurred.

Examples
--------

A developer would not manually use the constructor to create a `GPUValidationError` object. The user agent uses this constructor to create an appropriate object when a validation error is surfaced by `GPUDevice.popErrorScope` or the `uncapturederror` event.

See the main `GPUValidationError` page for a specific example involving a `GPUValidationError` object instance.

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpuvalidationerror-gpuvalidationerror |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API
* WebGPU Error Handling best practices


RTCAudioSourceStats: timestamp property - Web APIs

RTCAudioSourceStats: timestamp property
=======================================

The **`timestamp`** property of the `RTCAudioSourceStats` dictionary is a `DOMHighResTimeStamp` object specifying the time at which the data in the object was sampled.

The time is given in milliseconds elapsed since the first moment of January 1, 1970, UTC (also known as Unix time).

Value
-----

A `DOMHighResTimeStamp` value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC.

The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of fingerprinting protection in the form of reduced clock precision or accuracy.

Specifications
--------------

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-timestamp |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCAudioSourceStats: kind property - Web APIs

RTCAudioSourceStats: kind property
==================================

The `RTCAudioSourceStats` dictionary's **`kind`** property is a string value that is used to differentiate `audio` and `video` media sources.

Along with the `type`, this identifies the object as an `RTCAudioSourceStats` object when iterating the `RTCStatsReport` returned by `RTCRtpSender.getStats()` or `RTCPeerConnection.getStats()`.

Value
-----

A string with the value `audio`.

Specifications
--------------

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcmediasourcestats-kind |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCAudioSourceStats: totalSamplesDuration property - Web APIs

RTCAudioSourceStats: totalSamplesDuration property
==================================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The `RTCAudioSourceStats` dictionary's **`totalSamplesDuration`** property represents the combined duration of all samples produced by the media source over the lifetime of this stats object, in seconds.
 It does not include samples dropped before reaching this media source.

This can be used with `totalAudioEnergy` to compute an average audio level over different intervals.

**Note:** For audio duration of remotely sourced tracks, see `RTCInboundRtpStreamStats.totalSamplesDuration`.

Value
-----

A number indicating the total duration of all samples produced by this source over the lifetime this stats object, in seconds.

Specifications
--------------

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcaudiosourcestats-totalsamplesduration |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCAudioSourceStats: id property - Web APIs

RTCAudioSourceStats: id property
================================

The **`id`** property of the `RTCAudioSourceStats` dictionary is a string which uniquely identifies the object for which this object provides statistics.

Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an `RTCPeerConnection`, or an `RTCDataChannel`.

Value
-----

A string that uniquely identifies the object for which this `RTCAudioSourceStats` object provides statistics.

The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type.

Specifications
--------------

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-id |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCAudioSourceStats: totalAudioEnergy property - Web APIs

RTCAudioSourceStats: totalAudioEnergy property
==============================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The `RTCAudioSourceStats` dictionary's **`totalAudioEnergy`** property represents the total audio energy of the media source over the lifetime of this stats object.

The total energy across a particular duration can be determined by subtracting the value of this property returned by two different `getStats()` calls.

**Note:** For audio energy of remotely sourced tracks, see `RTCInboundRtpStreamStats.totalAudioEnergy`.

Value
-----

A number produced by summing the energy of every sample over the lifetime of this stats object.

 The energy of each sample is calculated by dividing the sample's value by the highest-intensity encodable value, squaring the result, and then multiplying by the duration of the sample in seconds.
 This is shown as an equation below:

duration

(

sample\_level
max\_level

)

2

Note that if multiple audio channels are used, the audio energy of a sample refers to the highest energy of any channel.

Specifications
--------------

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcaudiosourcestats-totalaudioenergy |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCAudioSourceStats: type property - Web APIs

RTCAudioSourceStats: type property
==================================

The `RTCAudioSourceStats` dictionary's property **`type`** is a string with value `media-source`.

 The type of `media-source` identifies the type of statistics as either `RTCAudioSourceStats` or `RTCVideoSourceStats` when iterating the `RTCStatsReport` returned by `RTCRtpSender.getStats()` or `RTCPeerConnection.getStats()`.
 The type of stats can further be differentiated using the `kind`, which will be `audio` for `RTCAudioSourceStats`.

Value
-----

A string with the value `media-source`.

Specifications
--------------

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcstats-type |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCAudioSourceStats: trackIdentifier property - Web APIs

RTCAudioSourceStats: trackIdentifier property
=============================================

The `RTCAudioSourceStats` dictionary's property **`trackIdentifier`** contains the `id` attribute of the associated `MediaStreamTrack`.

Value
-----

A string containing the value of the associated `MediaStreamTrack.id`.

Specifications
--------------

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcmediasourcestats-trackidentifier |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


RTCAudioSourceStats: audioLevel property - Web APIs

RTCAudioSourceStats: audioLevel property
========================================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The `RTCAudioSourceStats` dictionary's **`audioLevel`** property represents the audio level of the media source.

 The level is averaged over some small implementation-dependent interval.
 Users can alternatively calculate the average audio level over some arbitrary duration using the algorithm described in the `RTCAudioSourceStats` description.

**Note:** For audio levels of remotely sourced tracks, see `RTCInboundRtpStreamStats.audioLevel`.

Value
-----

A number between 0 and 1 (linear), where 1.0 represents 0 dBov (decibels relative to full scale (DBFS)), 0 represents silence, and 0.5 represents approximately 6 dB SPL change in the sound pressure level from 0 dBov.

Specifications
--------------

| Specification |
| --- |
| Identifiers for WebRTC's Statistics API # dom-rtcaudiosourcestats-audiolevel |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Selection: focusOffset property - Web APIs

Selection: focusOffset property
===============================

 The **`Selection.focusOffset`** read-only property returns the
 number of characters that the selection's focus is offset within the
 `Selection.focusNode`.

 This number is zero-based. If the selection ends with the first character in the
 `Selection.focusNode`, `0` is returned.

Value
-----

A number.

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-focusoffset |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: modify() method - Web APIs

Selection: modify() method
==========================

 The **`Selection.modify()`** method applies a change to the
 current selection or cursor position, using simple textual commands.

Syntax
------

```js
modify(alter, direction, granularity)
```

### Parameters

`alter`

 The type of change to apply. Specify `"move"` to move the current cursor
 position or `"extend"` to extend the current selection.

`direction`

 The direction in which to adjust the current selection. You can specify
 `"forward"` or `"backward"` to adjust in the appropriate
 direction based on the language at the selection point. If you want to adjust in a
 specific direction, you can specify `"left"` or `"right"`.

`granularity`

 The distance to adjust the current selection or cursor position. You can move by
 `"character"`, `"word"`, `"sentence"`,
 `"line"`, `"paragraph"`, `"lineboundary"`,
 `"sentenceboundary"`, `"paragraphboundary"`, or
 `"documentboundary"`.

**Note:** Firefox does **not** implement
 `"sentence"`, `"paragraph"`, `"sentenceboundary"`,
 `"paragraphboundary"`, or `"documentboundary"`. WebKit and Blink
 do.

**Note:** Starting in Firefox 5, the `"word"`
 granularity no longer includes the following space, regardless of the default platform
 behavior. This makes the behavior more consistent, as well as making it work the same
 way WebKit used to work, but unfortunately they have recently changed their behavior.

### Return value

None (`undefined`).

Examples
--------

 This example demonstrates the various `granularity` options for modifying a
 selection. Click somewhere inside the example (optionally selecting some text), and then
 click the button to expand the selection.

### HTML

```html
<p>
  Click somewhere in this example. Then click the button below to expand the
  selection. Watch what happens!
</p>
<p>
  Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore,
  cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod
  maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor
  repellendus.
</p>

<label for="granularity">Granularity:</label>
<select id="granularity">
  <option value="character">Character</option>
  <option value="word">Word</option>
  <option value="sentence">Sentence</option>
  <option value="line">Line</option>
  <option value="paragraph">Paragraph</option>
  <option value="lineboundary">Line Boundary</option>
  <option value="sentenceboundary">Sentence Boundary</option>
  <option value="paragraphboundary">Paragraph Boundary</option>
  <option value="documentboundary">Document Boundary</option>
</select>

<br /><br />

<button>Extend selection</button>
```

### JavaScript

```js
let select = document.querySelector("select");
let button = document.querySelector("button");

button.addEventListener("click", modify);

function modify() {
  let selection = window.getSelection();
  selection.modify("extend", "forward", select.value);
}
```

### Result

Specifications
--------------

*This method is not part of any specification.*

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: rangeCount property - Web APIs

Selection: rangeCount property
==============================

 The **`Selection.rangeCount`** read-only property returns the
 number of ranges in the selection.

 Before the user has clicked a freshly loaded page, the `rangeCount` is
 `0`. After the user clicks on the page, `rangeCount` is
 `1`, even if no selection is visible.

 A user can normally only select one range at a time, so the `rangeCount`
 will usually be `1`. Scripting can be used to make the selection contain more
 than one range.

 Gecko browsers allow multiple selections across table cells. Firefox allows to select
 multiple ranges in the document by using Ctrl+click (unless the click occurs within an
 element that has the `display: table-cell` CSS property assigned).

Value
-----

A number.

Examples
--------

 The following example will show the `rangeCount` every second. Select text
 in the browser to see it change.

### HTML

```html
<table>
  <tr>
    <td>a.1</td>
    <td>a.2</td>
  </tr>
  <tr>
    <td>b.1</td>
    <td>b.2</td>
  </tr>
  <tr>
    <td>c.1</td>
    <td>c.2</td>
  </tr>
</table>
```

### JavaScript

```js
setInterval(() => {
  console.log(window.getSelection().rangeCount);
}, 1000);
```

### Result

 Open your console to see how many ranges are in the selection. In Gecko browsers, you
 can select multiple ranges across table cells by holding down `Ctrl` (or `Cmd` on MacOS) while
 dragging with the mouse.

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-rangecount |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: type property - Web APIs

Selection: type property
========================

 The **`type`** read-only property of the
 `Selection` interface returns a string describing the
 type of the current selection.

Value
-----

 A string describing the type of the current selection. Possible
 values are:

`None`

No selection has currently been made.

`Caret`

 The selection is collapsed (i.e. the caret is placed on some
 text, but no range has been selected).

`Range`

A range has been selected.

Examples
--------

 In this example, the event handler will fire each time a new selection is made.
 `console.log(selection.type)` will return `Caret` or
 `Range` depending on whether the caret is placed at a single point in the
 text, or a range has been selected.

```js
let selection;

document.onselectionchange = () => {
  console.log("New selection made");
  selection = document.getSelection();
  console.log(selection.type);
};
```

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-type |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`


Selection: containsNode() method - Web APIs

Selection: containsNode() method
================================

 The **`Selection.containsNode()`** method indicates whether a
 specified node is part of the selection.

Syntax
------

```js
containsNode(node)
containsNode(node)
containsNode(node, partialContainment)
```

### Parameters

`node`

The node that is being looked for in the selection.

`partialContainment` Optional

 When `true`, `containsNode()` returns `true` when a
 part of the node is part of the selection. When `false`,
 `containsNode()` only returns `true` when the entire node is
 part of the selection. If not specified, the default value `false` is used.

### Return value

Returns `true` if the given node is part of the selection, and `false` otherwise.

Examples
--------

### Check for selection

This snippet checks whether anything inside the body element is selected.

```js
console.log(window.getSelection().containsNode(document.body, true));
```

### Find the hidden word

 In this example, a message appears when you select the secret word. It uses
 `addEventListener()` to check for
 `selectionchange` events.

#### HTML

```html
<p>Can you find the secret word?</p>
<p>
  Hmm, where <span id="secret" style="color:transparent">SECRET</span> could it
  be?
</p>
<p id="win" hidden>You found it!</p>
```

#### JavaScript

```js
const secret = document.getElementById("secret");
const win = document.getElementById("win");

// Listen for selection changes
document.addEventListener("selectionchange", () => {
  const selection = window.getSelection();
  const found = selection.containsNode(secret);

  win.toggleAttribute("hidden", !found);
});
```

#### Result

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-containsnode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: setPosition() method - Web APIs

Selection: setPosition() method
===============================

The **`Selection.setPosition()`** method collapses the current selection to a single point. The document is not modified. If the content is focused and editable, the caret will blink there.

**Note:** This method is an alias for the `Selection.collapse()` method.

Syntax
------

```js
setPosition(node)
setPosition(node, offset)
```

### Parameters

`node`

 The caret location will be within this node. This value can also be set to
 `null` — if `null` is specified, the method will behave like
 `Selection.removeAllRanges()`, i.e. all ranges will be removed from the
 selection.

`offset` Optional

 The offset in `node` to which the selection will be collapsed. If not
 specified, the default value `0` is used.

### Return value

None (`undefined`).

Examples
--------

```js
// Place the caret at the beginning of an HTML document's body.
const body = document.querySelector("body");
window.getSelection().setPosition(body, 0);
```

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-collapse |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection.collapse()`


Selection: toString() method - Web APIs

Selection: toString() method
============================

 The **`Selection.toString()`** method returns a string
 currently being represented by the selection object, i.e. the currently selected text.

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the selection.

Description
-----------

This method returns the currently selected text.

 In JavaScript, this method is called automatically when
 a function the selection object is passed to requires a string:

```js
alert(window.getSelection()); // What is called
alert(window.getSelection().toString()); // What is actually being effectively called.
```

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-stringifier |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: collapse() method - Web APIs

Selection: collapse() method
============================

The **`Selection.collapse()`** method collapses the current selection to a single point. The document is not modified. If the content is focused and editable, the caret will blink there.

**Note:** This method is an alias for the `Selection.setPosition()` method.

Syntax
------

```js
collapse(node)
collapse(node, offset)
```

### Parameters

`node`

 The caret location will be within this node. This value can also be set to
 `null` — if `null` is specified, the method will behave like
 `Selection.removeAllRanges()`, i.e. all ranges will be removed from the
 selection.

`offset` Optional

 The offset in `node` to which the selection will be collapsed. If not
 specified, the default value `0` is used.

### Return value

None (`undefined`).

Examples
--------

```js
// Place the caret at the beginning of an HTML document's body.
const body = document.querySelector("body");
window.getSelection().collapse(body, 0);
```

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-collapse |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection.setPosition()`


Selection: getRangeAt() method - Web APIs

Selection: getRangeAt() method
==============================

 The **`Selection.getRangeAt()`** method returns a range object
 representing one of the ranges currently selected.

Syntax
------

```js
getRangeAt(index)
```

### Parameters

`index`

 The zero-based index of the range to return. A negative number or a number greater
 than or equal to `Selection.rangeCount` will result in an error.

### Return value

The specified `Range` object.

Examples
--------

```js
let ranges = [];

sel = window.getSelection();

for (let i = 0; i < sel.rangeCount; i++) {
  ranges[i] = sel.getRangeAt(i);
}
/\* Each item in the ranges array is now
 \* a range object representing one of the
 \* ranges in the current selection \*/
```

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-getrangeat |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: extend() method - Web APIs

Selection: extend() method
==========================

 The **`Selection.extend()`** method moves the focus of the
 selection to a specified point. The anchor of the selection does not move. The selection
 will be from the anchor to the new focus, regardless of direction.

Syntax
------

```js
extend(node)
extend(node, offset)
```

### Parameters

`node`

The node within which the focus will be moved.

`offset` Optional

 The offset position within `node` where the focus will be moved to. If
 not specified, the default value `0` is used.

### Return value

None (`undefined`).

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-extend |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: removeRange() method - Web APIs

Selection: removeRange() method
===============================

 The **`Selection.removeRange()`** method removes a range from a
 selection.

Syntax
------

```js
removeRange(range)
```

### Parameters

`range`

A range object that will be removed to the selection.

### Return value

None (`undefined`).

Examples
--------

```js
/\* Programmatically, more than one range can be selected.
 \* This will remove all ranges except the first. \*/
const s = window.getSelection();
if (s.rangeCount > 1) {
  for (let i = 1; i < s.rangeCount; i++) {
    s.removeRange(s.getRangeAt(i));
  }
}
```

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-removerange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: anchorOffset property - Web APIs

Selection: anchorOffset property
================================

 The **`Selection.anchorOffset`** read-only property returns the
 number of characters that the selection's anchor is offset within the
 `Selection.anchorNode`.

 This number is zero-based. If the selection begins with the first character in the
 `Selection.anchorNode`, `0` is returned.

Value
-----

A number.

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-anchoroffset |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: focusNode property - Web APIs

Selection: focusNode property
=============================

 The **`Selection.focusNode`** read-only property returns the
 `Node` in which the selection ends.

 A user may make a selection from left to right (in document order) or right to left
 (reverse of document order). The focus is where the user ended the selection. This can
 be visualized by holding the `Shift` key and pressing the arrow keys on your
 keyboard to modify the current selection. The selection's focus moves, but the
 selection's anchor, the other end of the selection, does not move.

Value
-----

A `Node` object.

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-focusnode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: selectAllChildren() method - Web APIs

Selection: selectAllChildren() method
=====================================

 The **`Selection.selectAllChildren()`** method adds all the
 children of the specified node to the selection. Previous selection is lost.

Syntax
------

```js
selectAllChildren(parentNode)
```

### Parameters

`parentNode`

 All children of `parentNode` will be selected. `parentNode`
 itself is not part of the selection.

### Return value

None (`undefined`).

Examples
--------

### HTML

```html
<main>
  <button>Select Footer</button>
  <p>Welcome to my website.</p>
  <p>I hope you enjoy your visit.</p>
</main>
<footer>
  <address>webmaster@example.com</address>
  <p>© 2019</p>
</footer>
```

### JavaScript

```js
const button = document.querySelector("button");
const footer = document.querySelector("footer");

button.addEventListener("click", (e) => {
  window.getSelection().selectAllChildren(footer);
});
```

### Result

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-selectallchildren |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: collapseToEnd() method - Web APIs

Selection: collapseToEnd() method
=================================

 The **`Selection.collapseToEnd()`** method collapses the
 selection to the end of the last range in the selection. If the content of the selection
 is focused and editable, the caret will blink there.

Syntax
------

```js
collapseToEnd()
```

### Parameters

None.

### Return value

None (`undefined`).

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-collapsetoend |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: empty() method - Web APIs

Selection: empty() method
=========================

The **`Selection.empty()`** method removes all ranges from the selection, leaving the `anchorNode` and `focusNode` properties equal to `null` and nothing selected. When this method is called, a `selectionchange` event is fired at the document.

**Note:** This method is an alias for the `Selection.removeAllRanges()` method.

Syntax
------

```js
empty()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

This example displays a message when something is selected on the page or not. It does this by listening to the `selectionchange` event on the document. There also is a button that clears any selection by calling `Selection.empty()`. When this happens, the selection is changed and the message is updated.

```html
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse laoreet
  urna eget sapien venenatis, eget facilisis diam mattis.
</p>
<button>Clear selection</button>
<pre id="log"></pre>
```

```js
const log = document.getElementById("log");

// The selection object is a singleton associated with the document
const selection = document.getSelection();

// Logs if there is a selection or not
function newSelectionHandler() {
  if (selection.rangeCount !== 0) {
    log.textContent = "Some text is selected.";
  } else {
    log.textContent = "No selection on this document.";
  }
}

document.addEventListener("selectionchange", () => {
  newSelectionHandler();
});

newSelectionHandler();

// The button cancel all selection ranges
const button = document.querySelector("button");
button.addEventListener("click", () => {
  selection.empty();
});
```

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-removeallranges |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection.removeAllRanges()`
* `selectionchange`


Selection: anchorNode property - Web APIs

Selection: anchorNode property
==============================

 The **`Selection.anchorNode`** read-only property returns the
 `Node` in which the selection begins.

 A user may make a selection from left to right (in document order) or right to left
 (reverse of document order). The anchor is where the user began the selection. This can
 be visualized by holding the Shift key and pressing the arrow keys on your keyboard. The
 selection's anchor does not move, but the selection's focus, the other end of the
 selection, does move.

Value
-----

A `Node` object.

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-anchornode |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface it belongs to.


Selection: isCollapsed property - Web APIs

Selection: isCollapsed property
===============================

 The **`Selection.isCollapsed`** read-only property returns a
 boolean value which indicates whether or not there is currently any text
 selected. No text is selected when the selection's start and end points are at the same
 position in the content.

 Keep in mind that a collapsed selection may still have one (or more, in Gecko)
 `Range`s, so `Selection.rangeCount` may not be zero. In that
 scenario, calling a `Selection` object's `getRangeAt()` method may return a `Range` object which is collapsed.

Value
-----

A boolean.

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-iscollapsed |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`
* `Range`


Selection: addRange() method - Web APIs

Selection: addRange() method
============================

 The **`Selection.addRange()`** method adds a
 `Range` to a `Selection`.

Syntax
------

```js
addRange(range)
```

### Parameters

`range`

A `Range` object that will be added to the `Selection`.

### Return value

None (`undefined`).

Examples
--------

**Note:** Currently only Firefox supports multiple selection ranges, other browsers will not
 add new ranges to the selection if it already contains one.

### HTML

```html
<p>
  I <strong>insist</strong> that you <strong>try</strong> selecting the
  <strong>strong words</strong>.
</p>
<button>Select strong words</button>
```

### JavaScript

```js
let button = document.querySelector("button");

button.addEventListener("click", () => {
  const selection = window.getSelection();
  const strongs = document.getElementsByTagName("strong");

  if (selection.rangeCount > 0) {
    selection.removeAllRanges();
  }

  for (const node of strongs) {
    const range = document.createRange();
    range.selectNode(node);
    selection.addRange(range);
  }
});
```

### Result

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-addrange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface this method belongs to


Selection: removeAllRanges() method - Web APIs

Selection: removeAllRanges() method
===================================

The **`Selection.removeAllRanges()`** method removes all ranges from the selection, leaving the `anchorNode` and `focusNode` properties equal to `null` and nothing selected. When this method is called, a `selectionchange` event is fired at the document.

**Note:** This method is an alias for the `Selection.empty()` method.

Syntax
------

```js
removeAllRanges()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

This example displays a message when something is selected on the page or not. It does this by listening to the `selectionchange` event on the document. There also is a button that clears any selection by calling `Selection.removeAllRanges()`. When this happens, the selection is changed and the message is updated.

```html
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse laoreet
  urna eget sapien venenatis, eget facilisis diam mattis.
</p>
<button>Clear selection</button>
<pre id="log"></pre>
```

```js
const log = document.getElementById("log");

// The selection object is a singleton associated with the document
const selection = document.getSelection();

// Logs if there is a selection or not
function newSelectionHandler() {
  if (selection.rangeCount !== 0) {
    log.textContent = "Some text is selected.";
  } else {
    log.textContent = "No selection on this document.";
  }
}

document.addEventListener("selectionchange", () => {
  newSelectionHandler();
});

newSelectionHandler();

// The button cancel all selection ranges
const button = document.querySelector("button");
button.addEventListener("click", () => {
  selection.removeAllRanges();
});
```

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-removeallranges |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection.empty()`
* `selectionchange`


Selection: deleteFromDocument() method - Web APIs

Selection: deleteFromDocument() method
======================================

 The **`deleteFromDocument()`** method of the
 `Selection` interface deletes the selected text from the document's DOM.

Syntax
------

```js
deleteFromDocument()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

 This example lets you delete selected text by clicking a button. Upon clicking the
 button, the
 `Window.getSelection()` method gets the selected text, and the
 `deleteFromDocument()` method removes it.

### HTML

```html
<p>
  Try highlighting some of the text in this paragraph. Once you do, you can
  remove the selected content by clicking the button below.
</p>
<button>Delete selected text</button>
```

### JavaScript

```js
let button = document.querySelector("button");
button.addEventListener("click", deleteSelection);

function deleteSelection() {
  let selection = window.getSelection();
  selection.deleteFromDocument();
}
```

### Result

Specifications
--------------

| Specification |
| --- |
| Selection API # dom-selection-deletefromdocument |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Selection`, the interface defining this method