repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/queuemicrotask/index.md
--- title: queueMicrotask() global function short-title: queueMicrotask() slug: Web/API/queueMicrotask page-type: web-api-global-function browser-compat: api.queueMicrotask --- {{APIRef("HTML DOM")}}{{AvailableInWorkers}} The **`queueMicrotask()`** method, which is exposed on the {{domxref("Window")}} or {{domxref("Worker")}} interface, queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. The microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop. This lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. You can learn more about how to use microtasks and why you might choose to do so in our [microtask guide](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide). The importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. See [Using microtasks in JavaScript with queueMicrotask()](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) for more details. Microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. ## Syntax ```js-nolint queueMicrotask(() => {/* ... */}) ``` ### Parameters - `function` - : A {{jsxref("function")}} to be executed when the browser engine determines it is safe to call your code. Enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js queueMicrotask(() => { // function contents here }); ``` Taken from the [queueMicrotask spec](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing): ```js MyElement.prototype.loadData = function (url) { if (this._cache[url]) { queueMicrotask(() => { this._setData(this._cache[url]); this.dispatchEvent(new Event("load")); }); } else { fetch(url) .then((res) => res.arrayBuffer()) .then((data) => { this._cache[url] = data; this._setData(data); this.dispatchEvent(new Event("load")); }); } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `queueMicrotask()` in `core-js`](https://github.com/zloirock/core-js#queuemicrotask) - [Using microtasks in JavaScript with queueMicrotask()](/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide) - [Asynchronous JavaScript](/en-US/docs/Learn/JavaScript/Asynchronous) - [queueMicrotask explainer](https://github.com/fergald/docs/blob/master/explainers/queueMicrotask.md) - [Tasks, microtasks, queues and schedules](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/) by Jake Archibald
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/clipboardevent/index.md
--- title: ClipboardEvent slug: Web/API/ClipboardEvent page-type: web-api-interface browser-compat: api.ClipboardEvent --- {{APIRef("Clipboard API")}} The **`ClipboardEvent`** interface of the [Clipboard API](/en-US/docs/Web/API/Clipboard_API) represents events providing information related to modification of the clipboard, that is {{domxref("Element/cut_event", "cut")}}, {{domxref("Element/copy_event", "copy")}}, and {{domxref("Element/paste_event", "paste")}} events. {{InheritanceDiagram}} ## Constructor - {{domxref("ClipboardEvent.ClipboardEvent", "ClipboardEvent()")}} - : Creates a `ClipboardEvent` event with the given parameters. ## Instance properties _Also inherits properties from its parent {{domxref("Event")}}_. - {{domxref("ClipboardEvent.clipboardData")}} {{ReadOnlyInline}} - : A {{domxref("DataTransfer")}} object containing the data affected by the user-initiated {{domxref("Element/cut_event", "cut")}}, {{domxref("Element/copy_event", "copy")}}, or {{domxref("Element/paste_event", "paste")}} operation, along with its MIME type. ## Instance methods _No specific methods; inherits methods from its parent {{domxref("Event")}}_. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Copy-related events: {{domxref("Element/copy_event", "copy")}}, {{domxref("Element/cut_event", "cut")}}, {{domxref("Element/paste_event", "paste")}} - [Clipboard API](/en-US/docs/Web/API/Clipboard_API) - [Image support for Async Clipboard article](https://web.dev/articles/async-clipboard)
0
data/mdn-content/files/en-us/web/api/clipboardevent
data/mdn-content/files/en-us/web/api/clipboardevent/clipboarddata/index.md
--- title: "ClipboardEvent: clipboardData property" short-title: clipboardData slug: Web/API/ClipboardEvent/clipboardData page-type: web-api-instance-property browser-compat: api.ClipboardEvent.clipboardData --- {{APIRef("Clipboard API")}} The **`clipboardData`** property of the {{domxref("ClipboardEvent")}} interface holds a {{domxref("DataTransfer")}} object, which can be used to: - specify what data should be put into the clipboard from the {{domxref("Element/cut_event", "cut")}} and {{domxref("Element/copy_event", "copy")}} event handlers, typically with a {{domxref("DataTransfer.setData", "setData(format, data)")}} call; - obtain the data to be pasted from the {{domxref("Element/paste_event", "paste")}} event handler, typically with a {{domxref("DataTransfer.getData", "getData(format)")}} call. See the {{domxref("Element/cut_event", "cut")}}, {{domxref("Element/copy_event", "copy")}}, and {{domxref("Element/paste_event", "paste")}} events documentation for more information. ## Value A {{domxref("DataTransfer")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Copy-related events: {{domxref("Element/copy_event", "copy")}}, {{domxref("Element/cut_event", "cut")}}, {{domxref("Element/paste_event", "paste")}} - The {{domxref("ClipboardEvent")}} interface it belongs to. - [Clipboard API](/en-US/docs/Web/API/Clipboard_API)
0
data/mdn-content/files/en-us/web/api/clipboardevent
data/mdn-content/files/en-us/web/api/clipboardevent/clipboardevent/index.md
--- title: "ClipboardEvent: ClipboardEvent() constructor" short-title: ClipboardEvent() slug: Web/API/ClipboardEvent/ClipboardEvent page-type: web-api-constructor browser-compat: api.ClipboardEvent.ClipboardEvent --- {{APIRef("Clipboard API")}} The **`ClipboardEvent()`** constructor returns a new {{domxref("ClipboardEvent")}}, representing an event providing information related to modification of the clipboard, that is {{domxref("Element/cut_event", "cut")}}, {{domxref("Element/copy_event", "copy")}}, and {{domxref("Element/paste_event", "paste")}} events. ## Syntax ```js-nolint new ClipboardEvent(type) new ClipboardEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the type of the `ClipboardEvent`. It is case-sensitive and browsers set it to `copy`, `cut`, or `paste`. - `options` {{optional_inline}} - : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, has the following properties: - `clipboardData` {{optional_inline}} - : A {{domxref("DataTransfer")}} object containing the data concerned by the clipboard event. It defaults to `null`. - `dataType` {{non-standard_inline}} {{optional_inline}} - : A string containing the MIME-type of the data contained in the `data` argument. It defaults to `""`. - `data` {{non-standard_inline}} {{optional_inline}} - : A string containing the data concerned by the clipboard event. It defaults to `""`. ### Return value A new {{domxref("ClipboardEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Copy-related events: {{domxref("Element/copy_event", "copy")}}, {{domxref("Element/cut_event", "cut")}}, {{domxref("Element/paste_event", "paste")}} - The {{domxref("ClipboardEvent")}} interface it belongs to. - [Clipboard API](/en-US/docs/Web/API/Clipboard_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgtitleelement/index.md
--- title: SVGTitleElement slug: Web/API/SVGTitleElement page-type: web-api-interface browser-compat: api.SVGTitleElement --- {{APIRef("SVG")}} The **`SVGTitleElement`** interface corresponds to the {{SVGElement("title")}} element. {{InheritanceDiagram}} ## Instance properties _This interface doesn't implement any specific properties, but inherits properties from its parent interface, {{domxref("SVGElement")}}._ ## Instance methods _This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/node/index.md
--- title: Node slug: Web/API/Node page-type: web-api-interface browser-compat: api.Node --- {{APIRef("DOM")}} The {{Glossary("DOM")}} **`Node`** interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain `Node` object. All objects that implement `Node` functionality are based on one of its subclasses. Most notable are {{domxref("Document")}}, {{domxref("Element")}}, and {{domxref("DocumentFragment")}}. In addition, every kind of DOM node is represented by an interface based on `Node`. These include {{DOMxRef("Attr")}}, {{DOMxRef("CharacterData")}} (which {{DOMxRef("Text")}}, {{DOMxRef("Comment")}}, {{DOMxRef("CDATASection")}} and {{DOMxRef("ProcessingInstruction")}} are all based on), and {{DOMxRef("DocumentType")}}. In some cases, a particular feature of the base `Node` interface may not apply to one of its child interfaces; in that case, the inheriting node may return `null` or throw an exception, depending on circumstances. For example, attempting to add children to a node type that cannot have children will throw an exception. {{InheritanceDiagram}} ## Instance properties _In addition to the properties below, `Node` inherits properties from its parent, {{DOMxRef("EventTarget")}}_. - {{DOMxRef("Node.baseURI")}} {{ReadOnlyInline}} - : Returns a string representing the base URL of the document containing the `Node`. - {{DOMxRef("Node.childNodes")}} {{ReadOnlyInline}} - : Returns a live {{DOMxRef("NodeList")}} containing all the children of this node (including elements, text and comments). {{DOMxRef("NodeList")}} being live means that if the children of the `Node` change, the {{DOMxRef("NodeList")}} object is automatically updated. - {{DOMxRef("Node.firstChild")}} {{ReadOnlyInline}} - : Returns a `Node` representing the first direct child node of the node, or `null` if the node has no child. - {{DOMxRef("Node.isConnected")}} {{ReadOnlyInline}} - : A boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the {{DOMxRef("Document")}} object in the case of the normal DOM, or the {{DOMxRef("ShadowRoot")}} in the case of a shadow DOM. - {{DOMxRef("Node.lastChild")}} {{ReadOnlyInline}} - : Returns a `Node` representing the last direct child node of the node, or `null` if the node has no child. - {{DOMxRef("Node.nextSibling")}} {{ReadOnlyInline}} - : Returns a `Node` representing the next node in the tree, or `null` if there isn't such node. - {{DOMxRef("Node.nodeName")}} {{ReadOnlyInline}} - : Returns a string containing the name of the `Node`. The structure of the name will differ with the node type. E.g. An {{DOMxRef("HTMLElement")}} will contain the name of the corresponding tag, like `'audio'` for an {{DOMxRef("HTMLAudioElement")}}, a {{DOMxRef("Text")}} node will have the `'#text'` string, or a {{DOMxRef("Document")}} node will have the `'#document'` string. - {{DOMxRef("Node.nodeType")}} {{ReadOnlyInline}} - : Returns an `unsigned short` representing the type of the node. Possible values are: | Name | Value | | ----------------------------- | ----- | | `ELEMENT_NODE` | `1` | | `ATTRIBUTE_NODE` | `2` | | `TEXT_NODE` | `3` | | `CDATA_SECTION_NODE` | `4` | | `PROCESSING_INSTRUCTION_NODE` | `7` | | `COMMENT_NODE` | `8` | | `DOCUMENT_NODE` | `9` | | `DOCUMENT_TYPE_NODE` | `10` | | `DOCUMENT_FRAGMENT_NODE` | `11` | - {{DOMxRef("Node.nodeValue")}} - : Returns / Sets the value of the current node. - {{DOMxRef("Node.ownerDocument")}} {{ReadOnlyInline}} - : Returns the {{DOMxRef("Document")}} that this node belongs to. If the node is itself a document, returns `null`. - {{DOMxRef("Node.parentNode")}} {{ReadOnlyInline}} - : Returns a `Node` that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns `null`. - {{DOMxRef("Node.parentElement")}} {{ReadOnlyInline}} - : Returns an {{DOMxRef("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{DOMxRef("Element")}}, this property returns `null`. - {{DOMxRef("Node.previousSibling")}} {{ReadOnlyInline}} - : Returns a `Node` representing the previous node in the tree, or `null` if there isn't such node. - {{DOMxRef("Node.textContent")}} - : Returns / Sets the textual content of an element and all its descendants. ## Instance methods _In addition to the methods below, `Node` inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{DOMxRef("Node.appendChild()")}} - : Adds the specified `childNode` argument as the last child to the current node. If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position. - {{DOMxRef("Node.cloneNode()")}} - : Clone a `Node`, and optionally, all of its contents. By default, it clones the content of the node. - {{DOMxRef("Node.compareDocumentPosition()")}} - : Compares the position of the current node against another node in any other document. - {{DOMxRef("Node.contains()")}} - : Returns `true` or `false` value indicating whether or not a node is a descendant of the calling node. - {{DOMxRef("Node.getRootNode()")}} - : Returns the context object's root which optionally includes the shadow root if it is available. - {{DOMxRef("Node.hasChildNodes()")}} - : Returns a boolean value indicating whether or not the element has any child nodes. - {{DOMxRef("Node.insertBefore()")}} - : Inserts a `Node` before the reference node as a child of a specified parent node. - {{DOMxRef("Node.isDefaultNamespace()")}} - : Accepts a namespace URI as an argument and returns a boolean value with a value of `true` if the namespace is the default namespace on the given node or `false` if not. - {{DOMxRef("Node.isEqualNode()")}} - : Returns a boolean value which indicates whether or not two nodes are of the same type and all their defining data points match. - {{DOMxRef("Node.isSameNode()")}} - : Returns a boolean value indicating whether or not the two nodes are the same (that is, they reference the same object). - {{DOMxRef("Node.lookupPrefix()")}} - : Returns a string containing the prefix for a given namespace URI, if present, and `null` if not. When multiple prefixes are possible, the result is implementation-dependent. - {{DOMxRef("Node.lookupNamespaceURI()")}} - : Accepts a prefix and returns the namespace URI associated with it on the given node if found (and `null` if not). Supplying `null` for the prefix will return the default namespace. - {{DOMxRef("Node.normalize()")}} - : Clean up all the text nodes under this element (merge adjacent, remove empty). - {{DOMxRef("Node.removeChild()")}} - : Removes a child node from the current element, which must be a child of the current node. - {{DOMxRef("Node.replaceChild()")}} - : Replaces one child `Node` of the current one with the second one given in parameter. ## Examples ### Remove all children nested within a node This function remove each first child of an element, until there are none left. ```js function removeAllChildren(element) { while (element.firstChild) { element.removeChild(element.firstChild); } } ``` Using this function is a single call. Here we empty the body of the document: ```js removeAllChildren(document.body); ``` An alternative could be to set the textContent to the empty string: `document.body.textContent = ""`. ### Recurse through child nodes The following function recursively calls a callback function for each node contained by a root node (including the root itself): ```js function eachNode(rootNode, callback) { if (!callback) { const nodes = []; eachNode(rootNode, (node) => { nodes.push(node); }); return nodes; } if (callback(rootNode) === false) { return false; } if (rootNode.hasChildNodes()) { for (const node of rootNode.childNodes) { if (eachNode(node, callback) === false) { return; } } } } ``` The function recursively calls a function for each descendant node of `rootNode` (including the root itself). If `callback` is omitted, the function returns an {{jsxref("Array")}} instead, which contains `rootNode` and all nodes contained within. If `callback` is provided, and it returns `false` when called, the current recursion level is aborted, and the function resumes execution at the last parent's level. This can be used to abort loops once a node has been found (such as searching for a text node which contains a certain string). The function has two parameters: - `rootNode` - : The `Node` object whose descendants will be recursed through. - `callback` {{optional_inline}} - : An optional callback [function](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) that receives a `Node` as its only argument. If omitted, `eachNode` returns an {{jsxref("Array")}} of every node contained within `rootNode` (including the root itself). The following demonstrates a real-world use of the `eachNode()` function: searching for text on a web-page. We use a wrapper function named `grep` to do the searching: ```js function grep(parentNode, pattern) { let matches = []; let endScan = false; eachNode(parentNode, (node) => { if (endScan) { return false; } // Ignore anything which isn't a text node if (node.nodeType !== Node.TEXT_NODE) { return; } if (typeof pattern === "string" && node.textContent.includes(pattern)) { matches.push(node); } else if (pattern.test(node.textContent)) { if (!pattern.global) { endScan = true; matches = node; } else { matches.push(node); } } }); return matches; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/isconnected/index.md
--- title: "Node: isConnected property" short-title: isConnected slug: Web/API/Node/isConnected page-type: web-api-instance-property browser-compat: api.Node.isConnected --- {{APIRef("DOM")}} The read-only **`isConnected`** property of the {{domxref("Node")}} interface returns a boolean indicating whether the node is connected (directly or indirectly) to a {{domxref("Document")}} object. ## Value A boolean value that is `true` if the node is connected to its relevant context object, and `false` if not. ## Examples ### Standard DOM A standard DOM example: ```js let test = document.createElement("p"); console.log(test.isConnected); // Returns false document.body.appendChild(test); console.log(test.isConnected); // Returns true ``` ### Shadow DOM A shadow DOM example: ```js // Create a shadow root const shadow = this.attachShadow({ mode: "open" }); // Create some CSS to apply to the shadow DOM const style = document.createElement("style"); console.log(style.isConnected); // returns false style.textContent = ` .wrapper { position: relative; } .info { font-size: 0.8rem; width: 200px; display: inline-block; border: 1px solid black; padding: 10px; background: white; border-radius: 10px; opacity: 0; transition: 0.6s all; positions: absolute; bottom: 20px; left: 10px; z-index: 3 } `; // Attach the created style element to the shadow DOM shadow.appendChild(style); console.log(style.isConnected); // Returns true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Node.prototype.isConnected polyfill](https://gist.github.com/eligrey/f109a6d0bf4efe3461201c3d7b745e8f)
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/getrootnode/index.md
--- title: "Node: getRootNode() method" short-title: getRootNode() slug: Web/API/Node/getRootNode page-type: web-api-instance-method browser-compat: api.Node.getRootNode --- {{APIRef("DOM")}} The **`getRootNode()`** method of the {{domxref("Node")}} interface returns the context object's root, which optionally includes the shadow root if it is available. ## Syntax ```js-nolint getRootNode() getRootNode(options) ``` ### Parameters - `options` {{optional_inline}} - : An object that sets options for getting the root node. The available options are: - `composed`: A boolean value that indicates whether the shadow root should be returned (`false`, the default), or a root node beyond shadow root (`true`). ### Return value An object inheriting from {{domxref('Node')}}. This will differ in exact form depending on where you call `getRootNode()`; for example: - Calling it on an element inside a standard web page will return an {{domxref("HTMLDocument")}} object representing the entire page (or {{HTMLElement("iframe")}}). - Calling it on an element inside a shadow DOM will return the associated {{domxref("ShadowRoot")}}. - Calling it on an element that is not attached to a document or a shadow tree will return the root of the DOM tree it belongs to. ## Examples ### Example 1 The first simple example returns a reference to the HTML/document node: ```js const rootNode = node.getRootNode(); ``` ### Example 2 This more complex example shows the difference between returning a normal root, and a root including the shadow root: ```html <div class="parent"> <div class="child"></div> </div> <div class="shadowHost">shadowHost</div> <pre id="output">Output: </pre> ``` ```js const parent = document.querySelector(".parent"); const child = document.querySelector(".child"); const shadowHost = document.querySelector(".shadowHost"); const output = document.getElementById("output"); output.textContent += `\nparent's root: ${parent.getRootNode().nodeName} \n`; // #document output.textContent += `child's root: ${child.getRootNode().nodeName} \n\n`; // #document // create a ShadowRoot const shadowRoot = shadowHost.attachShadow({ mode: "open" }); shadowRoot.innerHTML = '<style>div{background:#2bb8aa;}</style><div class="shadowChild">shadowChild</div>'; const shadowChild = shadowRoot.querySelector(".shadowChild"); // The default value of composed is false output.textContent += `shadowChild.getRootNode() === shadowRoot : ${ shadowChild.getRootNode() === shadowRoot } \n`; // true output.textContent += `shadowChild.getRootNode({composed:false}) === shadowRoot : ${ shadowChild.getRootNode({ composed: false }) === shadowRoot } \n`; // true output.textContent += `shadowChild.getRootNode({composed:true}).nodeName : ${ shadowChild.getRootNode({ composed: true }).nodeName } \n`; // #document ``` {{ EmbedLiveSample('Example 2', '100%', '200px') }} ### Example 3 This example returns the root of the unmounted tree. Note `element` here is the root of the tree (as it has no parent), so by definition its root is itself: ```js const element = document.createElement("p"); const child = document.createElement("span"); element.append(child); const rootNode = child.getRootNode(); // <p><span></span></p> element === rootNode; // true element === element.getRootNode(); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/issamenode/index.md
--- title: "Node: isSameNode() method" short-title: isSameNode() slug: Web/API/Node/isSameNode page-type: web-api-instance-method browser-compat: api.Node.isSameNode --- {{APIRef("DOM")}} The **`isSameNode()`** method of the {{domxref("Node")}} interface is a legacy alias the [for the `===` strict equality operator](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality). That is, it tests whether two nodes are the same (in other words, whether they reference the same object). > **Note:** There is no need to use `isSameNode()`; instead use the `===` strict equality operator. ## Syntax ```js-nolint isSameNode(otherNode) ``` ### Parameters - `otherNode` - : The {{domxref("Node")}} to test against. > **Note:** This parameter is not optional, but can be set to `null`. ### Return value A boolean value that is `true` if both nodes are strictly equal, `false` if not. ## Example In this example, we create three {{HTMLElement("div")}} blocks. The first and third have the same contents and attributes, while the second is different. Then we run some JavaScript to compare the nodes using `isSameNode()` and output the results. ### HTML ```html <div>This is the first element.</div> <div>This is the second element.</div> <div>This is the first element.</div> <p id="output"></p> ``` ```css hidden #output { width: 440px; border: 2px solid black; border-radius: 5px; padding: 10px; margin-top: 20px; display: block; } ``` ### JavaScript ```js let output = document.getElementById("output"); let divList = document.getElementsByTagName("div"); output.innerHTML += `div 0 same as div 0: ${divList[0].isSameNode( divList[0], )}<br/>`; output.innerHTML += `div 0 same as div 1: ${divList[0].isSameNode( divList[1], )}<br/>`; output.innerHTML += `div 0 same as div 2: ${divList[0].isSameNode( divList[2], )}<br/>`; ``` ### Results {{ EmbedLiveSample('Example', "100%", "205") }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.isEqualNode()")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/childnodes/index.md
--- title: "Node: childNodes property" short-title: childNodes slug: Web/API/Node/childNodes page-type: web-api-instance-property browser-compat: api.Node.childNodes --- {{APIRef("DOM")}} The read-only **`childNodes`** property of the {{domxref("Node")}} interface returns a live {{domxref("NodeList")}} of child {{domxref("Node","nodes")}} of the given element where the first child node is assigned index `0`. Child nodes include elements, text and comments. > **Note:** The {{domxref("NodeList")}} being live means that its content is changed each time > new children are added or removed. > > Browsers insert text nodes into a document to represent whitespace in the source markup. > Therefore a node obtained, for example, using `Node.childNodes[0]` > may refer to a whitespace text node rather than the actual element the author intended to get. > > See [Whitespace in the DOM](/en-US/docs/Web/API/Document_Object_Model/Whitespace) for more information. The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties. For example, to get the name of the first childNode, you can use `elementNodeReference.childNodes[0].nodeName`. The {{domxref("document")}} object itself has two children: the Doctype declaration and the root element, typically referred to as `documentElement`. In HTML documents the latter is the {{HTMLElement("html")}} element. It is important to keep in mind that `childNodes` includes _all_ child nodes, including non-element nodes like text and comment. To get a collection containing only elements, use {{domxref("Element.children")}} instead. ## Value A live {{domxref("NodeList")}} containing the children of the node. > **Note:** Several calls to `childNodes` return the _same_ {{domxref("NodeList")}}. ## Examples ### Simple usage ```js // Note that parg is an object reference to a <p> element // First check that the element has child nodes if (parg.hasChildNodes()) { let children = parg.childNodes; for (const node of children) { // Do something with each child as children[i] // NOTE: List is live! Adding or removing children will change the list's `length` } } ``` ### Remove all children from a node ```js // This is one way to remove all children from a node // box is an object reference to an element while (box.firstChild) { // The list is LIVE so it will re-index each call box.removeChild(box.firstChild); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.firstChild")}} - {{domxref("Node.lastChild")}} - {{domxref("Node.nextSibling")}} - {{domxref("Node.previousSibling")}} - {{domxref("Element.children")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/parentelement/index.md
--- title: "Node: parentElement property" short-title: parentElement slug: Web/API/Node/parentElement page-type: web-api-instance-property browser-compat: api.Node.parentElement --- {{APIRef("DOM")}} The read-only **`parentElement`** property of {{domxref("Node")}} interface returns the DOM node's parent {{DOMxRef("Element")}}, or `null` if the node either has no parent, or its parent isn't a DOM {{DOMxRef("Element")}}. ## Value An {{domxref("Element")}} that is the parent element of the current node, or `null` if there isn't one. ## Example ```js if (node.parentElement) { node.parentElement.style.color = "red"; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.parentNode")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/ownerdocument/index.md
--- title: "Node: ownerDocument property" short-title: ownerDocument slug: Web/API/Node/ownerDocument page-type: web-api-instance-property browser-compat: api.Node.ownerDocument --- {{APIRef("DOM")}} The read-only **`ownerDocument`** property of the {{domxref("Node")}} interface returns the top-level document object of the node. ## Value A {{domxref("Document")}} that is the top-level object in which all the child nodes are created. If this property is used on a node that is itself a document, the value is `null`. ## Example ```js // Given a node "p", get the top-level HTML // child of the document object const d = p.ownerDocument; const html = d.documentElement; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/nodevalue/index.md
--- title: "Node: nodeValue property" short-title: nodeValue slug: Web/API/Node/nodeValue page-type: web-api-instance-property browser-compat: api.Node.nodeValue --- {{APIRef("DOM")}} The **`nodeValue`** property of the {{domxref("Node")}} interface returns or sets the value of the current node. ## Value A string containing the value of the current node, if any. For the document itself, `nodeValue` returns `null`. For text, comment, and CDATA nodes, `nodeValue` returns the content of the node. For attribute nodes, the value of the attribute is returned. The following table shows the return values for different types of nodes. | Node | Value of nodeValue | | ------------------------------------ | ----------------------------------- | | {{domxref("CDATASection")}} | Content of the CDATA section | | {{domxref("Comment")}} | Content of the comment | | {{domxref("Document")}} | `null` | | {{domxref("DocumentFragment")}} | `null` | | {{domxref("DocumentType")}} | `null` | | {{domxref("Element")}} | `null` | | {{domxref("NamedNodeMap")}} | `null` | | {{domxref("ProcessingInstruction")}} | Entire content excluding the target | | {{domxref("Text")}} | Content of the text node | > **Note:** When `nodeValue` is defined to be `null`, setting it has no effect. ## Example ```html <div id="d1">Hello world</div> <!-- Example of comment --> <output id="result">Not calculated yet.</output> ``` and the following script: ```js let node = document.querySelector("body").firstChild; let result = "<br/>Node names are:<br/>"; while (node) { result += `Value of ${node.nodeName}: ${node.nodeValue}<br/>`; node = node.nextSibling; } const output = document.getElementById("result"); output.innerHTML = result; ``` {{ EmbedLiveSample("Example", "100%", "250")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/isdefaultnamespace/index.md
--- title: "Node: isDefaultNamespace() method" short-title: isDefaultNamespace() slug: Web/API/Node/isDefaultNamespace page-type: web-api-instance-method browser-compat: api.Node.isDefaultNamespace --- {{APIRef("DOM")}} The **`isDefaultNamespace()`** method of the {{domxref("Node")}} interface accepts a namespace URI as an argument. It returns a boolean value that is `true` if the namespace is the default namespace on the given node and `false` if not. > **Note:** The default namespace of an HTML element is always `""`. For a SVG element, it is set by the `xmlns` attribute. ## Syntax ```js-nolint isDefaultNamespace(namespaceURI) ``` ### Parameters - `namespaceURI` - : A string representing the namespace against which the element will be checked. > **Note:** `namespaceURI` is not an optional parameter, but can be `null`. ### Return value A boolean value that holds the return value `true` or `false`, indicating if the parameter is the default namespace, or not. ## Example ```html Is "" the default namespace for &lt;output&gt;: <output>Not tested</output>.<br /> Is "http://www.w3.org/2000/svg" the default namespace for &lt;output&gt;: <output>Not tested</output>.<br /> Is "" the default namespace for &lt;svg&gt;: <output>Not tested</output>.<br /> Is "http://www.w3.org/2000/svg" the default namespace for &lt;svg&gt;: <output>Not tested</output>.<br /> <svg xmlns="http://www.w3.org/2000/svg" height="1"></svg> <button>Click to run tests</button> ``` ```js const button = document.querySelector("button"); button.addEventListener("click", () => { const aHtmlElt = document.querySelector("output"); const aSvgElt = document.querySelector("svg"); const result = document.getElementsByTagName("output"); result[0].value = aHtmlElt.isDefaultNamespace(""); // true result[1].value = aHtmlElt.isDefaultNamespace("http://www.w3.org/2000/svg"); // false result[2].value = aSvgElt.isDefaultNamespace(""); // false result[3].value = aSvgElt.isDefaultNamespace("http://www.w3.org/2000/svg"); // true }); ``` {{ EmbedLiveSample('Example','100%',130) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.lookupNamespaceURI")}} - {{domxref("Node.lookupPrefix")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/insertbefore/index.md
--- title: "Node: insertBefore() method" short-title: insertBefore() slug: Web/API/Node/insertBefore page-type: web-api-instance-method browser-compat: api.Node.insertBefore --- {{APIRef("DOM")}} The **`insertBefore()`** method of the {{domxref("Node")}} interface inserts a node before a _reference node_ as a child of a specified _parent node_. If the given node already exists in the document, `insertBefore()` moves it from its current position to the new position. (That is, it will automatically be removed from its existing parent before appending it to the specified new parent.) This means that a node cannot be in two locations of the document simultaneously. > **Note:** The {{domxref("Node.cloneNode()")}} can be used to make a copy > of the node before appending it under the new parent. Note that the copies made with > `cloneNode()` will not be automatically kept in sync. If the given child is a {{domxref("DocumentFragment")}}, the entire contents of the `DocumentFragment` are moved into the child list of the specified parent node. ## Syntax ```js-nolint insertBefore(newNode, referenceNode) ``` ### Parameters - `newNode` - : The node to be inserted. - `referenceNode` - : The node before which `newNode` is inserted. If this is `null`, then `newNode` is inserted at the end of node's child nodes. > **Note:** `referenceNode` is **not** an optional parameter. > You must explicitly pass a {{domxref("Node")}} or `null`. > Failing to provide it or passing invalid values may [behave](https://crbug.com/419780) [differently](https://bugzil.la/119489) in different browser versions. ### Return value Returns the added child (unless `newNode` is a {{domxref("DocumentFragment")}}, in which case the empty {{domxref("DocumentFragment")}} is returned). ### Exceptions Pre-insert validity ## Example ### Example 1 ```html <div id="parentElement"> <span id="childElement">foo bar</span> </div> <script> // Create the new node to insert const newNode = document.createElement("span"); // Get a reference to the parent node const parentDiv = document.getElementById("childElement").parentNode; // Begin test case [ 1 ] : Existing childElement (all works correctly) let sp2 = document.getElementById("childElement"); parentDiv.insertBefore(newNode, sp2); // End test case [ 1 ] // Begin test case [ 2 ] : childElement is of Type undefined sp2 = undefined; // Non-existent node of id "childElement" parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node // End test case [ 2 ] // Begin test case [ 3 ] : childElement is of Type "undefined" (string) sp2 = "undefined"; // Non-existent node of id "childElement" parentDiv.insertBefore(newNode, sp2); // Generates "Type Error: Invalid Argument" // End test case [ 3 ] </script> ``` ### Example 2 ```html <div id="parentElement"> <span id="childElement">foo bar</span> </div> <script> // Create a new, plain <span> element let sp1 = document.createElement("span"); // Get the reference element let sp2 = document.getElementById("childElement"); // Get the parent element let parentDiv = sp2.parentNode; // Insert the new element into before sp2 parentDiv.insertBefore(sp1, sp2); </script> ``` > **Note:** There is no `insertAfter()` method. > It can be emulated by combining the `insertBefore` method > with {{domxref("Node.nextSibling")}}. > > In the previous example, `sp1` could be inserted after `sp2` using: > > ```js > parentDiv.insertBefore(sp1, sp2.nextSibling); > ``` > > If `sp2` does not have a next sibling, then it must be the last child β€” > `sp2.nextSibling` returns `null`, and `sp1` is inserted > at the end of the child node list (immediately after `sp2`). ### Example 3 Insert an element before the first child element, using the {{domxref("Node/firstChild", "firstChild")}} property. ```js // Get the parent element let parentElement = document.getElementById("parentElement"); // Get the parent's first child let theFirstChild = parentElement.firstChild; // Create a new element let newElement = document.createElement("div"); // Insert the new element before the first child parentElement.insertBefore(newElement, theFirstChild); ``` When the element does not have a first child, then `firstChild` is `null`. The element is still appended to the parent, after the last child. Since the parent element did not have a first child, it did not have a last child, either. Consequently, the newly inserted element is the _only_ element. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.removeChild()")}} - {{domxref("Node.replaceChild()")}} - {{domxref("Node.appendChild()")}} - {{domxref("Node.hasChildNodes()")}} - {{domxref("Element.insertAdjacentElement()")}} - {{domxref("Element.prepend()")}} - {{domxref("Element.before()")}} - {{domxref("Element.after()")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/clonenode/index.md
--- title: "Node: cloneNode() method" short-title: cloneNode() slug: Web/API/Node/cloneNode page-type: web-api-instance-method browser-compat: api.Node.cloneNode --- {{APIRef("DOM")}} The **`cloneNode()`** method of the {{domxref("Node")}} interface returns a duplicate of the node on which this method was called. Its parameter controls if the subtree contained in a node is also cloned or not. Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does _not_ copy event listeners added using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or those assigned to element properties (e.g., `node.onclick = someFunction`). Additionally, for a {{HTMLElement("canvas")}} element, the painted image is not copied. > **Warning:** `cloneNode()` may lead to duplicate element IDs in a document! > > If the original node has an `id` attribute, and the clone > will be placed in the same document, then you should modify the clone's ID to be > unique. > > Also, `name` attributes may need to be modified, > depending on whether duplicate names are expected. To clone a node to insert into a _different_ document, use {{domxref("Document.importNode()")}} instead. ## Syntax ```js-nolint cloneNode() cloneNode(deep) ``` ### Parameters - `deep` {{optional_inline}} - : If `true`, then the node and its whole subtree, including text that may be in child {{domxref("Text")}} nodes, is also copied. If `false`, only the node will be cloned. The subtree, including any text that the node contains, is not cloned. Note that `deep` has no effect on {{glossary("void element", "void elements")}}, such as the {{HTMLElement("img")}} and {{HTMLElement("input")}} elements. ### Return value The new {{domxref("Node")}} cloned. The cloned node has no parent and is not part of the document, _until_ it is added to another node that is part of the document, using {{domxref("Node.appendChild()")}} or a similar method. ## Example ```js let p = document.getElementById("para1"); let p_prime = p.cloneNode(true); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/comparedocumentposition/index.md
--- title: "Node: compareDocumentPosition() method" short-title: compareDocumentPosition() slug: Web/API/Node/compareDocumentPosition page-type: web-api-instance-method browser-compat: api.Node.compareDocumentPosition --- {{APIRef("DOM")}} The **`compareDocumentPosition()`** method of the {{domxref("Node")}} interface reports the position of its argument node relative to the node on which it is called. ## Syntax ```js-nolint compareDocumentPosition(otherNode) ``` ### Parameters - `otherNode` - : The {{domxref("Node")}} for which position should be reported, relative to the node. ### Return value An integer value representing `otherNode`'s position relative to `node` as a [bitmask](<https://en.wikipedia.org/wiki/Mask_(computing)>) combining the following constant properties of {{domxref("Node")}}: - `Node.DOCUMENT_POSITION_DISCONNECTED` (`1`) - : Both nodes are in different documents or different trees in the same document. - `Node.DOCUMENT_POSITION_PRECEDING` (`2`) - : `otherNode` precedes the node in either a [pre-order depth-first traversal](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of a tree containing both (e.g., as an ancestor or previous sibling or a descendant of a previous sibling or previous sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering. - `Node.DOCUMENT_POSITION_FOLLOWING` (`4`) - : `otherNode` follows the node in either a [pre-order depth-first traversal](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of a tree containing both (e.g., as a descendant or following sibling or a descendant of a following sibling or following sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering. - `Node.DOCUMENT_POSITION_CONTAINS` (`8`) - : `otherNode` is an ancestor of the node. - `Node.DOCUMENT_POSITION_CONTAINED_BY` (`16`) - : `otherNode` is a descendant of the node. - `Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC` (`32`) - : The result relies upon arbitrary and/or implementation-specific behavior and is not guaranteed to be portable. More than one bit is set if multiple scenarios apply. For example, if `otherNode` is located earlier in the document **_and_** contains the node on which `compareDocumentPosition()` was called, then both the `DOCUMENT_POSITION_CONTAINS` and `DOCUMENT_POSITION_PRECEDING` bits would be set, producing a value of `10` (`0x0A`). ## Example ```js const head = document.head; const body = document.body; if (head.compareDocumentPosition(body) & Node.DOCUMENT_POSITION_FOLLOWING) { console.log("Well-formed document"); } else { console.error("<head> is not before <body>"); } ``` > **Note:** Because the result returned by `compareDocumentPosition()` is a bitmask, > the [bitwise AND operator](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND) > must be used for meaningful results. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("Node.contains()")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/nodetype/index.md
--- title: "Node: nodeType property" short-title: nodeType slug: Web/API/Node/nodeType page-type: web-api-instance-property browser-compat: api.Node.nodeType --- {{APIRef("DOM")}} The read-only **`nodeType`** property of a {{domxref("Node")}} interface is an integer that identifies what the node is. It distinguishes different kind of nodes from each other, such as {{domxref("Element", "elements")}}, {{domxref("Text", "text")}} and {{domxref("Comment", "comments")}}. ## Value An integer which specifies the type of the node. Possible values are: - `Node.ELEMENT_NODE` (`1`) - : An {{domxref("Element")}} node like {{HTMLElement("p")}} or {{HTMLElement("div")}}. - `Node.ATTRIBUTE_NODE` (`2`) - : An {{domxref("Attr", "Attribute")}} of an {{domxref("Element")}}. - `Node.TEXT_NODE` (`3`) - : The actual {{domxref("Text")}} inside an {{domxref("Element")}} or {{domxref("Attr")}}. - `Node.CDATA_SECTION_NODE`(`4`) - : A {{domxref("CDATASection")}}, such as `<!CDATA[[ … ]]>` - `Node.PROCESSING_INSTRUCTION_NODE` (`7`) - : A {{domxref("ProcessingInstruction")}} of an XML document, such as `<?xml-stylesheet … ?>`. - `Node.COMMENT_NODE` (`8`) - : A {{domxref("Comment")}} node, such as `<!-- … -->`. - `Node.DOCUMENT_NODE` (`9`) - : A {{domxref("Document")}} node. - `Node.DOCUMENT_TYPE_NODE` (`10`) - : A {{domxref("DocumentType")}} node, such as `<!DOCTYPE html>`. - `Node.DOCUMENT_FRAGMENT_NODE` (`11`) - : A {{domxref("DocumentFragment")}} node. The following constants have been deprecated and are not in use anymore: `Node.ENTITY_REFERENCE_NODE` (`5`), `Node.ENTITY_NODE` (`6`), and `Node.NOTATION_NODE` (`12`). ## Examples ### Different types of nodes ```js document.nodeType === Node.DOCUMENT_NODE; // true document.doctype.nodeType === Node.DOCUMENT_TYPE_NODE; // true document.createDocumentFragment().nodeType === Node.DOCUMENT_FRAGMENT_NODE; // true const p = document.createElement("p"); p.textContent = "Once upon a time…"; p.nodeType === Node.ELEMENT_NODE; // true p.firstChild.nodeType === Node.TEXT_NODE; // true ``` ### Comments This example checks if the first node inside the document element is a comment, and displays a message if not. ```js const node = document.documentElement.firstChild; if (node.nodeType !== Node.COMMENT_NODE) { console.warn("You should comment your code!"); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/lookupprefix/index.md
--- title: "Node: lookupPrefix() method" short-title: lookupPrefix() slug: Web/API/Node/lookupPrefix page-type: web-api-instance-method browser-compat: api.Node.lookupPrefix --- {{APIRef("DOM")}} The **`lookupPrefix()`** method of the {{domxref("Node")}} interface returns a string containing the prefix for a given namespace URI, if present, and `null` if not. When multiple prefixes are possible, the first prefix is returned. ## Syntax ```js-nolint lookupPrefix(namespace) ``` ### Parameters - `namespace` - : A string containing the namespace to look the prefix up. > **Note:** This parameter is not optional but can be set to `null`. ### Return value A string containing the corresponding prefix, or `null` if none has been found. If `namespace` is null, or the empty string, `lookupPrefix()` returns `null`. If the node is a {{domxref("DocumentType")}} or a {{domxref("DocumentFragment")}}, `lookupPrefix()` always returns `null`. ## Example ```html Prefix for <code>http://www.w3.org/2000/svg</code> on &lt;output&gt;: <output>Not tested</output>.<br /> Prefix for <code>http://www.w3.org/XML/1998/namespace</code> on &lt;output&gt;: <output>Not tested</output>.<br /> Prefix for <code>http://www.w3.org/TR/html4/</code> on &lt;output&gt;: <output>Not tested</output>.<br /> Prefix for <code>https://www.w3.org/1999/xlink</code> on &lt;output&gt;: <output>Not tested</output>.<br /> Prefix for <code>http://www.w3.org/2000/svg</code> on &lt;svg&gt;: <output>Not tested</output>.<br /> Prefix for <code>https://www.w3.org/1999/xlink</code> on &lt;svg&gt;: <output>Not tested</output>.<br /> Prefix for <code>http://www.w3.org/XML/1998/namespace</code> on &lt;svg&gt;: <output>Not tested</output>.<br /> <svg xmlns:t="http://www.w3.org/2000/svg" height="1"></svg> <button>Click to see the results</button> ``` ```js const button = document.querySelector("button"); button.addEventListener("click", () => { const aHtmlElt = document.querySelector("output"); const aSvgElt = document.querySelector("svg"); const result = document.getElementsByTagName("output"); result[0].value = aHtmlElt.lookupPrefix("http://www.w3.org/2000/svg"); // true result[1].value = aHtmlElt.lookupPrefix( "http://www.w3.org/XML/1998/namespace", ); // false result[2].value = aHtmlElt.lookupPrefix("http://www.w3.org/TR/html4/"); // true result[3].value = aHtmlElt.lookupPrefix("https://www.w3.org/1999/xlink"); // false result[4].value = aSvgElt.lookupPrefix("http://www.w3.org/2000/svg"); // true result[5].value = aSvgElt.lookupPrefix("https://www.w3.org/1999/xlink"); // true result[6].value = aSvgElt.lookupPrefix( "http://www.w3.org/XML/1998/namespace", ); // false }); ``` {{ EmbedLiveSample('Example','100%',190) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [http://www.w3.org/TR/DOM-Level-3-Cor...amespacePrefix](https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix)
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/nextsibling/index.md
--- title: "Node: nextSibling property" short-title: nextSibling slug: Web/API/Node/nextSibling page-type: web-api-instance-property browser-compat: api.Node.nextSibling --- {{APIRef("DOM")}} The read-only **`nextSibling`** property of the {{domxref("Node")}} interface returns the node immediately following the specified one in their parent's {{domxref("Node.childNodes","childNodes")}}, or returns `null` if the specified node is the last child in the parent element. > **Note:** Browsers insert {{domxref("Text")}} nodes into a document to represent whitespace in the source markup. > Therefore a node obtained, for example, using [`Node.firstChild`](/en-US/docs/Web/API/Node/firstChild) > or [`Node.previousSibling`](/en-US/docs/Web/API/Node/previousSibling) > may refer to a whitespace text node rather than the actual element the author > intended to get. > > The article [Whitespace in the DOM](/en-US/docs/Web/API/Document_Object_Model/Whitespace) > contains more information about this behavior. > > You can use {{domxref("Element.nextElementSibling")}} to obtain the next element > skipping any whitespace nodes, other between-element text, or comments. > > To navigate the opposite way through the child nodes list use [Node.previousSibling](/en-US/docs/Web/API/Node/previousSibling). ## Value A {{domxref("Node")}} representing the next sibling of the current node, or `null` if there are none. ## Example ```html <div id="div-1">Here is div-1</div> <div id="div-2">Here is div-2</div> <br /> <output><em>Not calculated.</em></output> ``` ```js let el = document.getElementById("div-1").nextSibling; let i = 1; let result = "Siblings of div-1:<br/>"; while (el) { result += `${i}. ${el.nodeName}<br/>`; el = el.nextSibling; i++; } const output = document.querySelector("output"); output.innerHTML = result; ``` {{ EmbedLiveSample("Example", "100%", 500)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element.nextElementSibling")}} - {{domxref("Node.previousSibling")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/lastchild/index.md
--- title: "Node: lastChild property" short-title: lastChild slug: Web/API/Node/lastChild page-type: web-api-instance-property browser-compat: api.Node.lastChild --- {{APIRef("DOM")}} The read-only **`lastChild`** property of the {{domxref("Node")}} interface returns the last child of the node, or `null` if there are no child nodes. > **Note:** This property returns any type of node that is the last child of this one. > It may be a {{domxref("Text")}} or a {{domxref("Comment")}} node. > If you want to get the last {{domxref("Element")}} that is a child of another element, > consider using {{domxref("Element.lastElementChild")}}. ## Value A {{domxref("Node")}} that is the last child of the node, or `null` if there are no child nodes. ## Example ```js const tr = document.getElementById("row1"); const corner_td = tr.lastChild; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.firstChild")}} - {{domxref("Element.lastElementChild")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/previoussibling/index.md
--- title: "Node: previousSibling property" short-title: previousSibling slug: Web/API/Node/previousSibling page-type: web-api-instance-property browser-compat: api.Node.previousSibling --- {{APIRef("DOM")}} The read-only **`previousSibling`** property of the {{domxref("Node")}} interface returns the node immediately preceding the specified one in its parent's {{domxref("Node.childNodes", "childNodes")}} list, or `null` if the specified node is the first in that list. > **Note:** Browsers insert text nodes into a document to represent whitespace in the source markup. > Therefore a node obtained, for example, using [`Node.firstChild`](/en-US/docs/Web/API/Node/firstChild) > or `Node.previousSibling` > may refer to a whitespace text node rather than the actual element the author intended to get. > > See [Whitespace in the DOM](/en-US/docs/Web/API/Document_Object_Model/Whitespace) for more information. > > You can use [`previousElementSibling`](/en-US/docs/Web/API/Element/previousElementSibling) > to get the previous element node (skipping text nodes and any other non-element nodes). > > To navigate the opposite way through the child nodes list use [Node.nextSibling](/en-US/docs/Web/API/Node/nextSibling). ## Value A {{domxref("Node")}} representing the previous sibling of the current node, or `null` if there are none. ## Examples The following examples demonstrate how `previousSibling` works with and without text nodes mixed in with elements. ### First example In this example, we have a series of `img` elements directly adjacent to each other, with no whitespace between them. ```html <img id="b0" /><img id="b1" /><img id="b2" /> ``` ```js document.getElementById("b1").previousSibling; // <img id="b0"> document.getElementById("b2").previousSibling.id; // "b1" ``` ### Second example In this example, there are whitespace text nodes (line breaks) between the `img` elements. ```html <img id="b0" /> <img id="b1" /> <img id="b2" /> ``` ```js document.getElementById("b1").previousSibling; // #text document.getElementById("b1").previousSibling.previousSibling; // <img id="b0"> document.getElementById("b2").previousSibling.previousSibling; // <img id="b1"> document.getElementById("b2").previousSibling; // #text document.getElementById("b2").previousSibling.id; // undefined ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.nextSibling")}} - {{domxref("Element.previousElementSibling")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/haschildnodes/index.md
--- title: "Node: hasChildNodes() method" short-title: hasChildNodes() slug: Web/API/Node/hasChildNodes page-type: web-api-instance-method browser-compat: api.Node.hasChildNodes --- {{APIRef("DOM")}} The **`hasChildNodes()`** method of the {{domxref("Node")}} interface returns a boolean value indicating whether the given {{domxref("Node")}} has [child nodes](/en-US/docs/Web/API/Node/childNodes) or not. ## Syntax ```js-nolint hasChildNodes() ``` ### Parameters None. ### Return value A boolean value that is `true` if the node has child nodes, and `false` otherwise. ## Example ```js let foo = document.getElementById("foo"); if (foo.hasChildNodes()) { // Do something with 'foo.childNodes' } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.childNodes")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/contains/index.md
--- title: "Node: contains() method" short-title: contains() slug: Web/API/Node/contains page-type: web-api-instance-method browser-compat: api.Node.contains --- {{APIRef("DOM")}} The **`contains()`** method of the {{domxref("Node")}} interface returns a boolean value indicating whether a node is a descendant of a given node, that is the node itself, one of its direct children ({{domxref("Node.childNodes", "childNodes")}}), one of the children's direct children, and so on. > **Note:** A node is _contained_ inside itself. ## Syntax ```js-nolint contains(otherNode) ``` ### Parameters - `otherNode` - : The {{domxref("Node")}} to test with. > **Note:** `otherNode` is not optional, but can be set to `null`. ### Return value A boolean value that is `true` if `otherNode` is contained in the node, `false` if not. If the `otherNode` parameter is `null`, `contains()` always returns `false`. ## Example This function checks to see if an element is in the page's body. As `contains` is inclusive and determining if the body contains itself isn't the intention of `isInPage` this case explicitly returns `false`. ```js function isInPage(node) { return node === document.body ? false : document.body.contains(node); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.compareDocumentPosition")}} - {{domxref("Node.hasChildNodes")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/appendchild/index.md
--- title: "Node: appendChild() method" short-title: appendChild() slug: Web/API/Node/appendChild page-type: web-api-instance-method browser-compat: api.Node.appendChild --- {{APIRef("DOM")}} The **`appendChild()`** method of the {{domxref("Node")}} interface adds a node to the end of the list of children of a specified parent node. > **Note:** If the given child is a reference to an existing node in the document, `appendChild()` moves it from its current position to the new position. If the given child is a {{domxref("DocumentFragment")}}, the entire contents of the {{domxref("DocumentFragment")}} are moved into the child list of the specified parent node. `appendChild()` returns the newly appended node, or if the child is a {{domxref("DocumentFragment")}}, the emptied fragment. > **Note:** Unlike this method, the {{domxref("Element.append()")}} method supports multiple arguments and appending strings. You can prefer using it if your node is an element. ## Syntax ```js-nolint appendChild(aChild) ``` ### Parameters - `aChild` - : The node to append to the given parent node (commonly an element). ### Return value A {{domxref("Node")}} that is the appended child (`aChild`), except when `aChild` is a {{domxref("DocumentFragment")}}, in which case the empty {{domxref("DocumentFragment")}} is returned. ### Exceptions - `HierarchyRequestError` {{domxref("DOMException")}} - : Thrown when the constraints of the DOM tree are violated, that is if one of the following cases occurs: - If the parent of `aChild` is not a {{domxref("Document")}}, {{domxref("DocumentFragment")}}, or an {{domxref("Element")}}. - If the insertion of `aChild` would lead to a cycle, that is if `aChild` is an ancestor of the node. - If `aChild` is not a {{domxref("DocumentFragment")}}, a {{domxref("DocumentType")}}, an {{domxref("Element")}}, or a {{domxref("CharacterData")}}. - If the current node is a {{domxref("Text")}}, and its parent is a {{domxref("Document")}}. - If the current node is a {{domxref("DocumentType")}} and its parent is _not_ a {{domxref("Document")}}, as a _doctype_ should always be a direct descendant of a _document_. - If the parent of the node is a {{domxref("Document")}} and `aChild` is a {{domxref("DocumentFragment")}} with more than one {{domxref("Element")}} child, or that has a {{domxref("Text")}} child. - If the insertion of `aChild` would lead to {{domxref("Document")}} with more than one {{domxref("Element")}} as child. ## Description If the given child is a reference to an existing node in the document, `appendChild()` moves it from its current position to the new position β€” there is no requirement to remove the node from its parent node before appending it to some other node. This means that a node can't be in two points of the document simultaneously. The {{domxref("Node.cloneNode()")}} method can be used to make a copy of the node before appending it under the new parent. Copies made with `cloneNode` are not automatically kept in sync. `appendChild()` returns the newly appended node, instead of the parent node. This means you can append the new node as soon as it's created without losing reference to it: ```js const paragraph = document.body.appendChild(document.createElement("p")); // You can append more elements to the paragraph later ``` On the other hand, you cannot use `appendChild()` in a [fluent API](https://en.wikipedia.org/wiki/Fluent_interface) fashion (like JQuery). ```js example-bad // This doesn't append three paragraphs: // the three elements will be nested instead of siblings document.body .appendChild(document.createElement("p")) .appendChild(document.createElement("p")) .appendChild(document.createElement("p")); ``` ## Example ### Append a paragraph to the body ```js // Create a new paragraph element, and append it to the end of the document body const p = document.createElement("p"); document.body.appendChild(p); ``` ### Creating a nested DOM structure In this example, we attempt to create a nested DOM structure using as few temporary variables as possible. ```js const fragment = document.createDocumentFragment(); const li = fragment .appendChild(document.createElement("section")) .appendChild(document.createElement("ul")) .appendChild(document.createElement("li")); li.textContent = "hello world"; document.body.appendChild(fragment); ``` It generates the following DOM tree: ```html <section> <ul> <li>hello world</li> </ul> </section> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.removeChild()")}} - {{domxref("Node.replaceChild()")}} - {{domxref("Node.insertBefore()")}} - {{domxref("Node.hasChildNodes()")}} - {{domxref("Element.insertAdjacentElement()")}} - {{domxref("Element.append()")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/parentnode/index.md
--- title: "Node: parentNode property" short-title: parentNode slug: Web/API/Node/parentNode page-type: web-api-instance-property browser-compat: api.Node.parentNode --- {{APIRef("DOM")}} The read-only **`parentNode`** property of the {{domxref("Node")}} interface returns the parent of the specified node in the DOM tree. `Document` and `DocumentFragment` [nodes](/en-US/docs/Web/API/Node/nodeType) can never have a parent, so `parentNode` will always return `null`. It also returns `null` if the node has just been created and is not yet attached to the tree. ## Value A {{domxref("Node")}} that is the parent of the current node. The parent of an element is an `Element` node, a `Document` node, or a `DocumentFragment` node. ## Example ```js if (node.parentNode) { // remove a node from the tree, unless // it's not in the tree already node.parentNode.removeChild(node); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{Domxref("Node.firstChild")}} - {{Domxref("Node.lastChild")}} - {{Domxref("Node.childNodes")}} - {{Domxref("Node.nextSibling")}} - {{Domxref("Node.parentElement")}} - {{Domxref("Node.previousSibling")}} - {{Domxref("Node.removeChild")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/normalize/index.md
--- title: "Node: normalize() method" short-title: normalize() slug: Web/API/Node/normalize page-type: web-api-instance-method browser-compat: api.Node.normalize --- {{APIRef("DOM")}} The **`normalize()`** method of the {{domxref("Node")}} interface puts the specified node and all of its sub-tree into a _normalized_ form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes. ## Syntax ```js-nolint normalize() ``` ### Parameters None. ### Return value None. ## Example ```html <output id="result"></output> ``` ```js const wrapper = document.createElement("div"); wrapper.appendChild(document.createTextNode("Part 1 ")); wrapper.appendChild(document.createTextNode("Part 2 ")); let node = wrapper.firstChild; let result = "Before normalization:<br/>"; while (node) { result += ` ${node.nodeName}: ${node.nodeValue}<br/>`; node = node.nextSibling; } wrapper.normalize(); node = wrapper.firstChild; result += "<br/><br/>After normalization:<br/>"; while (node) { result += ` ${node.nodeName}: ${node.nodeValue}<br/>`; node = node.nextSibling; } const output = document.getElementById("result"); output.innerHTML = result; ``` {{ EmbedLiveSample("Example", "100%", "170")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Text.splitText()")}}, its opposite.
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/replacechild/index.md
--- title: "Node: replaceChild() method" short-title: replaceChild() slug: Web/API/Node/replaceChild page-type: web-api-instance-method browser-compat: api.Node.replaceChild --- {{APIRef("DOM")}} The **`replaceChild()`** method of the {{domxref("Node")}} interface replaces a child node within the given (parent) node. ## Syntax ```js-nolint replaceChild(newChild, oldChild) ``` ### Parameters - `newChild` - : The new node to replace `oldChild`. > **Warning:** If the new node is already present somewhere else in the DOM, it is first removed from that position. - `oldChild` - : The child to be replaced. > **Note:** The parameter order, _new_ before _old_, is unusual. > [`Element.replaceWith()`](/en-US/docs/Web/API/Element/replaceWith), applying only to nodes that are elements, > may be easier to read and use. ### Return value The replaced {{domxref("Node")}}. This is the same node as `oldChild`. ### Exceptions - `HierarchyRequestError` {{domxref("DOMException")}} - : Thrown when the constraints of the DOM tree are violated, that is if one of the following cases occurs: - If the parent of `oldChild` is not a {{domxref("Document")}}, {{domxref("DocumentFragment")}}, or an {{domxref("Element")}}. - If the replacement of `oldChild` by `newChild` would lead to a cycle, that is if `newChild` is an ancestor of the node. - If `newChild` is not a {{domxref("DocumentFragment")}}, a {{domxref("DocumentType")}}, an {{domxref("Element")}}, or a {{domxref("CharacterData")}}. - If the current node is a {{domxref("Text")}}, and its parent is a {{domxref("Document")}}. - If the current node is a {{domxref("DocumentType")}} and its parent is _not_ a {{domxref("Document")}}, as a _doctype_ should always be a direct descendant of a _document_. - If the parent of the node is a {{domxref("Document")}} and `newChild` is a {{domxref("DocumentFragment")}} with more than one {{domxref("Element")}} child, or that has a {{domxref("Text")}} child. - If the replacement of `oldChild` by `newChild` would lead to {{domxref("Document")}} with more than one {{domxref("Element")}} as child. - If the replacement of `oldChild` by `newChild` would lead to the presence of an {{domxref("Element")}} node before a {{domxref("DocumentType")}} node. - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the parent of `oldChild` is not the current node. ## Example ```js // Given: // <div> // <span id="childSpan">foo bar</span> // </div> // Create an empty element node // without an ID, any attributes, or any content const sp1 = document.createElement("span"); // Give it an id attribute called 'newSpan' sp1.id = "newSpan"; // Create some content for the new element. const sp1_content = document.createTextNode("new replacement span element."); // Apply that content to the new element sp1.appendChild(sp1_content); // Build a reference to the existing node to be replaced const sp2 = document.getElementById("childSpan"); const parentDiv = sp2.parentNode; // Replace existing node sp2 with the new span element sp1 parentDiv.replaceChild(sp1, sp2); // Result: // <div> // <span id="newSpan">new replacement span element.</span> // </div> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.removeChild")}} - {{domxref("Element.replaceWith")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/nodename/index.md
--- title: "Node: nodeName property" short-title: nodeName slug: Web/API/Node/nodeName page-type: web-api-instance-property browser-compat: api.Node.nodeName --- {{APIRef("DOM")}} The read-only **`nodeName`** property of {{domxref("Node")}} returns the name of the current node as a string. ## Value A string. Values for the different types of nodes are: - {{domxref("Attr")}} - : The value of {{domxref("Attr.name")}}, that is the _qualified name_ of the attribute. - {{domxref("CDATASection")}} - : The string `"#cdata-section"`. - {{domxref("Comment")}} - : The string `"#comment"`. - {{domxref("Document")}} - : The string `"#document"`. - {{domxref("DocumentFragment")}} - : The string `"#document-fragment"`. - {{domxref("DocumentType")}} - : The value of {{domxref("DocumentType.name")}} - {{domxref("Element")}} - : The value of {{domxref("Element.tagName")}}, that is the _uppercase_ name of the element tag if an HTML element, or the _lowercase_ element tag if an XML element (like a SVG or MATHML element). - {{domxref("ProcessingInstruction")}} - : The value of {{domxref("ProcessingInstruction.target")}} - {{domxref("Text")}} - : The string `"#text"`. ## Example This example displays the node names of several nodes ```html This is some HTML: <div id="d1">Hello world</div> <!-- Example of comment --> Text <span>Text</span> Text<br /> <svg height="20" width="20"> <circle cx="10" cy="10" r="5" stroke="black" stroke-width="1" fill="red" /> </svg> <hr /> <output id="result">Not calculated yet.</output> ``` and the following script: ```js let node = document.querySelector("body").firstChild; let result = "Node names are:<br/>"; while (node) { result += `${node.nodeName}<br/>`; node = node.nextSibling; } const output = document.getElementById("result"); output.innerHTML = result; ``` {{ EmbedLiveSample("Example", "100%", "450")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element.tagName")}} - {{domxref("Attr.name")}} - {{domxref("DocumentType.name")}} - {{domxref("ProcessingInstruction.target")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/firstchild/index.md
--- title: "Node: firstChild property" short-title: firstChild slug: Web/API/Node/firstChild page-type: web-api-instance-property browser-compat: api.Node.firstChild --- {{APIRef("DOM")}} The read-only **`firstChild`** property of the {{domxref("Node")}} interface returns the node's first child in the tree, or `null` if the node has no children. If the node is a {{domxref("Document")}}, this property returns the first node in the list of its direct children. > **Note:** This property returns any type of node that is the first child of this one. > It may be a {{domxref("Text")}} or a {{domxref("Comment")}} node. > If you want to get the first {{domxref("Element")}} that is a child of another element, > consider using {{domxref("Element.firstElementChild")}}. ## Value A {{domxref("Node")}}, or `null` if there are none. ## Example This example demonstrates the use of `firstChild` and how whitespace nodes might interfere with using this property. ```html <p id="para-01"> <span>First span</span> </p> <script> const p01 = document.getElementById("para-01"); console.log(p01.firstChild.nodeName); </script> ``` In the above, the [console](/en-US/docs/Web/API/console) will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening `<p>` and `<span>` tags. **Any** [whitespace](/en-US/docs/Web/API/Document_Object_Model/Whitespace) will create a `#text` node, from a single space to multiple spaces, returns, tabs, and so on. Another `#text` node is inserted between the closing `</span>` and `</p>` tags. If this whitespace is removed from the source, the #text nodes are not inserted and the span element becomes the paragraph's first child. ```html <p id="para-01"><span>First span</span></p> <script> const p01 = document.getElementById("para-01"); console.log(p01.firstChild.nodeName); </script> ``` Now the console will show 'SPAN'. To avoid the issue with `node.firstChild` returning `#text` or `#comment` nodes, {{domxref("Element.firstElementChild")}} can be used to return only the first element node. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element.firstElementChild")}} - {{domxref("Node.lastChild")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/selectstart_event/index.md
--- title: "Node: selectstart event" short-title: selectstart slug: Web/API/Node/selectstart_event page-type: web-api-event browser-compat: api.Node.selectstart_event --- {{APIRef}} The **`selectstart`** event of the [Selection API](/en-US/docs/Web/API/Selection) is fired when a user starts a new selection. If the event is canceled, the selection is not changed. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("selectstart", (event) => {}); onselectstart = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js // addEventListener version document.addEventListener("selectstart", () => { console.log("Selection started"); }); // onselectstart version document.onselectstart = () => { console.log("Selection started."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Document/selectionchange_event", "selectionchange")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/lookupnamespaceuri/index.md
--- title: "Node: lookupNamespaceURI() method" short-title: lookupNamespaceURI() slug: Web/API/Node/lookupNamespaceURI page-type: web-api-instance-method browser-compat: api.Node.lookupNamespaceURI --- {{APIRef("DOM")}} The **`lookupNamespaceURI()`** method of the {{domxref("Node")}} interface takes a prefix as parameter and returns the namespace URI associated with it on the given node if found (and `null` if not). ## Syntax ```js-nolint lookupNamespaceURI(prefix) ``` ### Parameters - `prefix` - : The prefix to look for. > **Note:** This parameter is not optional, but can be set to `null`. ### Return value A string containing the namespace URI corresponding to the prefix. If the prefix is not found, it returns `null`. If the requested `prefix` is `null`, it returns the default namespace URI. ## Example ```html Namespace URL for <code>xlink</code> on &lt;output&gt;: <output>Not tested</output>.<br /> Namespace URL for <code>xml</code> on &lt;output&gt;: <output>Not tested</output>.<br /> Namespace URL for <code>html</code> on &lt;output&gt;: <output>Not tested</output>.<br /> Namespace URL for <code>``</code> on &lt;output&gt;: <output>Not tested</output>.<br /> Namespace URL for <code>svg</code> on &lt;svg&gt;: <output>Not tested</output>.<br /> Namespace URL for <code>xlink</code> on &lt;svg&gt;: <output>Not tested</output>.<br /> Namespace URL for <code>xml</code> on &lt;svg&gt;: <output>Not tested</output>.<br /> <svg xmlns:svg="http://www.w3.org/2000/svg" height="1"></svg> <button>Click to see the results</button> ``` ```js const button = document.querySelector("button"); button.addEventListener("click", () => { const aHtmlElt = document.querySelector("output"); const aSvgElt = document.querySelector("svg"); const result = document.getElementsByTagName("output"); result[0].value = aHtmlElt.lookupNamespaceURI("xlink"); result[1].value = aHtmlElt.lookupNamespaceURI("xml"); result[2].value = aHtmlElt.lookupNamespaceURI("html"); result[3].value = aHtmlElt.lookupNamespaceURI(""); result[4].value = aSvgElt.lookupNamespaceURI("svg"); result[5].value = aSvgElt.lookupNamespaceURI("xlink"); result[6].value = aSvgElt.lookupNamespaceURI("xml"); }); ``` {{ EmbedLiveSample('Example','100%',190) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.lookupPrefix")}} - {{domxref("Node.isDefaultNameSpace")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/removechild/index.md
--- title: "Node: removeChild() method" short-title: removeChild() slug: Web/API/Node/removeChild page-type: web-api-instance-method browser-compat: api.Node.removeChild --- {{APIRef("DOM")}} The **`removeChild()`** method of the {{domxref("Node")}} interface removes a child node from the DOM and returns the removed node. > **Note:** As long as a reference is kept on the removed child, > it still exists in memory, but is no longer part of the DOM. > It can still be reused later in the code. > > If the return value of `removeChild()` is not stored, and no other reference is kept, > it will be [automatically deleted](/en-US/docs/Web/JavaScript/Memory_management) from memory after a short time. Unlike {{domxref("Node.cloneNode()")}} the return value preserves the `EventListener` objects associated with it. ## Syntax ```js-nolint removeChild(child) ``` ### Parameters - `child` - : A {{domxref("Node")}} that is the child node to be removed from the DOM. ### Exception - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the `child` is not a child of the node. - {{jsxref("TypeError")}} - : Thrown if the `child` is `null`. ## Examples ### Simple examples Given this HTML: ```html <div id="parent"> <div id="child"></div> </div> ``` To remove a specified element when knowing its parent node: ```js const parent = document.getElementById("parent"); const child = document.getElementById("child"); const throwawayNode = parent.removeChild(child); ``` To remove a specified element without having to specify its parent node: ```js const node = document.getElementById("child"); if (node.parentNode) { node.parentNode.removeChild(node); } ``` To remove all children from an element: ```js const element = document.getElementById("idOfParent"); while (element.firstChild) { element.removeChild(element.firstChild); } ``` ### Causing a TypeError ```html <!--Sample HTML code--> <div id="parent"></div> ``` ```js const parent = document.getElementById("parent"); const child = document.getElementById("child"); // Throws Uncaught TypeError const garbage = parent.removeChild(child); ``` ### Causing a NotFoundError ```html <!--Sample HTML code--> <div id="parent"> <div id="child"></div> </div> ``` ```js const parent = document.getElementById("parent"); const child = document.getElementById("child"); // This first call correctly removes the node const garbage = parent.removeChild(child); // Throws NotFoundError garbage = parent.removeChild(child); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.replaceChild()")}} - {{domxref("Node.parentNode")}} - {{domxref("Element.remove()")}} - {{domxref("Node.cloneNode()")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/textcontent/index.md
--- title: "Node: textContent property" short-title: textContent slug: Web/API/Node/textContent page-type: web-api-instance-property browser-compat: api.Node.textContent --- {{APIRef("DOM")}} The **`textContent`** property of the {{domxref("Node")}} interface represents the text content of the node and its descendants. > **Note:** `textContent` and {{domxref("HTMLElement.innerText")}} are easily confused, > but the two properties are [different in important ways](#differences_from_innertext). ## Value A string, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null). Its value depends on the situation: - If the node is a {{domxref("document")}} or a {{glossary("doctype")}}, `textContent` returns [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null). > **Note:** To get _all_ of the text and [CDATA data](/en-US/docs/Web/API/CDATASection) for the whole > document, use `document.documentElement.textContent`. - If the node is a [CDATA section](/en-US/docs/Web/API/CDATASection), a comment, a [processing instruction](/en-US/docs/Web/API/ProcessingInstruction), or a [text node](/en-US/docs/Web/API/Text), `textContent` returns, or sets, the text inside the node, i.e., the {{domxref("Node.nodeValue")}}. - For other node types, `textContent` returns the concatenation of the `textContent` of every child node, excluding comments and processing instructions. (This is an empty string if the node has no children.) > **Warning:** Setting `textContent` on a node removes _all_ of the node's children > and replaces them with a single text node with the given string value. ### Differences from innerText Don't get confused by the differences between `Node.textContent` and {{domxref("HTMLElement.innerText")}}. Although the names seem similar, there are important differences: - `textContent` gets the content of _all_ elements, including {{HTMLElement("script")}} and {{HTMLElement("style")}} elements. In contrast, `innerText` only shows "human-readable" elements. - `textContent` returns every element in the node. In contrast, `innerText` is aware of styling and won't return the text of "hidden" elements. - Moreover, since `innerText` takes CSS styles into account, reading the value of `innerText` triggers a {{glossary("reflow")}} to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.) ### Differences from innerHTML {{domxref("Element.innerHTML")}} returns HTML, as its name indicates. Sometimes people use `innerHTML` to retrieve or write text inside an element, but `textContent` has better performance because its value is not parsed as HTML. Moreover, using `textContent` can prevent {{glossary("Cross-site_scripting", "XSS attacks")}}. ## Examples Start with this HTML fragment. ```html <div id="divA">This is <span>some</span> text!</div> ``` You can use `textContent` to get the element's text content: ```js let text = document.getElementById("divA").textContent; // The text variable is now: 'This is some text!' ``` If you prefer to set the element's text content, you can do: ```js document.getElementById("divA").textContent = "This text is different!"; // The HTML for divA is now: // <div id="divA">This text is different!</div> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLElement.innerText")}} - {{domxref("Element.innerHTML")}} - [More on differences between `innerText` and `textContent`](http://perfectionkills.com/the-poor-misunderstood-innerText/) (blog post)
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/isequalnode/index.md
--- title: "Node: isEqualNode() method" short-title: isEqualNode() slug: Web/API/Node/isEqualNode page-type: web-api-instance-method browser-compat: api.Node.isEqualNode --- {{APIRef("DOM")}} The **`isEqualNode()`** method of the {{domxref("Node")}} interface tests whether two nodes are equal. Two nodes are equal when they have the same type, defining characteristics (for elements, this would be their ID, number of children, and so forth), its attributes match, and so on. The specific set of data points that must match varies depending on the types of the nodes. ## Syntax ```js-nolint isEqualNode(otherNode) ``` ### Parameters - `otherNode` - : The {{domxref("Node")}} to compare equality with. > **Note:** This parameter is not optional, but can be set to `null`. ### Return value A boolean value that is `true` if the two nodes are equals, or `false` if not. If `otherNode` is `null`, `isEqualNode()` always return false. ## Example In this example, we create three {{HTMLElement("div")}} blocks. The first and third have the same contents and attributes, while the second is different. Then we run some JavaScript to compare the nodes using `isEqualNode()` and output the results. ### HTML ```html <div>This is the first element.</div> <div>This is the second element.</div> <div>This is the first element.</div> <p id="output"></p> ``` ```css hidden #output { width: 440px; border: 2px solid black; border-radius: 5px; padding: 10px; margin-top: 20px; display: block; } ``` ### JavaScript ```js let output = document.getElementById("output"); let divList = document.getElementsByTagName("div"); output.innerHTML += `div 0 equals div 0: ${divList[0].isEqualNode( divList[0], )}<br/>`; output.innerHTML += `div 0 equals div 1: ${divList[0].isEqualNode( divList[1], )}<br/>`; output.innerHTML += `div 0 equals div 2: ${divList[0].isEqualNode( divList[2], )}<br/>`; ``` ### Results {{ EmbedLiveSample('Example', "100%", "210") }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Node.isSameNode()")}}
0
data/mdn-content/files/en-us/web/api/node
data/mdn-content/files/en-us/web/api/node/baseuri/index.md
--- title: "Node: baseURI property" short-title: baseURI slug: Web/API/Node/baseURI page-type: web-api-instance-property browser-compat: api.Node.baseURI --- {{APIRef("DOM")}} The read-only **`baseURI`** property of the {{domxref("Node")}} interface returns the absolute base URL of the document containing the node. The base URL is used to resolve relative URLs when the browser needs to obtain an absolute URL, for example when processing the HTML {{HTMLElement("img")}} element's `src` attribute or the `xlink:href` {{deprecated_inline}} or `href` attributes in SVG. Although this property is read-only, its value is determined by an algorithm each time the property is accessed, and may change if the conditions changed. The base URL is determined as follows: 1. By default, the base URL is the location of the document (as determined by {{domxref("window.location")}}). 2. If it is an HTML Document and there is a {{HTMLElement("Base")}} element in the document, the `href` value of the _first_ `Base` element with such an attribute is used instead. ## Value A string representing the base URL of the {{domxref("Node")}}. ## Examples ### Without \<base> ```html <output>Not calculated</output> ``` ```js const output = document.querySelector("output"); output.value = output.baseURI; ``` {{EmbedLiveSample("Without_base", "100%", 40)}} ### With \<base> ```html <base href="https://developer.mozilla.org/modified_base_uri/" /> <output>Not calculated</output> ``` ```js const output = document.querySelector("output"); output.value = output.baseURI; ``` {{EmbedLiveSample("With_base", "100%", 40)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("base")}} element.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/usbalternateinterface/index.md
--- title: USBAlternateInterface slug: Web/API/USBAlternateInterface page-type: web-api-interface status: - experimental browser-compat: api.USBAlternateInterface --- {{securecontext_header}}{{APIRef("WebUSB API")}}{{SeeCompatTable}} The `USBAlternateInterface` interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) provides information about a particular configuration of an interface provided by the USB device. An interface includes one or more alternate settings which can configure a set of endpoints based on the operating mode of the device. ## Constructor - {{domxref("USBAlternateInterface.USBAlternateInterface", "USBAlternateInterface()")}} {{Experimental_Inline}} - : Creates a new `USBAlternateInterface` object which will be populated with information about the alternate interface of the provided `USBInterface` with the given alternate setting number. ## Instance properties - {{domxref("USBAlternateInterface.alternateSetting")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the alternate setting number of this interface. This is equal to the `bAlternateSetting` field of the interface descriptor defining this interface. - {{domxref("USBAlternateInterface.interfaceClass")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the class of this interface. This is equal to the `bInterfaceClass` field of the interface descriptor defining this interface. [Standardized values](https://www.usb.org/defined-class-codes) for this field are defined by the USB Implementers Forum. A value of `0xFF` indicates a vendor-defined interface. - {{domxref("USBAlternateInterface.interfaceSubclass")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the subclass of this interface. This is equal to the `bInterfaceSubClass` field of the interface descriptor defining this interface. The meaning of this value depends on the `interfaceClass` field. - {{domxref("USBAlternateInterface.interfaceProtocol")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the protocol supported by this interface. This is equal to the `bInterfaceProtocol` field of the interface descriptor defining this interface. The meaning of this value depends on the `interfaceClass` and `interfaceSubclass` fields. - {{domxref("USBAlternateInterface.interfaceName")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the name of the interface, if one is provided by the device. This is the value of the string descriptor with the index specified by the `iInterface` field of the interface descriptor defining this interface. - {{domxref("USBAlternateInterface.endpoints")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns an array containing instances of the `USBEndpoint` interface describing each of the endpoints that are part of this interface. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/speechsynthesiserrorevent/index.md
--- title: SpeechSynthesisErrorEvent slug: Web/API/SpeechSynthesisErrorEvent page-type: web-api-interface browser-compat: api.SpeechSynthesisErrorEvent --- {{APIRef("Web Speech API")}} The **`SpeechSynthesisErrorEvent`** interface of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) contains information about any errors that occur while processing {{domxref("SpeechSynthesisUtterance")}} objects in the speech service. {{InheritanceDiagram}} ## Constructor - {{domxref("SpeechSynthesisErrorEvent.SpeechSynthesisErrorEvent", "SpeechSynthesisErrorEvent()")}} - : Creates a new `SpeechSynthesisErrorEvent`. ## Instance properties _`SpeechSynthesisErrorEvent` extends the {{domxref("SpeechSynthesisEvent")}} interface, which inherits properties from its parent interface, {{domxref("Event")}}._ - {{domxref("SpeechSynthesisErrorEvent.error")}} {{ReadOnlyInline}} - : Returns an error code indicating what has gone wrong with a speech synthesis attempt. ## Instance methods _`SpeechSynthesisErrorEvent` extends the {{domxref("SpeechSynthesisEvent")}} interface, which inherits methods from its parent interface, {{domxref("Event")}}._ ## Examples ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); const voices = synth.getVoices(); // ... inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); for (let i = 0; i < voices.length; i++) { if (voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } synth.speak(utterThis); utterThis.onerror = (event) => { console.log( `An error has occurred with the speech synthesis: ${event.error}`, ); }; inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesiserrorevent
data/mdn-content/files/en-us/web/api/speechsynthesiserrorevent/error/index.md
--- title: "SpeechSynthesisErrorEvent: error property" short-title: error slug: Web/API/SpeechSynthesisErrorEvent/error page-type: web-api-instance-property browser-compat: api.SpeechSynthesisErrorEvent.error --- {{APIRef("Web Speech API")}} The **`error`** property of the {{domxref("SpeechSynthesisErrorEvent")}} interface returns an error code indicating what has gone wrong with a speech synthesis attempt. ## Value A string containing the error reason. Possible values are: - `canceled` - : A {{domxref("SpeechSynthesis.cancel")}} method call caused the {{domxref("SpeechSynthesisUtterance")}} to be removed from the queue before it had begun being spoken. - `interrupted` - : A {{domxref("SpeechSynthesis.cancel")}} method call caused the {{domxref("SpeechSynthesisUtterance")}} to be interrupted after it had begun being spoken and before it completed. - `audio-busy` - : The operation couldn't be completed at this time because the user-agent couldn't access the audio output device (for example, the user may need to correct this by closing another application.) - `audio-hardware` - : The operation couldn't be completed at this time because the user-agent couldn't identify an audio output device (for example, the user may need to connect a speaker or configure system settings.) - `network` - : The operation couldn't be completed at this time because some required network communication failed. - `synthesis-unavailable` - : The operation couldn't be completed at this time because no synthesis engine was available (For example, the user may need to install or configure a synthesis engine.) - `synthesis-failed` - : The operation failed because the synthesis engine raised an error. - `language-unavailable` - : No appropriate voice was available for the language set in {{domxref("SpeechSynthesisUtterance.lang")}}. You can use the [`window.speechSynthesis.getVoices()`](/en-US/docs/Web/API/SpeechSynthesis/getVoices) method to determine which voices and languages are supported in the user's browser. - `voice-unavailable` - : The voice set in {{domxref("SpeechSynthesisUtterance.voice")}} was not available. - `text-too-long` - : The contents of the {{domxref("SpeechSynthesisUtterance.text")}} attribute was too long to synthesize. - `invalid-argument` - : The content of the {{domxref("SpeechSynthesisUtterance.rate")}}, {{domxref("SpeechSynthesisUtterance.pitch")}} or {{domxref("SpeechSynthesisUtterance.volume")}} property was not valid. - `not-allowed` - : The operation's start was not allowed. ## Examples ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); const voices = synth.getVoices(); // ... inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); for (let i = 0; i < voices.length; i++) { if (voices[i].name === selectedOption) { utterThis.voice = voices[i]; } } synth.speak(utterThis); utterThis.onerror = (event) => { console.error( `An error has occurred with the speech synthesis: ${event.error}`, ); }; inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechsynthesiserrorevent
data/mdn-content/files/en-us/web/api/speechsynthesiserrorevent/speechsynthesiserrorevent/index.md
--- title: "SpeechSynthesisErrorEvent: SpeechSynthesisErrorEvent() constructor" short-title: SpeechSynthesisErrorEvent() slug: Web/API/SpeechSynthesisErrorEvent/SpeechSynthesisErrorEvent page-type: web-api-constructor browser-compat: api.SpeechSynthesisErrorEvent.SpeechSynthesisErrorEvent --- {{APIRef("Web Speech API")}} The **`SpeechSynthesisErrorEvent()`** constructor creates a new {{domxref("SpeechSynthesisErrorEvent")}} object. > **Note:** A web developer doesn't typically need to call this constructor, as the browser creates these objects itself when firing events. ## Syntax ```js-nolint new SpeechSynthesisErrorEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers set it to `error`. - `options` - : An object that, _in addition to the properties defined in {{domxref("SpeechSynthesisEvent/SpeechSynthesisEvent", "SpeechSynthesisEvent()")}}_, has the following properties: - `error` - : A string containing the error reason. Possible values are: - `canceled` - : A {{domxref("SpeechSynthesis.cancel")}} method call caused the {{domxref("SpeechSynthesisUtterance")}} to be removed from the queue before speech started. - `interrupted` - : A {{domxref("SpeechSynthesis.cancel")}} method call caused the {{domxref("SpeechSynthesisUtterance")}} to be interrupted after speech had started but before it completed. - `audio-busy` - : The operation couldn't be completed at this time because the user-agent couldn't access the audio output device (for example, the user may need to correct this by closing another application). - `audio-hardware` - : The operation couldn't be completed at this time because the user-agent couldn't identify an audio output device (for example, the user may need to connect a speaker or configure system settings.) - `network` - : The operation couldn't be completed at this time because some required network communication failed. - `synthesis-unavailable` - : The operation couldn't be completed at this time because no synthesis engine was available (for example, the user may need to install or configure a synthesis engine). - `synthesis-failed` - : The operation failed because the synthesis engine raised an error. - `language-unavailable` - : No appropriate voice was available for the language set in {{domxref("SpeechSynthesisUtterance.lang")}}. You can use the [`window.speechSynthesis.getVoices()`](/en-US/docs/Web/API/SpeechSynthesis/getVoices) method to determine which voices and languages are supported in the user's browser. - `voice-unavailable` - : The voice set in {{domxref("SpeechSynthesisUtterance.voice")}} was not available. - `text-too-long` - : The contents of the {{domxref("SpeechSynthesisUtterance.text")}} attribute was too long to synthesize. - `invalid-argument` - : The content of the {{domxref("SpeechSynthesisUtterance.rate")}}, {{domxref("SpeechSynthesisUtterance.pitch")}} or {{domxref("SpeechSynthesisUtterance.volume")}} property was not valid. - `not-allowed` - : The operation's start was not allowed. ### Return value A new {{domxref("SpeechSynthesisErrorEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("SpeechSynthesisEvent")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/geolocation/index.md
--- title: Geolocation slug: Web/API/Geolocation page-type: web-api-interface browser-compat: api.Geolocation --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`Geolocation`** interface represents an object able to obtain the position of the device programmatically. It gives Web content access to the location of the device. This allows a website or app to offer customized results based on the user's location. An object with this interface is obtained using the {{domxref("navigator.geolocation")}} property implemented by the {{domxref("Navigator")}} object. > **Note:** For security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. Be aware that each browser has its own policies and methods for requesting this permission. ## Instance properties _The `Geolocation` interface neither implements, nor inherits any property._ ## Instance methods _The `Geolocation` interface doesn't inherit any method._ - {{domxref("Geolocation.getCurrentPosition()")}} - : Determines the device's current location and gives back a {{domxref("GeolocationPosition")}} object with the data. - {{domxref("Geolocation.watchPosition()")}} - : Returns a `long` value representing the newly established callback function to be invoked whenever the device location changes. - {{domxref("Geolocation.clearWatch()")}} - : Removes the particular handler previously installed using `watchPosition()`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using geolocation](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API)
0
data/mdn-content/files/en-us/web/api/geolocation
data/mdn-content/files/en-us/web/api/geolocation/watchposition/index.md
--- title: "Geolocation: watchPosition() method" short-title: watchPosition() slug: Web/API/Geolocation/watchPosition page-type: web-api-instance-method browser-compat: api.Geolocation.watchPosition --- {{securecontext_header}}{{ APIref("Geolocation API") }} The **`watchPosition()`** method of the {{domxref("Geolocation")}} interface is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function. ## Syntax ```js-nolint watchPosition(success) watchPosition(success, error) watchPosition(success, error, options) ``` ### Parameters - `success` - : A callback function that takes a {{domxref("GeolocationPosition")}} object as an input parameter. - `error` {{optional_inline}} - : An optional callback function that takes a {{domxref("GeolocationPositionError")}} object as an input parameter. - `options` {{optional_inline}} - : An optional object that provides configuration options for the location watch. See {{domxref("Geolocation.getCurrentPosition()")}} for more details on possible options. ### Return value An integer ID that identifies the registered handler. The ID can be passed to the {{domxref("Geolocation.clearWatch()")}} to unregister the handler. ## Examples ```js let id; let target; let options; function success(pos) { const crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log("Congratulations, you reached the target"); navigator.geolocation.clearWatch(id); } } function error(err) { console.error(`ERROR(${err.code}): ${err.message}`); } target = { latitude: 0, longitude: 0, }; options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0, }; id = navigator.geolocation.watchPosition(success, error, options); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Geolocation API](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - The interface it belongs to, {{domxref("Geolocation")}}, and the way to access it β€” {{domxref("Navigator.geolocation")}}. - The opposite operation: {{domxref("Geolocation.clearWatch()")}} - A similar method: {{domxref("Geolocation.getCurrentPosition()")}}
0
data/mdn-content/files/en-us/web/api/geolocation
data/mdn-content/files/en-us/web/api/geolocation/getcurrentposition/index.md
--- title: "Geolocation: getCurrentPosition() method" short-title: getCurrentPosition() slug: Web/API/Geolocation/getCurrentPosition page-type: web-api-instance-method browser-compat: api.Geolocation.getCurrentPosition --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`getCurrentPosition()`** method of the {{domxref("Geolocation")}} interface is used to get the current position of the device. ## Syntax ```js-nolint getCurrentPosition(success) getCurrentPosition(success, error) getCurrentPosition(success, error, options) ``` ### Parameters - `success` - : A callback function that takes a {{domxref("GeolocationPosition")}} object as its sole input parameter. - `error` {{optional_inline}} - : An optional callback function that takes a {{domxref("GeolocationPositionError")}} object as its sole input parameter. - `options` {{optional_inline}} - : An optional object including the following parameters: - `maximumAge` {{optional_inline}} - : A positive `long` value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to `0`, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to {{jsxref("Infinity")}} the device must return a cached position regardless of its age. Default: `0`. - `timeout` {{optional_inline}} - : A positive `long` value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. The default value is {{jsxref("Infinity")}}, meaning that `getCurrentPosition()` won't return until the position is available. - `enableHighAccuracy` {{optional_inline}} - : A boolean value that indicates the application would like to receive the best possible results. If `true` and if the device is able to provide a more accurate position, it will do so. Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example). On the other hand, if `false`, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: `false`. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0, }; function success(pos) { const crd = pos.coords; console.log("Your current position is:"); console.log(`Latitude : ${crd.latitude}`); console.log(`Longitude: ${crd.longitude}`); console.log(`More or less ${crd.accuracy} meters.`); } function error(err) { console.warn(`ERROR(${err.code}): ${err.message}`); } navigator.geolocation.getCurrentPosition(success, error, options); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Geolocation API](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - {{domxref("Navigator.geolocation")}}
0
data/mdn-content/files/en-us/web/api/geolocation
data/mdn-content/files/en-us/web/api/geolocation/clearwatch/index.md
--- title: "Geolocation: clearWatch() method" short-title: clearWatch() slug: Web/API/Geolocation/clearWatch page-type: web-api-instance-method browser-compat: api.Geolocation.clearWatch --- {{securecontext_header}}{{ APIref("Geolocation API") }} The **`clearWatch()`** method of the {{domxref("Geolocation")}} interface is used to unregister location/error monitoring handlers previously installed using {{domxref("Geolocation.watchPosition()")}}. ## Syntax ```js-nolint clearWatch(id) ``` ### Parameters - `id` - : The ID number returned by the {{domxref("Geolocation.watchPosition()")}} method when installing the handler you wish to remove. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js let id; let target; let options; function success(pos) { const crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log("Congratulations, you've reached the target!"); navigator.geolocation.clearWatch(id); } } function error(err) { console.error(`ERROR(${err.code}): ${err.message}`); } target = { latitude: 0, longitude: 0, }; options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0, }; id = navigator.geolocation.watchPosition(success, error, options); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using geolocation](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - {{domxref("Geolocation")}} - {{domxref("Geolocation.watchPosition()")}} - {{domxref("Geolocation.getCurrentPosition()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/lock/index.md
--- title: Lock slug: Web/API/Lock page-type: web-api-interface browser-compat: api.Lock --- {{APIRef("Web Locks API")}}{{securecontext_header}} The **`Lock`** interface of the [Web Locks API](/en-US/docs/Web/API/Web_Locks_API) provides the name and mode of a lock. This may be a newly requested lock that is received in the callback to {{domxref('LockManager.request','LockManager.request()')}}, or a record of an active or queued lock returned by {{domxref('LockManager.query()')}}. {{AvailableInWorkers}} ## Instance properties - {{domxref('Lock.mode')}} {{ReadOnlyInline}} - : Returns the access mode passed to {{domxref('LockManager.request()')}} when the lock was requested. The mode is either `"exclusive"` (the default) or `"shared"`. - {{domxref('Lock.name')}} {{ReadOnlyInline}} - : Returns the name passed to {{domxref('LockManager.request()')}} when the lock was requested. ## Examples The following examples show how the mode and name properties are passed in the call to {{domxref('LockManager.request()')}}. {{domxref('LockManager')}} is the object returned by {{domxref('navigator.locks')}}. ```js navigator.locks.request("net_db_sync", show_lock_properties); navigator.locks.request( "another_lock", { mode: "shared" }, show_lock_properties, ); function show_lock_properties(lock) { console.log(`The lock name is: ${lock.name}`); console.log(`The lock mode is: ${lock.mode}`); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/lock
data/mdn-content/files/en-us/web/api/lock/name/index.md
--- title: "Lock: name property" short-title: name slug: Web/API/Lock/name page-type: web-api-instance-property browser-compat: api.Lock.name --- {{APIRef("Web Locks API")}}{{securecontext_header}} The **`name`** read-only property of the {{domxref("Lock")}} interface returns the _name_ passed to {{domxref('LockManager.request')}} selected when the lock was requested. The name of a lock is passed by script when the lock is requested. The name is selected by the developer to represent an abstract resource for which use is being coordinated across multiple tabs, workers, or other code within the origin. For example, if only one tab of a web application should be synchronizing network resources with an offline database, it could use a lock name such as `"net_db_sync"`. {{AvailableInWorkers}} ## Value A string. ## Examples The following examples show how the name property passed in the call to {{domxref('LockManager.request()')}}. {{domxref('LockManager')}} is the object returned by {{domxref('navigator.locks')}}. ```js navigator.locks.request("net_db_sync", show_lock_properties); function show_lock_properties(lock) { console.log(`The lock name is: ${lock.name}`); console.log(`The lock mode is: ${lock.mode}`); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/lock
data/mdn-content/files/en-us/web/api/lock/mode/index.md
--- title: "Lock: mode property" short-title: mode slug: Web/API/Lock/mode page-type: web-api-instance-property browser-compat: api.Lock.mode --- {{APIRef("Web Locks API")}}{{securecontext_header}} The **`mode`** read-only property of the {{domxref("Lock")}} interface returns the access mode passed to {{domxref('LockManager.request()')}} when the lock was requested. The mode is either `"exclusive"` (the default) or `"shared"`. {{AvailableInWorkers}} ## Value One of `"exclusive"` or `"shared"`. ## Examples The following examples show how the mode property is passed in the call to {{domxref('LockManager.request()')}}. {{domxref('LockManager')}} is the object returned by {{domxref('navigator.locks')}}. ```js // Should show "exclusive" (the default) navigator.locks.request("my_resource", show_lock_properties); // Should show "exclusive" navigator.locks.request( "my_resource", { mode: "exclusive" }, show_lock_properties, ); // Should show "shared" navigator.locks.request( "my_resource", { mode: "shared" }, show_lock_properties, ); function show_lock_properties(lock) { console.log(`The lock name is: ${lock.name}`); console.log(`The lock mode is: ${lock.mode}`); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfefuncrelement/index.md
--- title: SVGFEFuncRElement slug: Web/API/SVGFEFuncRElement page-type: web-api-interface browser-compat: api.SVGFEFuncRElement --- {{APIRef("SVG")}} The **`SVGFEFuncRElement`** interface corresponds to the {{SVGElement("feFuncR")}} element. {{InheritanceDiagram}} ## Instance properties _This interface not provide any specific properties, but inherits properties from its parent interface, {{domxref("SVGComponentTransferFunctionElement")}}._ ## Instance methods _This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGComponentTransferFunctionElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("feFuncR")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/presentationrequest/index.md
--- title: PresentationRequest slug: Web/API/PresentationRequest page-type: web-api-interface status: - experimental browser-compat: api.PresentationRequest --- {{SeeCompatTable}}{{securecontext_header}}{{APIRef("Presentation API")}} A `PresentationRequest` object is used to initiate or reconnect to a presentation made by a [controlling browsing context](https://www.w3.org/TR/presentation-api/#dfn-controlling-browsing-context). The `PresentationRequest` object _MUST_ be implemented in a [controlling browsing context](https://www.w3.org/TR/presentation-api/#dfn-controlling-browsing-context) provided by a [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent). When a `PresentationRequest` is constructed, the given `urls` _MUST_ be used as the list of _presentation request URLs_ which are each a possible [presentation URL](https://www.w3.org/TR/presentation-api/#dfn-presentation-url) for the `PresentationRequest` instance. {{InheritanceDiagram}} ## Constructor - {{domxref("PresentationRequest.PresentationRequest","PresentationRequest()")}} {{Experimental_Inline}} - : Creates a `PresentationRequest`. ## Instance properties None ## Instance methods - {{domxref("PresentationRequest.start()")}} {{Experimental_Inline}} - : Returns a {{JSxRef("Promise")}} that resolves with a {{DOMxRef("PresentationConnection")}} after the user agent prompts the user to select a display and grant permission to use that display. - {{domxref("PresentationRequest.reconnect()")}} {{Experimental_Inline}} - : When the `reconnect(presentationId)` method is called on a `PresentationRequest` _presentationRequest_, the [user agent](https://www.w3.org/TR/presentation-api/#dfn-user-agents) _MUST_ run the following steps to _reconnect to a presentation_. - {{domxref("PresentationRequest.getAvailability()")}} {{Experimental_Inline}} - : When the `getAvailability()` method is called, the user agent _MUST_ run the steps as the link. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/presentationrequest
data/mdn-content/files/en-us/web/api/presentationrequest/start/index.md
--- title: "PresentationRequest: start() method" short-title: start() slug: Web/API/PresentationRequest/start page-type: web-api-instance-method status: - experimental browser-compat: api.PresentationRequest.start --- {{DefaultAPISidebar("Presentation API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`start()`** property of the {{domxref("PresentationRequest")}} interface returns a {{jsxref("Promise")}} that resolves with a {{domxref("PresentationConnection")}} after the user agent prompts the user to select a display and grant permission to use that display. ## Syntax ```js-nolint start() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with a {{domxref("PresentationConnection")}}. ## Security [Transient user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/presentationrequest
data/mdn-content/files/en-us/web/api/presentationrequest/getavailability/index.md
--- title: "PresentationRequest: getAvailability() method" short-title: getAvailability() slug: Web/API/PresentationRequest/getAvailability page-type: web-api-instance-method status: - experimental browser-compat: api.PresentationRequest.getAvailability --- {{APIRef("Presentation API")}}{{SeeCompatTable}}{{SecureContext_Header}} When the `getAvailability()` method is called, the user agent _MUST_ run the following steps: - Input - : _presentationUrls_, a list of [presentation request URLs](https://www.w3.org/TR/presentation-api/#dfn-presentation-request-urls) - Output - : _P_, a [Promise](https://www.w3.org/TR/presentation-api/#dfn-promise) 1. If one of the following conditions is true: - The result of running the [prohibits mixed security contexts algorithm](https://www.w3.org/TR/presentation-api/#dfn-prohibits-mixed-security-contexts-algorithm) on the document's [settings object](https://www.w3.org/TR/presentation-api/#dfn-settings-object) is `"Prohibits Mixed Security Contexts"` and _presentationUrl_ is an [a priori unauthenticated URL](https://www.w3.org/TR/presentation-api/#dfn-a-priori-unauthenticated-url). - The document object's [active sandboxing flag set](https://www.w3.org/TR/presentation-api/#dfn-active-sandboxing-flag-set) has the [sandboxed presentation browsing context flag](https://www.w3.org/TR/presentation-api/#sandboxed-presentation-browsing-context-flag) set. Run the following substeps: 1. Return a [Promise](https://www.w3.org/TR/presentation-api/#dfn-promise) rejected with a `SecurityError` {{domxref("DOMException")}}. 2. Abort these steps. 2. Let _P_ be a new [Promise](https://www.w3.org/TR/presentation-api/#dfn-promise). 3. Return _P_, but continue running these steps [in parallel](https://www.w3.org/TR/presentation-api/#dfn-in-parallel). 4. If the user agent is unable to [monitor the list of available presentation displays](https://www.w3.org/TR/presentation-api/#dfn-monitor-the-list-of-available-presentation-displays) for the entire duration of the [controlling browsing context](https://www.w3.org/TR/presentation-api/#dfn-controlling-browsing-context) (e.g., because the user has disabled this feature), then: 1. [Resolve](https://www.w3.org/TR/presentation-api/#dfn-resolving-a-promise) _P_ with a new `PresentationAvailability` object with its `value` property set to `false`. 2. Abort all the remaining steps. 5. If the user agent is unable to continuously [monitor the list of available presentation displays](https://www.w3.org/TR/presentation-api/#dfn-monitor-the-list-of-available-presentation-displays) but can find presentation displays in order to start a connection, then: 1. [Reject](https://www.w3.org/TR/presentation-api/#dfn-rejecting-a-promise) _P_ with a `NotSupportedError` {{domxref("DOMException")}}. 2. Abort all the remaining steps. 6. If there exists a tuple (_A_, _presentationUrls_) in the [set of availability objects](https://www.w3.org/TR/presentation-api/#dfn-set-of-availability-objects), then: 1. [Resolve](https://www.w3.org/TR/presentation-api/#dfn-resolving-a-promise) _P_ with _A_. 2. Abort all the remaining steps. 7. Let _A_ be a new `PresentationAvailability` object with its `value` property set as follows: 1. `false` if the [list of available presentation displays](https://www.w3.org/TR/presentation-api/#dfn-list-of-available-presentation-displays) is empty. 2. `true` if there is at least one [compatible presentation display](https://www.w3.org/TR/presentation-api/#dfn-compatible-presentation-display) for some member of _presentationUrls_. Meaning there is an entry _(presentationUrl, display)_ in the [list of available presentation displays](https://www.w3.org/TR/presentation-api/#dfn-list-of-available-presentation-displays) for some _presentationUrl_ in _presentationUrls_. 3. `false` otherwise. 8. Create a tuple (_A_, _presentationUrls_) and add it to the [set of availability objects](https://www.w3.org/TR/presentation-api/#dfn-set-of-availability-objects). 9. Run the algorithm to [monitor the list of available presentation displays](https://www.w3.org/TR/presentation-api/#dfn-monitor-the-list-of-available-presentation-displays). 10. [Resolve](https://www.w3.org/TR/presentation-api/#dfn-resolving-a-promise) _P_ with _A_. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/presentationrequest
data/mdn-content/files/en-us/web/api/presentationrequest/reconnect/index.md
--- title: "PresentationRequest: reconnect() method" short-title: reconnect() slug: Web/API/PresentationRequest/reconnect page-type: web-api-instance-method status: - experimental browser-compat: api.PresentationRequest.reconnect --- {{APIRef("Presentation API")}}{{SeeCompatTable}}{{SecureContext_Header}} When the `reconnect(presentationId)` method is called on a `PresentationRequest` _presentationRequest_, the [user agent](https://www.w3.org/TR/presentation-api/#dfn-user-agents) _MUST_ run the following steps to _reconnect to a presentation_: ## Input - _presentationRequest_, the [`PresentationRequest`](https://www.w3.org/TR/presentation-api/#idl-def-presentationrequest) object that [`reconnect()`](https://www.w3.org/TR/presentation-api/#dom-presentationrequest-reconnect) was called on. - _presentationId_, a valid [presentation identifier](https://www.w3.org/TR/presentation-api/#dfn-presentation-identifier) ## Output _P_, a [Promise](https://www.w3.org/TR/presentation-api/#dfn-promise). ## Algorithm 1. Using the document's [settings object](https://www.w3.org/TR/presentation-api/#dfn-settings-object) run the [prohibits mixed security contexts algorithm](https://www.w3.org/TR/presentation-api/#dfn-prohibits-mixed-security-contexts-algorithm). 2. If the result of the algorithm is `"Prohibits Mixed Security Contexts"` and the [presentation request URL](https://www.w3.org/TR/presentation-api/#dfn-presentation-request-urls) of _presentationRequest_ is an [a priori unauthenticated URL](https://www.w3.org/TR/presentation-api/#dfn-a-priori-unauthenticated-url), then return a [Promise](https://www.w3.org/TR/presentation-api/#dfn-promise) rejected with a [`SecurityError`](https://www.w3.org/TR/presentation-api/#dfn-securityerror) and abort these steps. 3. If the document object's [active sandboxing flag set](https://www.w3.org/TR/presentation-api/#dfn-active-sandboxing-flag-set) has the [sandboxed presentation browsing context flag](https://www.w3.org/TR/presentation-api/#sandboxed-presentation-browsing-context-flag) set, then return a [Promise](https://www.w3.org/TR/presentation-api/#dfn-promise) rejected with a [`SecurityError`](https://www.w3.org/TR/presentation-api/#dfn-securityerror) and abort these steps. 4. Let _P_ be a new [Promise](https://www.w3.org/TR/presentation-api/#dfn-promise). 5. Return _P_ but continue running these steps in parallel. 6. Search the [set of controlled presentations](https://www.w3.org/TR/presentation-api/#dfn-set-of-controlled-presentations) for a [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection) that meets the following criteria: its [controlling browsing context](https://www.w3.org/TR/presentation-api/#dfn-controlling-browsing-context) is the current [browsing context](https://www.w3.org/TR/presentation-api/#dfn-browsing-context), its [presentation connection state](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection-state) is not [`terminated`](https://www.w3.org/TR/presentation-api/#dom-presentationconnectionstate-terminated), its [presentation URL](https://www.w3.org/TR/presentation-api/#dfn-presentation-url) is equal to one of the [presentation request URLs](https://www.w3.org/TR/presentation-api/#dfn-presentation-request-urls) of _presentationRequest_ and its [presentation identifier](https://www.w3.org/TR/presentation-api/#dfn-presentation-identifier) is equal to _presentationId_. 7. If such a [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection) exists, run the following steps: 1. Let _S_ be that [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection). 2. [Resolve](https://www.w3.org/TR/presentation-api/#dfn-resolving-a-promise) _P_ with _S_. 3. If the [presentation connection state](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection-state) of _S_ is [`connecting`](https://www.w3.org/TR/presentation-api/#dom-presentationconnectionstate-connecting) or [`connected`](https://www.w3.org/TR/presentation-api/#dom-presentationconnectionstate-connected), then abort all remaining steps. 4. Set the [presentation connection state](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection-state) of _S_ to [`connecting`](https://www.w3.org/TR/presentation-api/#dom-presentationconnectionstate-connecting). 5. [Establish a presentation connection](https://www.w3.org/TR/presentation-api/#dfn-establish-a-presentation-connection) with _S_. 6. Abort all remaining steps. 8. Search the [set of controlled presentations](https://www.w3.org/TR/presentation-api/#dfn-set-of-controlled-presentations) for the first [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection) that meets the following criteria: its [presentation connection state](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection-state) is not [`terminated`](https://www.w3.org/TR/presentation-api/#dom-presentationconnectionstate-terminated), its [presentation URL](https://www.w3.org/TR/presentation-api/#dfn-presentation-url) is equal to one of the [presentation request URLs](https://www.w3.org/TR/presentation-api/#dfn-presentation-request-urls) of _presentationRequest_, and its [presentation identifier](https://www.w3.org/TR/presentation-api/#dfn-presentation-identifier) is equal to _presentationId_. 9. If such a [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection) exists, let _E_ be that [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection), and run the following steps: 1. Create a new [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection) _S_. 2. Set the [presentation identifier](https://www.w3.org/TR/presentation-api/#dfn-presentation-identifier) of _S_ to _presentationId_. 3. Set the [presentation URL](https://www.w3.org/TR/presentation-api/#dfn-presentation-url) of _S_ to the [presentation URL](https://www.w3.org/TR/presentation-api/#dfn-presentation-url) of _E_. 4. Set the [presentation connection state](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection-state) of _S_ to [`connecting`](https://www.w3.org/TR/presentation-api/#dom-presentationconnectionstate-connecting). 5. Add _S_ to the [set of controlled presentations](https://www.w3.org/TR/presentation-api/#dfn-set-of-controlled-presentations). 6. [Resolve](https://www.w3.org/TR/presentation-api/#dfn-resolving-a-promise) _P_ with _S_. 7. [Queue a task](https://www.w3.org/TR/presentation-api/#dfn-queue-a-task) to [fire](https://www.w3.org/TR/presentation-api/#dfn-firing-an-event) a [trusted event](https://www.w3.org/TR/presentation-api/#dfn-trusted-event) with the name [`connectionavailable`](https://www.w3.org/TR/presentation-api/#dfn-connectionavailable), that uses the [`PresentationConnectionAvailableEvent`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnectionavailableevent) interface with the [`connection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnectionavailableevent-connection) attribute initialized to _S_, at _presentationRequest_. The event must not bubble and cancelable and should have no default action. 8. [Establish a presentation connection](https://www.w3.org/TR/presentation-api/#dfn-establish-a-presentation-connection) with _S_. 9. Abort all remaining steps. 10. [Reject](https://www.w3.org/TR/presentation-api/#dfn-rejecting-a-promise) _P_ with a [`NotFoundError`](https://www.w3.org/TR/presentation-api/#dfn-notfounderror) exception. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/presentationrequest
data/mdn-content/files/en-us/web/api/presentationrequest/presentationrequest/index.md
--- title: "PresentationRequest: PresentationRequest() constructor" short-title: PresentationRequest() slug: Web/API/PresentationRequest/PresentationRequest page-type: web-api-constructor status: - experimental browser-compat: api.PresentationRequest.PresentationRequest --- {{APIRef("Presentation API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`PresentationRequest()`** constructor creates a new {{domxref("PresentationRequest")}} object which creates a new PresentationRequest. ## Syntax ```js-nolint new PresentationRequest(url) new PresentationRequest(urls) ``` ### Parameters - `url` or `urls\[]` - : A URL or array of URLs that are possible URLs used to create, or reconnect, a presentation for the PresentationRequest instance. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/videodecoder/index.md
--- title: VideoDecoder slug: Web/API/VideoDecoder page-type: web-api-interface browser-compat: api.VideoDecoder --- {{securecontext_header}}{{APIRef("WebCodecs API")}} The **`VideoDecoder`** interface of the {{domxref('WebCodecs API','','','true')}} decodes chunks of video. {{InheritanceDiagram}} ## Constructor - {{domxref("VideoDecoder.VideoDecoder", "VideoDecoder()")}} - : Creates a new `VideoDecoder` object. ## Instance properties _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("VideoDecoder.decodeQueueSize")}} {{ReadOnlyInline}} - : An integer representing the number of queued decode requests. - {{domxref("VideoDecoder.state")}} {{ReadOnlyInline}} - : Indicates the current state of decoder. Possible values are: - `"unconfigured"` - `"configured"` - `"closed"` ### Events - {{domxref("VideoDecoder.dequeue_event", "dequeue")}} - : Fires to signal a decrease in {{domxref("VideoDecoder.decodeQueueSize")}}. ## Static methods - {{domxref("VideoDecoder.isConfigSupported_static", "VideoDecoder.isConfigSupported()")}} - : Returns a promise indicating whether the provided `VideoDecoderConfig` is supported. ## Instance methods _Inherits methods from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("VideoDecoder.configure()")}} - : Enqueues a control message to configure the video decoder for decoding chunks. - {{domxref("VideoDecoder.decode()")}} - : Enqueues a control message to decode a given chunk of video. - {{domxref("VideoDecoder.flush()")}} - : Returns a promise that resolves once all pending messages in the queue have been completed. - {{domxref("VideoDecoder.reset()")}} - : Resets all states including configuration, control messages in the control message queue, and all pending callbacks. - {{domxref("VideoDecoder.close()")}} - : Ends all pending work and releases system resources. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Video processing with WebCodecs](https://developer.chrome.com/docs/web-platform/best-practices/webcodecs) - [WebCodecs API Samples](https://w3c.github.io/webcodecs/samples/)
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/configure/index.md
--- title: "VideoDecoder: configure() method" short-title: configure() slug: Web/API/VideoDecoder/configure page-type: web-api-instance-method browser-compat: api.VideoDecoder.configure --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`configure()`** method of the {{domxref("VideoDecoder")}} interface enqueues a control message to configure the video decoder for decoding chunks. ## Syntax ```js-nolint configure(config) ``` ### Parameters - `config` - : An object containing the following members: - `codec` - : A string containing a [valid codec string](https://www.w3.org/TR/webcodecs-codec-registry/#video-codec-registry). See ["codecs" parameter](/en-US/docs/Web/Media/Formats/codecs_parameter#codec_options_by_container) for details on codec string construction. - `description` {{optional_inline}} - : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}} containing a sequence of codec specific bytes, commonly known as extradata. - `codedWidth` {{optional_inline}} - : An integer representing the width of the {{domxref("VideoFrame")}} in pixels, including any non-visible padding, before any ratio adjustments. - `codedHeight` {{optional_inline}} - : An integer representing the height of the {{domxref("VideoFrame")}} in pixels, including any non-visible padding, before any ratio adjustments. - `displayAspectWidth` {{optional_inline}} - : An integer representing the horizontal dimension of the {{domxref("VideoFrame")}} in pixels when displayed. - `displayAspectHeight` {{optional_inline}} - : An integer representing the vertical dimension of the {{domxref("VideoFrame")}} in pixels when displayed. - `colorSpace` - : An object representing a {{domxref("VideoColorSpace")}}, containing the following members: - `primaries` - : A string representing the color {{glossary("gamut")}} of the video sample. One of: - `"bt709"` - `"bt470bg"` - `"smpte170m"` - `transfer` - : A string representing transfer characteristics. One of: - `"bt709"` - `"smpte170m"` - `"iec61966-2-1"` - `matrix` - : A string representing a matrix coefficient. One of: - `"rgb"` - `"bt709"` - `"bt470bg"` - `"smpte170m"` - `hardwareAcceleration` - : A hint as to the hardware acceleration method to use. One of: - `"no-preference"` - `"prefer-hardware"` - `"prefer-software"` - `optimizeForLatency` - : A boolean. If `true` this is a hint that the selected decoder should be optimized to minimize the number of {{domxref("EncodedVideoChunk")}} objects that have to be decoded before a {{domxref("VideoFrame")}} is output. > **Note:** The registrations in the [WebCodecs Codec Registry](https://www.w3.org/TR/webcodecs-codec-registry/#audio-codec-registry) link to a specification detailing whether and how to populate the optional `description` member. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the provided `config` is invalid. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("VideoDecoder.state","state")}} is `"closed"`. - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the provided `config` is valid but the user agent cannot provide a codec that can decode this profile. ## Examples The following example creates a new {{domxref("VideoDecoder")}} and configures it with the `"vp8"` codec, a `codedWidth` of 640 pixels and a `codedHeight` of 480 pixels. ```js const init = { output: handleFrame, error: (e) => { console.log(e.message); }, }; const config = { codec: "vp8", codedWidth: 640, codedHeight: 480, }; let decoder = new VideoDecoder(init); decoder.configure(config); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/decodequeuesize/index.md
--- title: "VideoDecoder: decodeQueueSize property" short-title: decodeQueueSize slug: Web/API/VideoDecoder/decodeQueueSize page-type: web-api-instance-property browser-compat: api.VideoDecoder.decodeQueueSize --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`decodeQueueSize`** read-only property of the {{domxref("VideoDecoder")}} interface returns the number of pending decode requests in the queue. ## Value An integer containing the number of requests. ## Examples The following example prints the size of the queue to the console. ```js console.log(VideoDecoder.decodeQueueSize); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/dequeue_event/index.md
--- title: "VideoDecoder: dequeue event" short-title: dequeue slug: Web/API/VideoDecoder/dequeue_event page-type: web-api-event browser-compat: api.VideoDecoder.dequeue_event --- {{securecontext_header}}{{APIRef("WebCodecs API")}} The **`dequeue`** event of the {{domxref("VideoDecoder")}} interface fires to signal a decrease in {{domxref("VideoDecoder.decodeQueueSize")}}. This eliminates the need for developers to use a {{domxref("setTimeout()")}} poll to determine when the queue has decreased, and more work should be queued up. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("dequeue", (event) => {}); ondequeue = (event) => {}; ``` ## Example ```js videoDecoder.addEventListener("dequeue", (event) => { // Queue up more encoding work }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/flush/index.md
--- title: "VideoDecoder: flush() method" short-title: flush() slug: Web/API/VideoDecoder/flush page-type: web-api-instance-method browser-compat: api.VideoDecoder.flush --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`flush()`** method of the {{domxref("VideoDecoder")}} interface returns a Promise that resolves once all pending messages in the queue have been completed. ## Syntax ```js-nolint flush() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with undefined. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Returned if the Promise is rejected because the {{domxref("VideoDecoder.state","state")}} is not `configured`. ## Examples The following example flushes the `VideoDecoder`. ```js VideoDecoder.flush(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/decode/index.md
--- title: "VideoDecoder: decode() method" short-title: decode() slug: Web/API/VideoDecoder/decode page-type: web-api-instance-method browser-compat: api.VideoDecoder.decode --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`decode()`** method of the {{domxref("VideoDecoder")}} interface enqueues a control message to decode a given chunk of video. ## Syntax ```js-nolint decode(chunk) ``` ### Parameters - `chunk` - : An {{domxref("EncodedVideoChunk")}} object representing a chunk of encoded video. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("VideoDecoder.state","state")}} is not `configured`. - `DataError` {{domxref("DOMException")}} - : Thrown if the `chunk` is unable to be decoded due to relying on other frames for decoding. ## Examples The following example demonstrates how to use the `decode()` method to decode {{domxref("EncodedVideoChunk")}} objects created from encoded video data. ```js const responses = await downloadVideoChunksFromServer(timestamp); for (const response of responses) { const chunk = new EncodedVideoChunk({ timestamp: response.timestamp, type: response.key ? "key" : "delta", data: new Uint8Array(response.body), }); decoder.decode(chunk); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/isconfigsupported_static/index.md
--- title: "VideoDecoder: isConfigSupported() static method" short-title: isConfigSupported() slug: Web/API/VideoDecoder/isConfigSupported_static page-type: web-api-static-method browser-compat: api.VideoDecoder.isConfigSupported_static --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`isConfigSupported()`** static method of the {{domxref("VideoDecoder")}} interface checks if the given config is supported (that is, if {{domxref("VideoDecoder")}} objects can be successfully configured with the given config). ## Syntax ```js-nolint VideoDecoder.isConfigSupported(config) ``` ### Parameters - `config` - : The dictionary object accepted by {{domxref("VideoDecoder.configure")}} ### Return value A {{jsxref("Promise")}} that resolves with an object containing the following members: - `supported` - : A boolean value which is `true` if the given config is supported by the decoder. - `config` - : A copy of the given config with all the fields recognized by the decoder. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the provided `config` is invalid; that is, if doesn't have required values (such as an empty `codec` field) or has invalid values (such as a negative `codedWidth`). ## Examples The following example tests if the browser supports accelerated and un-accelerated versions of several video codecs. ```js const codecs = ["avc1.42001E", "vp8", "vp09.00.10.08", "av01.0.04M.08"]; const accelerations = ["prefer-hardware", "prefer-software"]; const configs = []; for (const codec of codecs) { for (const acceleration of accelerations) { configs.push({ codec, hardwareAcceleration: acceleration, codedWidth: 1280, codedHeight: 720, not_supported_field: 123, }); } } for (const config of configs) { const support = await VideoDecoder.isConfigSupported(config); console.log( `VideoDecoder's config ${JSON.stringify(support.config)} support: ${ support.supported }`, ); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/state/index.md
--- title: "VideoDecoder: state property" short-title: state slug: Web/API/VideoDecoder/state page-type: web-api-instance-property browser-compat: api.VideoDecoder.state --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`state`** property of the {{domxref("VideoDecoder")}} interface returns the current state of the underlying codec. ## Value A string containing one of the following values: - `"unconfigured"` - : The codec is not configured for decoding. - `"configured"` - : The codec has a valid configuration and is ready. - `"closed"` - : The codec is no longer usable and system resources have been released. ## Examples The following example prints the state of the `VideoDecoder` to the console. ```js console.log(VideoDecoder.state); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/reset/index.md
--- title: "VideoDecoder: reset() method" short-title: reset() slug: Web/API/VideoDecoder/reset page-type: web-api-instance-method browser-compat: api.VideoDecoder.reset --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`reset()`** method of the {{domxref("VideoDecoder")}} interface resets all states including configuration, control messages in the control message queue, and all pending callbacks. ## Syntax ```js-nolint reset() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example resets the `VideoDecoder`. ```js VideoDecoder.reset(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/videodecoder/index.md
--- title: "VideoDecoder: VideoDecoder() constructor" short-title: VideoDecoder() slug: Web/API/VideoDecoder/VideoDecoder page-type: web-api-constructor browser-compat: api.VideoDecoder.VideoDecoder --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`VideoDecoder()`** constructor creates a new {{domxref("VideoDecoder")}} object with the provided `init.output` callback assigned as the output callback, the provided `init.error` callback as the error callback, and the {{domxref("VideoDecoder.state")}} set to `"unconfigured"`. ## Syntax ```js-nolint new VideoDecoder(options) ``` ### Parameters - `options` - : An object containing two callbacks. - `output` - : A callback which takes a {{domxref("VideoFrame")}} object as its only argument. - `error` - : A callback which takes an {{jsxref("Error")}} object as its only argument. ## Examples In the following example a `VideoDecoder` is created with the two required callback functions, one to deal with the decoded frame and the other to handle errors. ```js const videoDecoder = new VideoDecoder({ output: processVideo, error: onEncoderError, }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/videodecoder
data/mdn-content/files/en-us/web/api/videodecoder/close/index.md
--- title: "VideoDecoder: close() method" short-title: close() slug: Web/API/VideoDecoder/close page-type: web-api-instance-method browser-compat: api.VideoDecoder.close --- {{APIRef("WebCodecs API")}}{{SecureContext_Header}} The **`close()`** method of the {{domxref("VideoDecoder")}} interface ends all pending work and releases system resources. ## Syntax ```js-nolint close() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example closes the `VideoDecoder`. ```js VideoDecoder.close(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/animation/index.md
--- title: Animation slug: Web/API/Animation page-type: web-api-interface browser-compat: api.Animation --- {{ APIRef("Web Animations") }} The **`Animation`** interface of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) represents a single animation player and provides playback controls and a timeline for an animation node or source. {{InheritanceDiagram}} ## Constructor - {{domxref("Animation.Animation()", "Animation()")}} - : Creates a new `Animation` object instance. ## Instance properties - {{domxref("Animation.currentTime")}} - : The current time value of the animation in milliseconds, whether running or paused. If the animation lacks a {{domxref("AnimationTimeline", "timeline")}}, is inactive or hasn't been played yet, its value is `null`. - {{domxref("Animation.effect")}} - : Gets and sets the {{domxref("AnimationEffect")}} associated with this animation. This will usually be a {{domxref("KeyframeEffect")}} object. - {{domxref("Animation.finished")}} {{ReadOnlyInline}} - : Returns the current finished Promise for this animation. - {{domxref("Animation.id")}} - : Gets and sets the `String` used to identify the animation. - {{domxref("Animation.pending")}} {{ReadOnlyInline}} - : Indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation. - {{domxref("Animation.playState")}} {{ReadOnlyInline}} - : Returns an enumerated value describing the playback state of an animation. - {{domxref("Animation.playbackRate")}} - : Gets or sets the playback rate of the animation. - {{domxref("Animation.ready")}} {{ReadOnlyInline}} - : Returns the current ready Promise for this animation. - {{domxref("Animation.replaceState")}} {{ReadOnlyInline}} - : Indicates whether the animation is active, has been automatically removed after being replaced by another animation, or has been explicitly persisted by a call to {{domxref("Animation.persist()")}}. - {{domxref("Animation.startTime")}} - : Gets or sets the scheduled time when an animation's playback should begin. - {{domxref("Animation.timeline")}} - : Gets or sets the {{domxref("AnimationTimeline", "timeline")}} associated with this animation. ## Instance methods - {{domxref("Animation.cancel()")}} - : Clears all {{domxref("KeyframeEffect", "keyframeEffects")}} caused by this animation and aborts its playback. - {{domxref("Animation.commitStyles()")}} - : Commits the current styling state of an animation to the element being animated, even after that animation has been removed. It will cause the current styling state to be written to the element being animated, in the form of properties inside a `style` attribute. - {{domxref("Animation.finish()")}} - : Seeks either end of an animation, depending on whether the animation is playing or reversing. - {{domxref("Animation.pause()")}} - : Suspends playing of an animation. - {{domxref("Animation.persist()")}} - : Explicitly persists an animation, preventing it from being [automatically removed](/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API#automatically_removing_filling_animations) when another animation replaces it. - {{domxref("Animation.play()")}} - : Starts or resumes playing of an animation, or begins the animation again if it previously finished. - {{domxref("Animation.reverse()")}} - : Reverses playback direction, stopping at the start of the animation. If the animation is finished or unplayed, it will play from end to beginning. - {{domxref("Animation.updatePlaybackRate()")}} - : Sets the speed of an animation after first synchronizing its playback position. ## Events - {{domxref("Animation.cancel_event", "cancel")}} - : Fires when the {{domxref("Animation.cancel()")}} method is called or when the animation enters the `"idle"` play state from another state. - {{domxref("Animation.finish_event", "finish")}} - : Fires when the animation finishes playing. - {{domxref("animation.remove_event", "remove")}} - : Fires when the animation is [automatically removed](#automatically_removing_filling_animations) by the browser. ## Accessibility concerns Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine, and Scotopic sensitivity. Consider providing a mechanism for pausing or disabling animation, as well as using the [Reduced Motion Media Query](/en-US/docs/Web/CSS/@media/prefers-reduced-motion) (or equivalent [user agent client hint](/en-US/docs/Web/HTTP/Client_hints#user-agent_client_hints) {{HTTPHeader("Sec-CH-Prefers-Reduced-Motion")}}) to create a complimentary experience for users who have expressed a preference for no animated experiences. - [Designing Safer Web Animation For Motion Sensitivity Β· An A List Apart Article](https://alistapart.com/article/designing-safer-web-animation-for-motion-sensitivity/) - [An Introduction to the Reduced Motion Media Query | CSS-Tricks](https://css-tricks.com/introduction-reduced-motion-media-query/) - [Responsive Design for Motion | WebKit](https://webkit.org/blog/7551/responsive-design-for-motion/) - [MDN Understanding WCAG, Guideline 2.2 explanations](/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.2_%e2%80%94_enough_time_provide_users_enough_time_to_read_and_use_content) - [Understanding Success Criterion 2.2.2 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-pause.html) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/currenttime/index.md
--- title: "Animation: currentTime property" short-title: currentTime slug: Web/API/Animation/currentTime page-type: web-api-instance-property browser-compat: api.Animation.currentTime --- {{APIRef("Web Animations")}} The **`Animation.currentTime`** property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) returns and sets the current time value of the animation in milliseconds, whether running or paused. If the animation lacks a {{domxref("AnimationTimeline", "timeline")}}, is inactive, or hasn't been played yet, `currentTime`'s return value is `null`. ## Value A number representing the current time in milliseconds, or `null` to deactivate the animation. ## Examples In the [Drink Me/Eat Me game](https://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010), Alice's height is animated so it can go from small to large or large to small. At the start of the game, her height is set between the two extremes by setting her animation's `currentTime` to half her `KeyframeEffect`'s duration: ```js aliceChange.currentTime = aliceChange.effect.timing.duration / 2; ``` A more generic means of seeking to the 50% mark of an animation would be: ```js animation.currentTime = animation.effect.getComputedTiming().delay + animation.effect.getComputedTiming().activeDuration / 2; ``` ## Reduced time precision To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting), the precision of `animation.currentTime` might get rounded depending on browser settings. In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 20 microseconds in Firefox 59; in 60 it will be 2 milliseconds. ```js // reduced time precision (2ms) in Firefox 60 animation.currentTime; // 23.404 // 24.192 // 25.514 // … // reduced time precision with `privacy.resistFingerprinting` enabled animation.currentTime; // 49.8 // 50.6 // 51.7 // … ``` In Firefox, you can also enabled `privacy.resistFingerprinting`, the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Animation")}} for other methods and properties you can use to control web page animation. - {{domxref("Animation.startTime")}} for the time an animation is scheduled to start. - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/reverse/index.md
--- title: "Animation: reverse() method" short-title: reverse() slug: Web/API/Animation/reverse page-type: web-api-instance-method browser-compat: api.Animation.reverse --- {{APIRef("Web Animations")}} The **`Animation.reverse()`** method of the {{ domxref("Animation") }} Interface reverses the playback direction, meaning the animation ends at its beginning. If called on an unplayed animation, the whole animation is played backwards. If called on a paused animation, the animation will continue in reverse. ## Syntax ```js-nolint reverse() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples In the [Growing/Shrinking Alice Game](https://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010) example, clicking or tapping the bottle causes Alice's growing animation (`aliceChange`) to play backwards, causing her to get smaller. It is done by setting `aliceChange`'s {{ domxref("Animation.playbackRate") }} to `-1` like so: ```js const shrinkAlice = () => { // play Alice's animation in reverse aliceChange.playbackRate = -1; aliceChange.play(); // play the bottle's animation drinking.play(); }; ``` But it could also have been done by calling `reverse()` on `aliceChange` like so: ```js const shrinkAlice = () => { // play Alice's animation in reverse aliceChange.reverse(); // play the bottle's animation drinking.play(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} for other methods and properties you can use to control web page animation. - {{domxref("Animation.pause()")}} to pause an animation. - {{domxref("Animation.play()")}} to move an animation forward.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/finish_event/index.md
--- title: "Animation: finish event" short-title: finish slug: Web/API/Animation/finish_event page-type: web-api-event browser-compat: api.Animation.finish_event --- {{ APIRef("Web Animations") }} The **`finish`** event of the {{domxref("Animation")}} interface is fired when the animation finishes playing, either when the animation completes naturally, or when the {{domxref("Animation.finish()")}} method is called to immediately cause the animation to finish up. > **Note:** The `"paused"` play state supersedes the `"finished"` play > state; if the animation is both paused and finished, the `"paused"` state > is the one that will be reported. You can force the animation into the > `"finished"` state by setting its {{domxref("Animation.startTime", "startTime")}} to > `document.timeline.currentTime - (Animation.currentTime * Animation.playbackRate)`. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js-nolint addEventListener("finish", (event) => { }) onfinish = (event) => { } ``` ## Event type An {{domxref("AnimationPlaybackEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("AnimationPlaybackEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("AnimationPlaybackEvent.currentTime")}} {{ReadOnlyInline}} - : The current time of the animation that generated the event. - {{domxref("AnimationPlaybackEvent.timelineTime")}} {{ReadOnlyInline}} - : The time value of the timeline of the animation that generated the event. ## Examples `Animation.onfinish` is used several times in the Alice in Web Animations API Land [Growing/Shrinking Alice Game](https://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010). Here is one instance where we add pointer events back to an element after its opacity animation has faded it in: ```js // Add an animation to the game's ending credits const endingUI = document.getElementById("ending-ui"); const bringUI = endingUI.animate(keysFade, timingFade); // Pause said animation's credits bringUI.pause(); // This function removes pointer events on the credits. hide(endingUI); // When the credits are later faded in, // we re-add the pointer events when they're done bringUI.onfinish = (event) => { endingUI.style.pointerEvents = "auto"; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} - {{domxref("Animation.finish()")}}
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/playbackrate/index.md
--- title: "Animation: playbackRate property" short-title: playbackRate slug: Web/API/Animation/playbackRate page-type: web-api-instance-property browser-compat: api.Animation.playbackRate --- {{APIRef("Web Animations")}} The **`Animation.playbackRate`** property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) returns or sets the playback rate of the animation. Animations have a **playback rate** that provides a scaling factor from the rate of change of the animation's {{domxref("DocumentTimeline", "timeline")}} time values to the animation's current time. The playback rate is initially `1`. ## Value Takes a number that can be 0, negative, or positive. Negative values reverse the animation. The value is a scaling factor, so for example a value of 2 would double the playback rate. > **Note:** Setting an animation's `playbackRate` to `0` effectively pauses the animation (however, its {{domxref("Animation.playstate", "playstate")}} does not necessarily become `paused`). ## Examples In the [Growing/Shrinking Alice Game](https://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010) example, clicking or tapping the bottle causes Alice's growing animation (`aliceChange`) to reverse, causing her to shrink: ```js const shrinkAlice = () => { aliceChange.playbackRate = -1; aliceChange.play(); }; // On tap or click, Alice will shrink. bottle.addEventListener("mousedown", shrinkAlice, false); bottle.addEventListener("touchstart", shrinkAlice, false); ``` Contrariwise, clicking on the cake causes her to "grow," playing `aliceChange` forwards again: ```js const growAlice = () => { aliceChange.playbackRate = 1; aliceChange.play(); }; // On tap or click, Alice will grow. cake.addEventListener("mousedown", growAlice, false); cake.addEventListener("touchstart", growAlice, false); ``` In another example, the [Red Queen's Race Game](https://codepen.io/rachelnabors/pen/PNGGaV?editors=0010), Alice and the Red Queen are constantly slowing down: ```js setInterval(() => { // Make sure the playback rate never falls below .4 if (redQueen_alice.playbackRate > 0.4) { redQueen_alice.playbackRate *= 0.9; } }, 3000); ``` But clicking or tapping on them causes them to speed up by multiplying their `playbackRate`: ```js const goFaster = () => { redQueen_alice.playbackRate *= 1.1; }; document.addEventListener("click", goFaster); document.addEventListener("touchstart", goFaster); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}}
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/starttime/index.md
--- title: "Animation: startTime property" short-title: startTime slug: Web/API/Animation/startTime page-type: web-api-instance-property browser-compat: api.Animation.startTime --- {{ APIRef("Web Animations") }} The **`Animation.startTime`** property of the {{domxref("Animation")}} interface is a double-precision floating-point value which indicates the scheduled time when an animation's playback should begin. An animation's **start time** is the time value of its {{domxref("DocumentTimeline","timeline")}} when its target {{domxref("KeyframeEffect")}} is scheduled to begin playback. An animation's **start time** is initially unresolved (meaning that it's `null` because it has no value). ## Value A floating-point number representing the current time in milliseconds, or `null` if no time is set. You can read this value to determine what the start time is currently set at, and you can change this value to make the animation start at a different time. ## Examples In the [Running on Web Animations API example](https://codepen.io/rachelnabors/pen/zxYexJ?editors=0010), we can sync all new animated cats by giving them all the same `startTime` as the original running cat: ```js const catRunning = document .getElementById("withWAAPI") .animate(keyframes, timing); /* A function that makes new cats. */ function addCat() { const newCat = document.createElement("div"); newCat.classList.add("cat"); return newCat; } /* This is the function that adds a cat to the WAAPI column */ function animateNewCatWithWAAPI() { // make a new cat const newCat = addCat(); // animate said cat with the WAAPI's "animate" function const newAnimationPlayer = newCat.animate(keyframes, timing); // set the animation's start time to be the same as the original .cat#withWAAPI newAnimationPlayer.startTime = catRunning.startTime; // Add the cat to the pile. WAAPICats.appendChild(newCat); } ``` ## Reduced time precision To offer protection against timing attacks and [fingerprinting](/en-US/docs/Glossary/Fingerprinting), the precision of `animation.startTime` might get rounded depending on browser settings. In Firefox, the `privacy.reduceTimerPrecision` preference is enabled by default and defaults to 20 Β΅s in Firefox 59; in 60 it will be 2 ms. ```js // reduced time precision (2ms) in Firefox 60 animation.startTime; // 23.404 // 24.192 // 25.514 // … // reduced time precision with `privacy.resistFingerprinting` enabled animation.startTime; // 49.8 // 50.6 // 51.7 // … ``` In Firefox, you can also enabled `privacy.resistFingerprinting`, the precision will be 100ms or the value of `privacy.resistFingerprinting.reduceTimerPrecision.microseconds`, whichever is larger. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} - {{domxref("Animation.currentTime")}} for the current time of the animation.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/playstate/index.md
--- title: "Animation: playState property" short-title: playState slug: Web/API/Animation/playState page-type: web-api-instance-property browser-compat: api.Animation.playState --- {{APIRef("Web Animations")}} The read-only **`Animation.playState`** property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) returns an enumerated value describing the playback state of an animation. ## Value - `idle` - : The current time of the animation is unresolved and there are no pending tasks. - `running` - : The animation is running. - `paused` - : The animation was suspended and the {{domxref("Animation.currentTime")}} property is not updating. - `finished` - : The animation has reached one of its boundaries and the {{domxref("Animation.currentTime")}} property is not updating. Previously, Web Animations defined a **`pending`** value to indicate that some asynchronous operation such as initiating playback was yet to complete. This is now indicated by the separate {{domxref("Animation.pending")}} property. ## Examples In the [Growing/Shrinking Alice Game](https://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010) example, players can get an ending with [Alice crying into a pool of tears](https://codepen.io/rachelnabors/pen/EPJdJx?editors=0010). In the game, for performance reasons, the tears should only be animating when they're visible. So they must be paused as soon as they are animated like so: ```js // Setting up the tear animations tears.forEach((el) => { el.animate(tearsFalling, { delay: getRandomMsRange(-1000, 1000), // randomized for each tear duration: getRandomMsRange(2000, 6000), // randomized for each tear iterations: Infinity, easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)", }); el.pause(); }); // Play the tears falling when the ending needs to be shown. tears.forEach((el) => { el.play(); }); // Reset the crying tears animations and pause them. tears.forEach((el) => { el.pause(); el.currentTime = 0; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} for other methods and properties you can use to control web page animation.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/timeline/index.md
--- title: "Animation: timeline property" short-title: timeline slug: Web/API/Animation/timeline page-type: web-api-instance-property browser-compat: api.Animation.timeline --- {{ APIRef("Web Animations") }} The **`Animation.timeline`** property of the {{domxref("Animation")}} interface returns or sets the {{domxref("AnimationTimeline", "timeline")}} associated with this animation. A timeline is a source of time values for synchronization purposes, and is an {{domxref("AnimationTimeline")}}-based object. By default, the animation's timeline and the {{domxref("Document")}}'s timeline are the same. ## Value A {{domxref("AnimationTimeline", "timeline object", "", 1)}} to use as the timing source for the animation, or `null` to use the default, which is the {{domxref("Document")}}'s timeline. ## Examples Here we set the animation's timeline to be the same as the document's timeline (this is the default timeline for all animations, by the way): ```js animation.timeline = document.timeline; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} - {{domxref("AnimationTimeline")}} the parent object all timelines inherit from. - {{domxref("DocumentTimeline")}} the only kind of timeline object available at this time. - {{domxref("Document.timeline")}} is the default timeline all animations are assigned.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/pause/index.md
--- title: "Animation: pause() method" short-title: pause() slug: Web/API/Animation/pause page-type: web-api-instance-method browser-compat: api.Animation.pause --- {{ APIRef("Web Animations") }} The **`pause()`** method of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)'s {{domxref("Animation")}} interface suspends playback of the animation. ## Syntax ```js-nolint animation.pause(); ``` ### Parameters None. ### Return value None. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the animation's {{domxref("Animation.currentTime", "currentTime")}} is `unresolved` (perhaps it hasn't started playing yet), and the end time of the animation is positive infinity. ## Example `Animation.pause()` is used many times in the Alice in Web Animations API Land [Growing/Shrinking Alice Game](https://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010), largely because animations created with the {{domxref("Element.animate()")}} method immediately start playing and must be paused manually if you want to avoid that: ```js // animation of the cupcake slowly getting eaten up const nommingCake = document .getElementById("eat-me_sprite") .animate( [{ transform: "translateY(0)" }, { transform: "translateY(-80%)" }], { fill: "forwards", easing: "steps(4, end)", duration: aliceChange.effect.timing.duration / 2, }, ); // doesn't actually need to be eaten until a click event, so pause it initially: nommingCake.pause(); ``` Additionally, when resetting: ```js // An all-purpose function to pause the animations on Alice, the cupcake, and the bottle that reads "drink me." const stopPlayingAlice = () => { aliceChange.pause(); nommingCake.pause(); drinking.pause(); }; // When the user releases the cupcake or the bottle, pause the animations. cake.addEventListener("mouseup", stopPlayingAlice, false); bottle.addEventListener("mouseup", stopPlayingAlice, false); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} for other methods and properties you can use to control web page animation. - {{domxref("Animation.pause()")}} to pause an animation. - {{domxref("Animation.reverse()")}} to play an animation backwards. - {{domxref("Animation.finish()")}} to finish an animation. - {{domxref("Animation.cancel()")}} to cancel an animation.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/replacestate/index.md
--- title: "Animation: replaceState property" short-title: replaceState slug: Web/API/Animation/replaceState page-type: web-api-instance-property browser-compat: api.Animation.replaceState --- {{ APIRef("Web Animations") }} The read-only **`Animation.replaceState`** property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) indicates whether the animation has been [removed by the browser automatically](/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API#automatically_removing_filling_animations) after being replaced by another animation. ## Value A string that represents the replace state of the animation. The value can be one of: - `active` - : The initial value of the animation's replace state when the animation is created. - `persisted` - : The animation has been explicitly persisted by invoking {{domxref("Animation.persist()")}} on it. - `removed` - : The animation has been removed by the browser automatically. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} - {{domxref("Animation.remove_event","remove")}} event - {{domxref("Animation.persist()")}}
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/updateplaybackrate/index.md
--- title: "Animation: updatePlaybackRate() method" short-title: updatePlaybackRate() slug: Web/API/Animation/updatePlaybackRate page-type: web-api-instance-method browser-compat: api.Animation.updatePlaybackRate --- {{APIRef("Web Animations")}} The **`updatePlaybackRate()`** method of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)'s {{domxref("Animation")}} Interface sets the speed of an animation after first synchronizing its playback position. In some cases, an animation may run on a separate thread or process and will continue updating even while long-running JavaScript delays the main thread. In such a case, setting the {{domxref("Animation.playbackRate", "playbackRate")}} on the animation directly may cause the animation's playback position to jump since its playback position on the main thread may have drifted from the playback position where it is currently running. `updatePlaybackRate()` is an asynchronous method that sets the speed of an animation after synchronizing with its current playback position, ensuring that the resulting change in speed does not produce a sharp jump. After calling `updatePlaybackRate()` the animation's {{domxref("Animation.playbackRate", "playbackRate")}} is _not_ immediately updated. It will be updated once the animation's {{domxref("Animation.ready", "ready")}} promise is resolved. ## Syntax ```js-nolint updatePlaybackRate(playbackRate) ``` ### Parameters - `playbackRate` - : The new speed to set. This may be a positive number (to speed up or slow down the animation), a negative number (to make it play backwards), or zero (to effectively pause the animation). ### Return value None ({{jsxref("undefined")}}). ## Examples A speed selector component would benefit from smooth updating of `updatePlaybackRate()`, as demonstrated below: ```js speedSelector.addEventListener("input", (evt) => { cartoon.updatePlaybackRate(parseFloat(evt.target.value)); cartoon.ready.then(() => { console.log(`Playback rate set to ${cartoon.playbackRate}`); }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation.playbackRate")}} β€” read back the current playback rate or set it in a synchronous manner. - {{domxref("Animation.reverse()")}} β€” invert the playback rate and restart playback if necessary. - {{domxref("Animation")}} β€” contains other methods and properties you can use to control web page animation.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/play/index.md
--- title: "Animation: play() method" short-title: play() slug: Web/API/Animation/play page-type: web-api-instance-method browser-compat: api.Animation.play --- {{ APIRef("Web Animations") }} The **`play()`** method of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)'s {{ domxref("Animation") }} Interface starts or resumes playing of an animation. If the animation is finished, calling `play()` restarts the animation, playing it from the beginning. ## Syntax ```js-nolint play() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples In the [Growing/Shrinking Alice Game](https://codepen.io/rachelnabors/pen/PNYGZQ?editors=0010) example, clicking or tapping the cake causes Alice's growing animation (`aliceChange`) to play forward, causing her to get bigger, as well as triggering the cake's animation. Two `Animation.play()`s, one `EventListener`: ```js // The cake has its own animation: const nommingCake = document .getElementById("eat-me_sprite") .animate( [{ transform: "translateY(0)" }, { transform: "translateY(-80%)" }], { fill: "forwards", easing: "steps(4, end)", duration: aliceChange.effect.timing.duration / 2, }, ); // Pause the cake's animation so it doesn't play immediately. nommingCake.pause(); // This function will play when ever a user clicks or taps const growAlice = () => { // Play Alice's animation. aliceChange.play(); // Play the cake's animation. nommingCake.play(); }; // When a user holds their mouse down or taps, call growAlice to make all the animations play. cake.addEventListener("mousedown", growAlice, false); cake.addEventListener("touchstart", growAlice, false); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} for other methods and properties you can use to control web page animation. - {{domxref("Animation.pause()")}} to pause an animation. - {{domxref("Animation.reverse()")}} to play an animation backwards. - {{domxref("Animation.finish()")}} to finish an animation. - {{domxref("Animation.cancel()")}} to cancel an animation.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/cancel/index.md
--- title: "Animation: cancel() method" short-title: cancel() slug: Web/API/Animation/cancel page-type: web-api-instance-method browser-compat: api.Animation.cancel --- {{ APIRef("Web Animations") }} The Web Animations API's **`cancel()`** method of the {{domxref("Animation")}} interface clears all {{domxref("KeyframeEffect")}}s caused by this animation and aborts its playback. > **Note:** When an animation is cancelled, its {{domxref("Animation.startTime", "startTime")}} and {{domxref("Animation.currentTime", "currentTime")}} are set to `null`. ## Syntax ```js-nolint cancel() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions This method doesn't directly throw exceptions; however, if the animation's {{domxref("Animation.playState", "playState")}} is anything but `"idle"` when cancelled, the {{domxref("Animation.finished", "current finished promise", "", 1)}} is rejected with a {{domxref("DOMException")}} named `AbortError`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("KeyframeEffect")}} - {{domxref("Animation")}} - {{domxref("Animation.playState")}} - {{domxref("Animation.finished")}} returns the promise this action will reject if the animation's `playState` is not `"idle"`.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/finish/index.md
--- title: "Animation: finish() method" short-title: finish() slug: Web/API/Animation/finish page-type: web-api-instance-method browser-compat: api.Animation.finish --- {{APIRef("Web Animations")}} The **`finish()`** method of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)'s {{domxref("Animation")}} Interface sets the current playback time to the end of the animation corresponding to the current playback direction. That is, if the animation is playing forward, it sets the playback time to the length of the animation sequence, and if the animation is playing in reverse (having had its {{domxref("Animation.reverse", "reverse()")}} method called), it sets the playback time to 0. ## Syntax ```js-nolint finish() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidState` - : The player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. ## Examples The following example shows how to use the `finish()` method and catch an `InvalidState` error. ```js interfaceElement.addEventListener("mousedown", () => { try { player.finish(); } catch (e) { if (e instanceof InvalidState) { console.log("finish() called on paused or finished animation."); } else { logMyErrors(e); //pass exception object to error handler } } }); ``` The following example finishes all the animations on a single element, regardless of their direction of playback. ```js elem.getAnimations().forEach((animation) => animation.finish()); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} for other methods and properties you can use to control web page animation. - {{domxref("Animation.play()")}} to play an animation forward. - {{domxref("Animation.reverse()")}} to play an animation backward.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/id/index.md
--- title: "Animation: id property" short-title: id slug: Web/API/Animation/id page-type: web-api-instance-property browser-compat: api.Animation.id --- {{ APIRef("Web Animations") }} The **`Animation.id`** property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) returns or sets a string used to identify the animation. ## Value A string which can be used to identify the animation, or `null` if the animation has no `id`. ## Examples In the [Follow the White Rabbit example](https://codepen.io/rachelnabors/pen/eJyWzm?editors=0010), you can assign the `rabbitDownAnimation` an `id` like so: ```js rabbitDownAnimation.id = "rabbitGo"; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("KeyframeEffect")}} - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}}
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/pending/index.md
--- title: "Animation: pending property" short-title: pending slug: Web/API/Animation/pending page-type: web-api-instance-property browser-compat: api.Animation.pending --- {{APIRef("Web Animations")}} The read-only **`Animation.pending`** property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation. ## Value **`true`** if the animation is pending, **`false`** otherwise. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Animation")}} for other methods and properties you can use to control web page animation. - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/ready/index.md
--- title: "Animation: ready property" short-title: ready slug: Web/API/Animation/ready page-type: web-api-instance-property browser-compat: api.Animation.ready --- {{ APIRef("Web Animations") }} The read-only **`Animation.ready`** property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) returns a {{jsxref("Promise")}} which resolves when the animation is ready to play. A new promise is created every time the animation enters the `"pending"` [play state](/en-US/docs/Web/API/Animation/playState) as well as when the animation is canceled, since in both of those scenarios, the animation is ready to be started again. > **Note:** Since the same {{jsxref("Promise")}} is used for both pending `play` and pending `pause` requests, authors are advised to check the state of the animation when the promise is resolved. ## Value A {{jsxref("Promise")}} which resolves when the animation is ready to be played. You'll typically use a construct similar to this when using the ready promise: ```js animation.ready.then(() => { // Do whatever needs to be done when // the animation is ready to run }); ``` ## Examples In the following example, the state of the animation will be `running` when the **current ready Promise** is resolved because the animation does not leave the `pending` play state in between the calls to `pause` and `play` and hence the **current ready Promise** does not change. ```js animation.pause(); animation.ready.then(() => { // Displays 'running' alert(animation.playState); }); animation.play(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} - {{domxref("Animation.playState")}}
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/effect/index.md
--- title: "Animation: effect property" short-title: effect slug: Web/API/Animation/effect page-type: web-api-instance-property browser-compat: api.Animation.effect --- {{ APIRef("Web Animations") }} The **`Animation.effect`** property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) gets and sets the target effect of an animation. The target effect may be either an effect object of a type based on {{domxref("AnimationEffect")}}, such as {{domxref("KeyframeEffect")}}, or `null`. ## Value A {{domxref("AnimationEffect")}} object describing the target animation effect for the animation, or `null` to indicate no active effect. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("AnimationEffect")}} - {{domxref("Animation")}}
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/finished/index.md
--- title: "Animation: finished property" short-title: finished slug: Web/API/Animation/finished page-type: web-api-instance-property browser-compat: api.Animation.finished --- {{ APIRef("Web Animations") }} The **`Animation.finished`** read-only property of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) returns a {{jsxref("Promise")}} which resolves once the animation has finished playing. > **Note:** Every time the animation leaves the `finished` play state (that is, when it starts playing again), a new `Promise` is created for this property. The new `Promise` will resolve once the new animation sequence has completed. ## Value A {{jsxref("Promise")}} object which will resolve once the animation has finished running. ## Examples The following code waits until all animations running on the element `elem` have finished, then deletes the element from the DOM tree: ```js Promise.all(elem.getAnimations().map((animation) => animation.finished)).then( () => elem.remove(), ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("KeyframeEffect")}} - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}}
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/persist/index.md
--- title: "Animation: persist() method" short-title: persist() slug: Web/API/Animation/persist page-type: web-api-instance-method browser-compat: api.Animation.persist --- {{APIRef("Web Animations")}} The `persist()` method of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)'s {{domxref("Animation")}} interface explicitly persists an animation, preventing it from being [automatically removed](/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API#automatically_removing_filling_animations) when it is replaced by another animation. ## Syntax ```js-nolint persist() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Using `persist()` In this example, we have three buttons: - "Add persistent animation" and "Add transient animation" each add a new transform animation to the red square. The animations alternate direction: so the first is left to right, the second is right to left, and so on. "Add persistent animation" calls `persist()` on the animation it creates. - The third button, "Cancel an animation", cancels the most recently added animation. The example displays a list of all animations that have not been canceled, in the order they were added, along with each animation's `replaceState`. #### HTML ```html <div id="animation-target"></div> <button id="start-persistent">Add persistent animation</button> <button id="start-transient">Add transient animation</button> <button id="cancel">Cancel an animation</button> <ol id="stack"></ol> ``` ```html hidden <template id="list-item-template"> <li> <span class="replaceState"></span>, <span class="description"></span> </li> </template> ``` #### CSS ```css div { width: 100px; height: 100px; background: red; transform: translate(100px); } ``` #### JavaScript ```js const target = document.getElementById("animation-target"); const persistentButton = document.getElementById("start-persistent"); const transientButton = document.getElementById("start-transient"); const cancelButton = document.getElementById("cancel"); persistentButton.addEventListener("click", () => startAnimation(true)); transientButton.addEventListener("click", () => startAnimation(false)); cancelButton.addEventListener("click", cancelTop); const stack = []; let offset = -100; function startAnimation(persist) { offset = -offset; const animation = target.animate( { transform: `translate(${100 + offset}px)` }, { duration: 500, fill: "forwards" }, ); stack.push(animation); if (persist) { animation.persist(); } // Add the animation to the displayed stack (implementation not shown) show(animation, offset); } function cancelTop() { stack.pop()?.cancel(); } ``` ```js hidden const stackDisplay = document.getElementById("stack"); const template = document.getElementById("list-item-template").content.firstElementChild; const nodes = new Map(); function show(animation, offset) { const direction = offset < 0 ? "left" : "right"; const li = template.cloneNode(true); const description = li.querySelector(".description"); const replaceState = li.querySelector(".replaceState"); description.textContent = direction; replaceState.textContent = animation.replaceState; nodes.set(animation, { li, description, replaceState }); stackDisplay.append(li); animation.addEventListener("cancel", () => { nodes.get(animation).li.remove(); nodes.delete(animation); }); animation.addEventListener("remove", () => { nodes.get(animation).replaceState.textContent = animation.replaceState; }); } ``` #### Result Note that adding a new transient animation will replace any previously added transient animation. Those animations will be automatically removed, and their `replaceState` will be `"removed"`. However, persistent animations will not be removed. Also note that removed animations don't affect the display; the position of the {{htmlelement("div")}} is determined by the most recent active or persisted animation. {{EmbedLiveSample("using_persist","",300)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} for other methods and properties you can use to control web page animation. - {{domxref("Animation.replaceState")}} - {{domxref("Animation.remove_event","remove")}} event
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/remove_event/index.md
--- title: "Animation: remove event" short-title: remove slug: Web/API/Animation/remove_event page-type: web-api-event browser-compat: api.Animation.remove_event --- {{ APIRef("Web Animations") }} The **`remove`** event of the {{domxref("Animation")}} interface fires when the animation is [automatically removed](/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API#automatically_removing_filling_animations) by the browser. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js-nolint addEventListener('remove', (event) => { }) onremove = (event) => { } ``` ## Event type An {{domxref("AnimationPlaybackEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("AnimationPlaybackEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("AnimationPlaybackEvent.currentTime")}} {{ReadOnlyInline}} - : The current time of the animation that generated the event. - {{domxref("AnimationPlaybackEvent.timelineTime")}} {{ReadOnlyInline}} - : The time value of the timeline of the animation that generated the event. ## Examples ### Removing replaced animations In this example we have a `<button id="start">` element, and an event listener that runs whenever the mouse moves. The {{domxref("Element.mousemove_event","mousemove")}} event handler sets up an animation that animates the `<button>` to the position of the mouse pointer. This could result in a huge animations list, which could create a memory leak. For this reason, modern browsers automatically remove forwards-filling animations that are overridden by other animations. The number of animations created is displayed. A `remove` event listener is used to count and display the number of animations removed as well. All but one of the animations should eventually be removed. #### HTML ```html <button id="start">Click to drag</button> <br /> <button id="reset">Reset example</button> <p> Click the button to start the animation (disabled by default to protect those who suffer migraines when experiencing such animations). </p> <p>Animations created: <span id="count-created">0</span></p> <p>Animations removed: <span id="count-removed">0</span></p> ``` #### CSS ```css :root, body { margin: 0; padding: 0; height: 100%; } button { margin: 0.5rem 0; } ``` #### JavaScript ```js const button = document.querySelector("#start"); let created = 0; let removed = 0; button.addEventListener( "click", () => { document.body.addEventListener("mousemove", (event) => { const animation = button.animate( { transform: `translate(${event.clientX}px, ${event.clientY}px)` }, { duration: 500, fill: "forwards" }, ); created++; showCounts(); // the remove event fires after the animation is removed animation.addEventListener("remove", () => { removed++; showCounts(); }); }); }, { once: true }, ); function showCounts() { document.getElementById("count-created").textContent = created; document.getElementById("count-removed").textContent = removed; } const reset = document.querySelector("#reset"); reset.addEventListener("click", () => { document.location.reload(); }); ``` #### Result {{embedlivesample("Removing_replaced_animations","",250)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}}, {{domxref("AnimationPlaybackEvent")}} - {{domxref("Animation.replaceState")}}, to check whether an animation has been removed - {{domxref("Animation.persist()")}}, to prevent removal of an animation
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/animation/index.md
--- title: "Animation: Animation() constructor" short-title: Animation() slug: Web/API/Animation/Animation page-type: web-api-constructor browser-compat: api.Animation.Animation --- {{ APIRef("Web Animations") }} The **`Animation()`** constructor of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) returns a new `Animation` object instance. ## Syntax ```js-nolint new Animation() new Animation(effect) new Animation(effect, timeline) ``` ### Parameters - `effect` {{optional_inline}} - : The target effect, as an object based on the {{domxref("AnimationEffect")}} interface, to assign to the animation. Although in the future other effects such as `SequenceEffect`s or `GroupEffect`s might be possible, the only kind of effect currently available is {{domxref("KeyframeEffect")}}. This can be `null` (which is the default) to indicate that there should be no effect applied. - `timeline` {{optional_inline}} - : Specifies the `timeline` with which to associate the animation, as an object of a type based on the {{domxref("AnimationTimeline")}} interface. Currently the only timeline type available is {{domxref("DocumentTimeline")}}, but in the future there may be timelines associated with gestures or scrolling, for example. The default value is {{domxref("Document.timeline")}}, but this can be set to `null` as well. ## Examples In the [Follow the White Rabbit example](https://codepen.io/rachelnabors/pen/eJyWzm/?editors=0010), the `Animation()` constructor is used to create an `Animation` for the `rabbitDownKeyframes` using the document's `timeline`: ```js const rabbitDownAnimation = new Animation( rabbitDownKeyframes, document.timeline, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}}
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/commitstyles/index.md
--- title: "Animation: commitStyles() method" short-title: commitStyles() slug: Web/API/Animation/commitStyles page-type: web-api-instance-method browser-compat: api.Animation.commitStyles --- {{APIRef("Web Animations")}} The `commitStyles()` method of the [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)'s {{domxref("Animation")}} interface writes the [computed values](/en-US/docs/Web/CSS/computed_value) of the animation's current styles into its target element's [`style`](/en-US/docs/Web/HTML/Global_attributes#style) attribute. `commitStyles()` works even if the animation has been [automatically removed](/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API#automatically_removing_filling_animations). `commitStyles()` can be used in combination with `fill` to cause the final state of an animation to persist after the animation ends. The same effect could be achieved with `fill` alone, but [using indefinitely filling animations is discouraged](https://drafts.csswg.org/web-animations-1/#fill-behavior). Animations [take precedence over all static styles](/en-US/docs/Web/CSS/Cascade#cascading_order), so an indefinite filling animation can prevent the target element from ever being styled normally. Using `commitStyles()` writes the styling state into the element's [`style`](/en-US/docs/Web/HTML/Global_attributes#style) attribute, where they can be modified and replaced as normal. ## Syntax ```js-nolint commitStyles() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Committing the final state of an animation In this example we have two buttons, labeled "Commit styles" and "Fill forwards". Both buttons animate when you click them, and both buttons persist the final state of the animation. The difference, though, is that "Fill forwards" only uses `fill: "forwards"` to persist the animation's final state: this means that the browser has to maintain the animation's state indefinitely, or until it can be automatically removed. However, the "Commit styles" button waits for the animation to finish, then calls `commitStyles()`, then cancels the animation, so the finished style is captured as the value of the `style` attribute, rather than as the animation state. #### HTML ```html <button class="commit-styles">Commit styles</button> <br /> <button class="fill-forwards">Fill forwards</button> ``` ```css hidden button { margin: 0.5rem; } ``` #### JavaScript ```js const commitStyles = document.querySelector(".commit-styles"); let offset1 = 0; commitStyles.addEventListener("click", async (event) => { // Start the animation offset1 = 100 - offset1; const animation = commitStyles.animate( { transform: `translate(${offset1}px)` }, { duration: 500, fill: "forwards" }, ); // Wait for the animation to finish await animation.finished; // Commit animation state to style attribute animation.commitStyles(); // Cancel the animation animation.cancel(); }); const fillForwards = document.querySelector(".fill-forwards"); let offset2 = 0; fillForwards.addEventListener("click", async (event) => { // Start the animation offset2 = 100 - offset2; const animation = fillForwards.animate( { transform: `translate(${offset2}px)` }, { duration: 500, fill: "forwards" }, ); }); ``` #### Result {{EmbedLiveSample("committing_the_final_state_of_an_animation")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}} for other methods and properties you can use to control web page animation.
0
data/mdn-content/files/en-us/web/api/animation
data/mdn-content/files/en-us/web/api/animation/cancel_event/index.md
--- title: "Animation: cancel event" short-title: cancel slug: Web/API/Animation/cancel_event page-type: web-api-event browser-compat: api.Animation.cancel_event --- {{ APIRef("Web Animations") }} The **`cancel`** event of the {{domxref("Animation")}} interface is fired when the {{domxref("Animation.cancel()")}} method is called or when the animation enters the `"idle"` play state from another state, such as when the animation is removed from an element before it finishes playing. > **Note:** Creating a new animation that is initially idle does not trigger a `cancel` event on the new animation. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js-nolint addEventListener("cancel", (event) => { }) oncancel = (event) => { } ``` ## Event type An {{domxref("AnimationPlaybackEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("AnimationPlaybackEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("AnimationPlaybackEvent.currentTime")}} {{ReadOnlyInline}} - : The current time of the animation that generated the event. - {{domxref("AnimationPlaybackEvent.timelineTime")}} {{ReadOnlyInline}} - : The time value of the timeline of the animation that generated the event. ## Examples If this animation is canceled, remove its element. ```js animation.oncancel = (event) => { animation.effect.target.remove(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API) - {{domxref("Animation")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/ext_color_buffer_half_float/index.md
--- title: EXT_color_buffer_half_float extension short-title: EXT_color_buffer_half_float slug: Web/API/EXT_color_buffer_half_float page-type: webgl-extension browser-compat: api.EXT_color_buffer_half_float --- {{APIRef("WebGL")}} The **`EXT_color_buffer_half_float`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and adds the ability to render to 16-bit floating-point color buffers. WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial). > **Note:** This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts. On WebGL 2, it's an alternative to using the {{domxref("EXT_color_buffer_float")}} extension on platforms that support 16-bit floating point render targets but not 32-bit floating point render targets. > > The {{domxref("OES_texture_half_float")}} extension implicitly enables this extension. ## Constants - `ext.RGBA16F_EXT` - : RGBA 16-bit floating-point color-renderable format. - `ext.RGB16F_EXT` - : RGB 16-bit floating-point color-renderable format. - `ext.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT` - : ? - `ext.UNSIGNED_NORMALIZED_EXT` - : ? ## Extended methods This extension extends {{domxref("WebGLRenderingContext.renderbufferStorage()")}}: - The `internalformat` parameter now accepts `ext.RGBA16F_EXT` and `ext.RGBA16F_EXT`. ## Examples ```js const ext = gl.getExtension("EXT_color_buffer_half_float"); gl.renderbufferStorage(gl.RENDERBUFFER, ext.RGBA16F_EXT, 256, 256); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("WebGLRenderingContext.renderbufferStorage()")}} - {{domxref("OES_texture_half_float")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/messagechannel/index.md
--- title: MessageChannel slug: Web/API/MessageChannel page-type: web-api-interface browser-compat: api.MessageChannel --- {{APIRef("Channel Messaging API")}} The **`MessageChannel`** interface of the [Channel Messaging API](/en-US/docs/Web/API/Channel_Messaging_API) allows us to create a new message channel and send data through it via its two {{domxref("MessagePort")}} properties. {{AvailableInWorkers}} ## Constructor - {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}} - : Returns a new `MessageChannel` object with two new {{domxref("MessagePort")}} objects. ## Instance properties - {{domxref("MessageChannel.port1")}} {{ReadOnlyInline}} - : Returns port1 of the channel. - {{domxref("MessageChannel.port2")}} {{ReadOnlyInline}} - : Returns port2 of the channel. ## Example In the following example, you can see a new channel being created using the {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}} constructor. When the IFrame has loaded, we register an {{domxref("MessagePort/message_event","onmessage")}} handler for {{domxref("MessageChannel.port1")}} and transfer {{domxref("MessageChannel.port2")}} to the IFrame using the {{domxref("window.postMessage")}} method along with a message. When a message is received back from the IFrame, the `onMessage` function outputs the message to a paragraph. ```js const channel = new MessageChannel(); const output = document.querySelector(".output"); const iframe = document.querySelector("iframe"); // Wait for the iframe to load iframe.addEventListener("load", onLoad); function onLoad() { // Listen for messages on port1 channel.port1.onmessage = onMessage; // Transfer port2 to the iframe iframe.contentWindow.postMessage("Hello from the main page!", "*", [ channel.port2, ]); } // Handle messages received on port1 function onMessage(e) { output.innerHTML = e.data; } ``` For a full working example, see our [channel messaging basic demo](https://github.com/mdn/dom-examples/tree/main/channel-messaging-basic) on GitHub ([run it live too](https://mdn.github.io/dom-examples/channel-messaging-basic/)). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using channel messaging](/en-US/docs/Web/API/Channel_Messaging_API/Using_channel_messaging)
0
data/mdn-content/files/en-us/web/api/messagechannel
data/mdn-content/files/en-us/web/api/messagechannel/port1/index.md
--- title: "MessageChannel: port1 property" short-title: port1 slug: Web/API/MessageChannel/port1 page-type: web-api-instance-property browser-compat: api.MessageChannel.port1 --- {{APIRef("Channel Messaging API")}} The **`port1`** read-only property of the {{domxref("MessageChannel")}} interface returns the first port of the message channel β€” the port attached to the context that originated the channel. {{AvailableInWorkers}} ## Value A {{domxref("MessagePort")}} object, the first port of the channel, that is the port attached to the context that originated the channel. ## Examples In the following code block, you can see a new channel being created using the {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}} constructor. When the {{HTMLElement("iframe")}} has loaded, we pass {{domxref("MessageChannel.port2", "port2")}} to the {{HTMLElement("iframe")}} using {{domxref("MessagePort.postMessage")}} along with a message. The `handleMessage` handler then responds to a message being sent back from the `<iframe>` (using {{domxref("MessagePort.message_event", "onmessage")}}), putting it into a paragraph. The `handleMessage` method is associated to the `port1` to listen when the message arrives. ```js const channel = new MessageChannel(); const para = document.querySelector("p"); const ifr = document.querySelector("iframe"); const otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage("Hello from the main page!", "*", [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using channel messaging](/en-US/docs/Web/API/Channel_Messaging_API/Using_channel_messaging)
0
data/mdn-content/files/en-us/web/api/messagechannel
data/mdn-content/files/en-us/web/api/messagechannel/port2/index.md
--- title: "MessageChannel: port2 property" short-title: port2 slug: Web/API/MessageChannel/port2 page-type: web-api-instance-property browser-compat: api.MessageChannel.port2 --- {{APIRef("Channel Messaging API")}} The **`port2`** read-only property of the {{domxref("MessageChannel")}} interface returns the second port of the message channel β€” the port attached to the context at the other end of the channel, which the message is initially sent to. {{AvailableInWorkers}} ## Value A {{domxref("MessagePort")}} object representing the second port of the channel, the port attached to the context at the other end of the channel. ## Examples In the following code block, you can see a new channel being created using the {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}} constructor. When the IFrame has loaded, we pass `port2` to the IFrame using {{domxref("MessagePort.postMessage")}} along with a message. The `handleMessage` handler then responds to a message being sent back from the IFrame (using {{domxref("MessagePort.message_event", "onmessage")}}), putting it into a paragraph. {{domxref("MessageChannel.port1", "port1")}} is listened to, to check when the message arrives. ```js const channel = new MessageChannel(); const para = document.querySelector("p"); const ifr = document.querySelector("iframe"); const otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage("Hello from the main page!", "*", [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } ``` For a full working example, see our [channel messaging basic demo](https://github.com/mdn/dom-examples/tree/main/channel-messaging-basic) on GitHub ([run it live too](https://mdn.github.io/dom-examples/channel-messaging-basic/)). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using channel messaging](/en-US/docs/Web/API/Channel_Messaging_API/Using_channel_messaging)
0
data/mdn-content/files/en-us/web/api/messagechannel
data/mdn-content/files/en-us/web/api/messagechannel/messagechannel/index.md
--- title: "MessageChannel: MessageChannel() constructor" short-title: MessageChannel() slug: Web/API/MessageChannel/MessageChannel page-type: web-api-constructor browser-compat: api.MessageChannel.MessageChannel --- {{APIRef("Channel Messaging API")}} The **`MessageChannel()`** constructor of the {{domxref("MessageChannel")}} interface returns a new {{domxref("MessageChannel")}} object with two new {{domxref("MessagePort")}} objects. {{AvailableInWorkers}} ## Syntax ```js-nolint new MessageChannel() ``` ### Parameters None ({{jsxref("undefined")}}). ### Return value A new {{domxref("MessageChannel")}} object. ## Examples In the following code block, you can see a new channel being created using the `MessageChannel()` constructor. When the {{HTMLElement("iframe")}} has loaded, we pass {{domxref("MessageChannel.port2", "port2")}} to the `<iframe>` using {{domxref("MessagePort.postMessage")}} along with a message. The `handleMessage` handler then responds to a message being sent back from the `<iframe>` (using {{domxref("MessagePort.message_event", "onmessage")}}), putting it into a paragraph. The {{domxref("MessageChannel.port1", "port1")}} is listened to, to check when the message arrives. ```js const channel = new MessageChannel(); const para = document.querySelector("p"); const ifr = document.querySelector("iframe"); const otherWindow = ifr.contentWindow; ifr.addEventListener("load", iframeLoaded, false); function iframeLoaded() { otherWindow.postMessage("Hello from the main page!", "*", [channel.port2]); } channel.port1.onmessage = handleMessage; function handleMessage(e) { para.innerHTML = e.data; } ``` For a full working example, see our [channel messaging basic demo](https://github.com/mdn/dom-examples/tree/main/channel-messaging-basic) on GitHub ([run it live too](https://mdn.github.io/dom-examples/channel-messaging-basic/)). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using channel messaging](/en-US/docs/Web/API/Channel_Messaging_API/Using_channel_messaging)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/sharedstorage/index.md
--- title: SharedStorage slug: Web/API/SharedStorage page-type: web-api-interface status: - experimental browser-compat: api.SharedStorage --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}} The **`SharedStorage`** interface of the {{domxref("Shared Storage API", "Shared Storage API", "", "nocode")}} represents the shared storage for a particular origin, defining methods to write data to the shared storage. `SharedStorage` is the base class for: - {{domxref("WindowSharedStorage")}}, accessed via {{domxref("Window.sharedStorage")}}. - {{domxref("WorkletSharedStorage")}}, accessed via {{domxref("SharedStorageWorkletGlobalScope.sharedStorage")}}. {{InheritanceDiagram}} ## Instance methods - {{domxref("SharedStorage.append", "append()")}} {{Experimental_Inline}} - : Appends a string to the value of an existing key-value pair in the current origin's shared storage. - {{domxref("SharedStorage.clear", "clear()")}} {{Experimental_Inline}} - : Clears the current origin's shared storage, removing all data from it. - {{domxref("SharedStorage.delete", "delete()")}} {{Experimental_Inline}} - : Deletes an existing key-value pair from the current origin's shared storage. - {{domxref("SharedStorage.set", "set()")}} {{Experimental_Inline}} - : Stores a new key-value pair in the current origin's shared storage or updates an existing one. ## Examples ```js window.sharedStorage .set("ab-testing-group", "0") .then(console.log("Value saved to shared storage")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WindowSharedStorage")}} - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api/sharedstorage
data/mdn-content/files/en-us/web/api/sharedstorage/set/index.md
--- title: "SharedStorage: set() method" short-title: set() slug: Web/API/SharedStorage/set page-type: web-api-instance-method status: - experimental browser-compat: api.SharedStorage.set --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}} The **`set()`** method of the {{domxref("SharedStorage")}} interface either stores a new key-value pair in the current origin's shared storage or updates an existing one. ## Syntax ```js-nolint set(key, value) set(key, value, options) ``` ### Parameters - `key` - : A string representing the key in the key-value pair that you want to add or update. - `value` - : A string representing the value you want to add or update. - `options` {{optional_inline}} - : An options object containing the following properties: - `ignoreIfPresent` - : A boolean value. The value `true` causes the set operation to abort if a key-value pair with the specified `key` already exists. The default value `false` causes the set operation to overwrite the previous value. ### Return value A {{jsxref("Promise")}} that fulfills with `undefined`. ### Exceptions - The `Promise` rejects with a {{jsxref("TypeError")}} if: - The created entry was not successfully stored in the database due to shared storage not being available (for example it is disabled using a browser setting). - `key` and/or `value` exceed the browser-defined maximum length. - The calling site does not have the Shared Storage API included in a successful [privacy sandbox enrollment process](/en-US/docs/Web/Privacy/Privacy_sandbox/Enrollment). - In the case of {{domxref("WorkletSharedStorage")}}, the `Promise` rejects with a {{jsxref("TypeError")}} if the worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}. > **Note:** In the case of {{domxref("WindowSharedStorage")}}, if the `set()` operation doesn't successfully write to the database for a reason other than shared storage not being available, no error is thrown β€” the operation still fulfills with `undefined`. ## Examples ```js window.sharedStorage .set("ab-testing-group", "0", { ignoreIfPresent: true, }) .then(console.log("Set operation completed")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api/sharedstorage
data/mdn-content/files/en-us/web/api/sharedstorage/append/index.md
--- title: "SharedStorage: append() method" short-title: append() slug: Web/API/SharedStorage/append page-type: web-api-instance-method status: - experimental browser-compat: api.SharedStorage.append --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}} The **`append()`** method of the {{domxref("SharedStorage")}} interface appends a string to the value of an existing key-value pair in the current origin's shared storage. ## Syntax ```js-nolint append(key, value) ``` ### Parameters - `key` - : A string representing the key of the key-value pair to which you want to append a value. - `value` - : A string that you want to append to the existing value of the key-value pair. > **Note:** If the specified `key` isn't found in the shared storage, the `append()` operation is equivalent to {{domxref("SharedStorage.set", "set()")}}, that is, a new key-value pair with the specified `key` is added to the shared storage. ### Return value A {{jsxref("Promise")}} that fulfills with `undefined`. ### Exceptions - The `Promise` rejects with a {{jsxref("TypeError")}} if: - The appended entry was not successfully stored in the database due to shared storage not being available (for example it is disabled using a browser setting). - `key` and/or `value` exceed the browser-defined maximum length. - The calling site does not have the Shared Storage API included in a successful [privacy sandbox enrollment process](/en-US/docs/Web/Privacy/Privacy_sandbox/Enrollment). - In the case of {{domxref("WorkletSharedStorage")}}, the `Promise` rejects with a {{jsxref("TypeError")}} if the worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}. > **Note:** In the case of {{domxref("WindowSharedStorage")}}, if the `append()` operation doesn't successfully write to the database for a reason other than shared storage not being available, no error is thrown β€” the operation still fulfills with `undefined`. ## Examples ```js window.sharedStorage .append("integer-list", ",9") .then(console.log("Value appended to integer list")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api/sharedstorage
data/mdn-content/files/en-us/web/api/sharedstorage/clear/index.md
--- title: "SharedStorage: clear() method" short-title: clear() slug: Web/API/SharedStorage/clear page-type: web-api-instance-method status: - experimental browser-compat: api.SharedStorage.clear --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}} The **`clear()`** method of the {{domxref("SharedStorage")}} interface clears the current origin's shared storage, removing all data from it. ## Syntax ```js-nolint clear() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that fulfills with `undefined`. ### Exceptions - The `Promise` rejects with a {{jsxref("TypeError")}} if: - The database was not cleared successfully due to shared storage not being available (for example it is disabled using a browser setting). - The calling site does not have the Shared Storage API included in a successful [privacy sandbox enrollment process](/en-US/docs/Web/Privacy/Privacy_sandbox/Enrollment). - In the case of {{domxref("WorkletSharedStorage")}}, the `Promise` rejects with a {{jsxref("TypeError")}} if the worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}. > **Note:** In the case of {{domxref("WindowSharedStorage")}}, if the `clear()` operation doesn't successfully write to the database for a reason other than shared storage not being available, no error is thrown β€” the operation still fulfills with `undefined`. ## Examples ```js window.sharedStorage.clear().then(console.log("Shared storage cleared")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api/sharedstorage
data/mdn-content/files/en-us/web/api/sharedstorage/delete/index.md
--- title: "SharedStorage: delete() method" short-title: delete() slug: Web/API/SharedStorage/delete page-type: web-api-instance-method status: - experimental browser-compat: api.SharedStorage.delete --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}} The **`delete()`** method of the {{domxref("SharedStorage")}} interface deletes an existing key-value pair from the current origin's shared storage. ## Syntax ```js-nolint delete(key) ``` ### Parameters - `key` - : A string representing the key of the key-value pair you want to delete. ### Return value A {{jsxref("Promise")}} that fulfills with `undefined`. ### Exceptions - The `Promise` rejects with a {{jsxref("TypeError")}} if: - The database was not cleared successfully due to shared storage not being available (for example it is disabled using a browser setting). - `key` exceeds the browser-defined maximum length. - The calling site does not have the Shared Storage API included in a successful [privacy sandbox enrollment process](/en-US/docs/Web/Privacy/Privacy_sandbox/Enrollment). - In the case of {{domxref("WorkletSharedStorage")}}, the `Promise` rejects with a {{jsxref("TypeError")}} if: - The worklet module has not been added with {{domxref("Worklet.addModule", "SharedStorageWorklet.addModule()")}}. > **Note:** If the key-value pair doesn't exist in the shared storage, no error is thrown β€” the operation still fulfills with `undefined`. > **Note:** In the case of {{domxref("WindowSharedStorage")}}, if the `delete()` operation doesn't successfully write to the database for a reason other than shared storage not being available, no error is thrown β€” the operation still fulfills with `undefined`. ## Examples ```js window.sharedStorage .delete("ab-testing-group") .then(console.log("Value deleted")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfedisplacementmapelement/index.md
--- title: SVGFEDisplacementMapElement slug: Web/API/SVGFEDisplacementMapElement page-type: web-api-interface browser-compat: api.SVGFEDisplacementMapElement --- {{APIRef("SVG")}} The **`SVGFEDisplacementMapElement`** interface corresponds to the {{SVGElement("feDisplacementMap")}} element. {{InheritanceDiagram}} ## Constants <table class="no-markdown"> <tbody> <tr> <th>Name</th> <th>Value</th> <th>Description</th> </tr> <tr> <td><code>SVG_CHANNEL_UNKNOWN</code></td> <td>0</td> <td> The type is not one of predefined types. It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. </td> </tr> <tr> <td><code>SVG_CHANNEL_R</code></td> <td>1</td> <td>Corresponds to the <code>R</code> value.</td> </tr> <tr> <td><code>SVG_CHANNEL_G</code></td> <td>2</td> <td>Corresponds to the <code>G</code> value.</td> </tr> <tr> <td><code>SVG_CHANNEL_B</code></td> <td>3</td> <td>Corresponds to the <code>B</code> value.</td> </tr> <tr> <td><code>SVG_CHANNEL_A</code></td> <td>4</td> <td>Corresponds to the <code>A</code> value.</td> </tr> </tbody> </table> ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGFEDisplacementMapElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element. - {{domxref("SVGFEDisplacementMapElement.in1")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element. - {{domxref("SVGFEDisplacementMapElement.in2")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in2")}} attribute of the given element. - {{domxref("SVGFEDisplacementMapElement.result")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element. - {{domxref("SVGFEDisplacementMapElement.scale")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("scale")}} attribute of the given element. - {{domxref("SVGFEDisplacementMapElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element. - {{domxref("SVGFEDisplacementMapElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGFEDisplacementMapElement.xChannelSelector")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("xChannelSelect")}} attribute of the given element. It takes one of the `SVG_CHANNEL_*` constants defined on this interface. - {{domxref("SVGFEDisplacementMapElement.y")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element. - {{domxref("SVGFEDisplacementMapElement.yChannelSelector")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("yChannelSelect")}} attribute of the given element. It takes one of the `SVG_CHANNEL_*` constants defined on this interface. ## Instance methods _This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("feDisplacementMap")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfedropshadowelement/index.md
--- title: SVGFEDropShadowElement slug: Web/API/SVGFEDropShadowElement page-type: web-api-interface browser-compat: api.SVGFEDropShadowElement --- {{APIRef("SVG")}} The **`SVGFEDropShadowElement`** interface corresponds to the {{SVGElement("feDropShadow")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGFEDropShadowElement.dx")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("dx")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.dy")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("dy")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.in1")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.result")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.stdDeviationX")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the (possibly automatically computed) X component of the {{SVGAttr("stdDeviationX")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.stdDeviationY")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the (possibly automatically computed) Y component of the {{SVGAttr("stdDeviationY")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGFEDropShadowElement.y")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element. ## Instance methods _This interface also inherits methods of its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGFEDropShadowElement.setStdDeviation()")}} - : Sets the values for the `stdDeviation` attribute. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("feDropShadow")}}
0