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/htmlcollection
data/mdn-content/files/en-us/web/api/htmlcollection/length/index.md
--- title: "HTMLCollection: length property" short-title: length slug: Web/API/HTMLCollection/length page-type: web-api-instance-property browser-compat: api.HTMLCollection.length --- {{APIRef("DOM")}} The **`HTMLCollection.length`** property returns the number of items in a {{domxref("HTMLCollection")}}. ## Value An integer value representing the number of items in a `HTMLCollection`. ## Examples The `length` property is often useful in DOM programming. It's often used to test the length of a list, to see if it exists at all. It's also commonly used as the iterator in a `for` loop, as in this example. ```js // All the elements with the class ".test" in the document const items = document.getElementsByClassName("test"); // For each test item in the list, // append the entire element as a string of HTML let gross = ""; for (let i = 0; i < items.length; i++) { gross += items[i].innerHTML; } // gross is now all the HTML for the test elements ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlcollection
data/mdn-content/files/en-us/web/api/htmlcollection/item/index.md
--- title: "HTMLCollection: item() method" short-title: item() slug: Web/API/HTMLCollection/item page-type: web-api-instance-method browser-compat: api.HTMLCollection.item --- {{APIRef("HTML DOM")}} The {{domxref("HTMLCollection")}} method `item()` returns the element located at the specified offset into the collection. > **Note:** Because the contents of an `HTMLCollection` are > live, changes to the underlying DOM can and will cause the position of individual > elements in the collection to change, so the index value will not necessarily remain > constant for a given element. ## Syntax ```js-nolint item(index) ``` ### Parameters - `index` - : The position of the {{domxref("Element")}} to be returned. Elements appear in an `HTMLCollection` in the same order in which they appear in the document's source. ### Return value The {{domxref("Element")}} at the specified index, or `null` if `index` is less than zero or greater than or equal to the length property. ## Usage notes The `item()` method returns a numbered element from an `HTMLCollection`. In JavaScript, it is easier to treat the `HTMLCollection` as an array and to index it using array notation. See the [example](#examples) below. ## Examples ```js const images = document.images; // This is an HTMLCollection const img0 = images.item(0); // You can use the item() method this way const img1 = images[1]; // But this notation is easier and more common ``` ## Browser compatibility {{Compat}} ## See also - {{domxref("NodeList.item()")}}
0
data/mdn-content/files/en-us/web/api/htmlcollection
data/mdn-content/files/en-us/web/api/htmlcollection/nameditem/index.md
--- title: "HTMLCollection: namedItem() method" short-title: namedItem() slug: Web/API/HTMLCollection/namedItem page-type: web-api-instance-method browser-compat: api.HTMLCollection.namedItem --- {{APIRef("DOM")}} The **`namedItem()`** method of the {{domxref("HTMLCollection")}} interface returns the first {{domxref("Element")}} in the collection whose `id` or `name` attribute match the specified name, or `null` if no element matches. In JavaScript, using the array bracket syntax with a {{jsxref("String")}}, like `collection["value"]` is equivalent to `collection.namedItem("value")`. ## Syntax ```js-nolint namedItem(key) ``` ### Parameters - `key` is a string representing the value of the `id` or `name` attribute of the element we are looking for. ### Return value - `item` is the first {{domxref("Element")}} in the {{domxref("HTMLCollection")}} matching the _key_, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), if there are none. ## Example ### HTML ```html <div id="personal"> <span name="title">Dr.</span> <span name="firstname">Carina</span> <span name="lastname">Anand</span> <span id="degree">(MD)</span> </div> ``` ### JavaScript ```js const container = document.getElementById("personal"); // Returns the HTMLSpanElement with the name "title" if no such element exists null is returned const titleSpan = container.children.namedItem("title"); // The following variants return undefined instead of null if there's no element with a matching name or id const firstnameSpan = container.children["firstname"]; const lastnameSpan = container.children.lastname; // Returns the span element with the id "degree" const degreeSpan = container.children.namedItem("degree"); const output = document.createElement("div"); output.textContent = `Result: ${titleSpan.textContent} ${firstnameSpan.textContent} ${lastnameSpan.textContent} ${degreeSpan.textContent}`; container.insertAdjacentElement("afterend", output); ``` {{EmbedLiveSample("Example")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfespecularlightingelement/index.md
--- title: SVGFESpecularLightingElement slug: Web/API/SVGFESpecularLightingElement page-type: web-api-interface browser-compat: api.SVGFESpecularLightingElement --- {{APIRef("SVG")}} The **`SVGFESpecularLightingElement`** interface corresponds to the {{SVGElement("feSpecularLighting")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGFESpecularLightingElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.in1")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.kernelUnitLengthX")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the X component of the {{SVGAttr("kernelUnitLength")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.kernelUnitLengthY")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the Y component of the {{SVGAttr("kernelUnitLength")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.result")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.specularConstant")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("specularConstant")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.specularExponent")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("specularExponent")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.surfaceScale")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("surfaceScale")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGFESpecularLightingElement.y")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element. ## 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("feSpecularLighting")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/ndefreader/index.md
--- title: NDEFReader slug: Web/API/NDEFReader page-type: web-api-interface status: - experimental browser-compat: api.NDEFReader --- {{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}} The **`NDEFReader`** interface of the [Web NFC API](/en-US/docs/Web/API/Web_NFC_API) is used to read from and write data to compatible NFC devices, e.g. NFC tags supporting NDEF, when these devices are within the reader's magnetic induction field. {{InheritanceDiagram}} ## Constructor - {{DOMxRef("NDEFReader.NDEFReader", "NDEFReader()")}} {{Experimental_Inline}} - : Returns a new `NDEFReader` object. ## Instance methods _The `NDEFReader` interface inherits the methods of {{domxref("EventTarget")}}, its parent interface._ - {{DOMxRef("NDEFReader.scan", "NDEFReader.scan()")}} {{Experimental_Inline}} - : Activates a reading device and returns a {{jsxref("Promise")}} that either resolves when an NFC tag read operation is scheduled or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted. - {{DOMxRef("NDEFReader.write", "NDEFReader.write()")}} {{Experimental_Inline}} - : Attempts to write an NDEF message to a tag and returns a {{jsxref("Promise")}} that either resolves when a message has been written to the tag or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted. ## Events _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{DOMxRef("NDEFReader.reading_event", "reading")}} {{Experimental_Inline}} - : Fires when a new reading is available from compatible NFC devices. - {{DOMxRef("NDEFReader.readingerror_event", "readingerror")}} {{Experimental_Inline}} - : Fires when a tag is in proximity of a reading device, but cannot be read. ## Examples ### Handling initial reads while writing The example below shows how to coordinate between a common reading handler and one used specifically for a single write. In order to write, a tag needs to be found and read. This gives you the ability to check whether it is actually a tag that you want to write to. That's why it's recommended that you call `write()` from a reading event. ```js const ndef = new NDEFReader(); let ignoreRead = false; ndef.onreading = (event) => { if (ignoreRead) { return; // write pending, ignore read. } console.log("We read a tag, but not during pending write!"); }; function write(data) { ignoreRead = true; return new Promise((resolve, reject) => { ndef.addEventListener( "reading", (event) => { // Check if we want to write to this tag, or reject. ndef .write(data) .then(resolve, reject) .finally(() => (ignoreRead = false)); }, { once: true }, ); }); } await ndef.scan(); try { await write("Hello World"); console.log("We wrote to a tag!"); } catch (err) { console.error("Something went wrong", err); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/ndefreader
data/mdn-content/files/en-us/web/api/ndefreader/scan/index.md
--- title: "NDEFReader: scan() method" short-title: scan() slug: Web/API/NDEFReader/scan page-type: web-api-instance-method status: - experimental browser-compat: api.NDEFReader.scan --- {{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}} The `scan()` method of the {{DOMxRef("NDEFReader")}} interface activates a reading device and returns a {{jsxref("Promise")}} that either resolves when an NFC tag read operation is scheduled or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted. ## Syntax ```js-nolint scan(options) ``` ### Parameters - `options` {{optional_inline}} - : An object with the following properties: - `signal` - : An {{DOMxRef("AbortSignal")}} that allows cancelling this `scan()` operation. ### Return value A {{JSxRef("Promise")}} that resolves immediately after scheduling read operations for the NFC adapter. ## Exceptions This method doesn't throw exceptions; instead, it rejects the returned promise, passing a {{domxref("DOMException")}} whose `name` is one of the following: - `AbortError` {{domxref("DOMException")}} - : Returned if the scan operation was aborted with the {{DOMxRef("AbortSignal")}} passed in the `options` argument. - `InvalidStateError` {{domxref("DOMException")}} - : Returned if there's already an ongoing scan. - `NotAllowedError` {{domxref("DOMException")}} - : Returned if the permission for this operation was rejected. - `NotSupportedError` {{domxref("DOMException")}} - : Returned if there is no NFC adapter compatible with Web NFC or a connection cannot be established. ## Examples ### Handle scanning errors This example shows what happens when a scan promise rejects and `readingerror` is thrown. ```js const ndef = new NDEFReader(); ndef .scan() .then(() => { console.log("Scan started successfully."); ndef.onreadingerror = (event) => { console.log( "Error! Cannot read data from the NFC tag. Try a different one?", ); }; ndef.onreading = (event) => { console.log("NDEF message read."); }; }) .catch((error) => { console.log(`Error! Scan failed to start: ${error}.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/ndefreader
data/mdn-content/files/en-us/web/api/ndefreader/reading_event/index.md
--- title: "NDEFReader: reading event" short-title: reading slug: Web/API/NDEFReader/reading_event page-type: web-api-event status: - experimental browser-compat: api.NDEFReader.reading_event --- {{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}} The `reading` event of the {{DOMxRef("NDEFReader")}} interface is fired whenever a new reading is available from compatible NFC devices (e.g. NFC tags supporting NDEF) when these devices are within the reader's magnetic induction field. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("reading", (event) => {}); onreading = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples The following example shows how to process events using both the `onreading` and `onreadingerror` event handlers. ```js const ndef = new NDEFReader(); ndef .scan() .then(() => { console.log("Scan started successfully."); ndef.onreadingerror = (event) => { console.log( "Error! Cannot read data from the NFC tag. Try a different one?", ); }; ndef.onreading = (event) => { console.log("NDEF message read."); }; }) .catch((error) => { console.log(`Error! Scan failed to start: ${error}.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("NDEFReader.readingerror_event")}}
0
data/mdn-content/files/en-us/web/api/ndefreader
data/mdn-content/files/en-us/web/api/ndefreader/write/index.md
--- title: "NDEFReader: write() method" short-title: write() slug: Web/API/NDEFReader/write page-type: web-api-instance-method status: - experimental browser-compat: api.NDEFReader.write --- {{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}} The `write()` method of the {{DOMxRef("NDEFReader")}} interface attempts to write an NDEF message to a tag and returns a {{jsxref("Promise")}} that either resolves when a message has been written to the tag or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted. ## Syntax ```js-nolint write(message) write(message, options) ``` ### Parameters - `message` - : The message to be written, either a string object or literal, an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}}, or an array of records. A record has the following members: - `data` {{optional_inline}} - : Contains the data to be transmitted, a string object or literal, an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}}, or an array of nested records - `encoding` {{optional_inline}} - : A string specifying the record's encoding. - `id` {{optional_inline}} - : A developer-defined identifier for the record. - `lang` {{optional_inline}} - : A valid language tag according to {{RFC(5646, "Tags for Identifying Languages (also known as BCP 47)")}}. - `mediaType` {{optional_inline}} - : A valid [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types). - `recordType` - : A string indicating the type of data stored in `data`. It must be one of the following values: - `"absolute-url"` - : An absolute URL to the data. - `"empty"` - : An empty {{domxref("NDEFRecord")}}. - `"mime"` - : A valid [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types). - `"smart-poster"` - : A smart poster as defined by the [NDEF-SMARTPOSTER](https://w3c.github.io/web-nfc/#bib-ndef-smartposter) specification. - `"text"` - : Text as defined by the [NDEF-TEXT](https://w3c.github.io/web-nfc/#bib-ndef-text) specification. - `"unknown"` - : The record type is not known. - `"URL"` - : A URL as defined by the [NDEF-URI](https://w3c.github.io/web-nfc/#bib-ndef-uri) specification. - `options` {{optional_inline}} - : An object with the following properties: - `overwrite` - : A boolean value specifying whether or not existing records should be overwritten, if such exists. - `signal` {{optional_inline}} - : An {{DOMxRef("AbortSignal")}} that allows the current write operation to be canceled. ### Return value A {{JSxRef("Promise")}} that either resolves when a message has been written to the tag or rejects if a hardware or permission error is encountered. ## Exceptions This method doesn't throw exceptions; instead, it rejects the returned promise, passing a {{domxref("DOMException")}} whose `name` is one of the following: - `AbortError` - : The scan operation was aborted with the {{DOMxRef("AbortSignal")}} passed in the `options` argument. - `NotAllowedError` - : The permission for this operation was rejected or `overwrite` is `false` and there are already records on the tag. - `NotSupportedError` - : There is no NFC adapter compatible with Web NFC, or the available NFC adapter does not support pushing messages, or connection can not be established. - `NotReadableError` - : The UA is not allowed to access underlying NFC adapter (e.g., due to user preference). - `NetworkError` - : Transfer failed after it already started (e.g., the tag was removed from the reader). ## Examples ### Write a text string The following example shows how to write a string to an NFC tag and process any errors that occur. ```js const ndef = new NDEFReader(); ndef .write("Hello World") .then(() => { console.log("Message written."); }) .catch((error) => { console.log(`Write failed :-( try again: ${error}.`); }); ``` ### Write a URL The following example shows how to write a record object (described above) to an NFC tag and process any errors that occur. ```js const ndef = new NDEFReader(); try { await ndef.write({ records: [{ recordType: "url", data: "http://example.com/" }], }); } catch { console.log("Write failed :-( try again."); } ``` ### Scheduling a write with a timeout It's sometimes useful to set a time limit on a write operation. For example, you ask the user to touch a tag, but no tag is found within a certain amount of time, then you time out. ```js const ndef = new NDEFReader(); ndef.onreading = (event) => console.log("We read a tag!"); function write(data, { timeout } = {}) { return new Promise((resolve, reject) => { const ctlr = new AbortController(); ctlr.signal.onabort = () => reject("Time is up, bailing out!"); setTimeout(() => ctlr.abort(), timeout); ndef.addEventListener( "reading", (event) => { ndef.write(data, { signal: ctlr.signal }).then(resolve, reject); }, { once: true }, ); }); } await ndef.scan(); try { // Let's wait for 5 seconds only. await write("Hello World", { timeout: 5_000 }); } catch (err) { console.error("Something went wrong", err); } finally { console.log("We wrote to a tag!"); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/ndefreader
data/mdn-content/files/en-us/web/api/ndefreader/ndefreader/index.md
--- title: "NDEFReader: NDEFReader() constructor" short-title: NDEFReader() slug: Web/API/NDEFReader/NDEFReader page-type: web-api-constructor status: - experimental browser-compat: api.NDEFReader.NDEFReader --- {{SecureContext_Header}}{{APIRef("Web NFC API")}}{{SeeCompatTable}} The **`NDEFReader()`** constructor of the {{domxref("NDEFReader")}} interface returns a new `NDEFReader` object, which is used to read NDEF messages from compatible NFC devices, e.g. NDEF tags, within the reader's magnetic induction field. ## Syntax ```js-nolint new NDEFReader() ``` ### Parameters None. ### Return value A new {{DOMxRef("NDEFReader")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/ndefreader
data/mdn-content/files/en-us/web/api/ndefreader/readingerror_event/index.md
--- title: "NDEFReader: readingerror event" short-title: readingerror slug: Web/API/NDEFReader/readingerror_event page-type: web-api-event status: - experimental browser-compat: api.NDEFReader.readingerror_event --- {{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}} The `readingerror` event of the {{DOMxRef("NDEFReader")}} interface is fired whenever an error occurs during reading of NFC tags, e.g. when tags leave the reader's magnetic induction field. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("readingerror", (event) => {}); onreadingerror = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples The following example shows how to process events using both the `onreading` and `onreadingerror` event handlers. ```js const ndef = new NDEFReader(); ndef .scan() .then(() => { console.log("Scan started successfully."); ndef.onreadingerror = (event) => { console.log( "Error! Cannot read data from the NFC tag. Try a different one?", ); }; ndef.onreading = (event) => { console.log("NDEF message read."); }; }) .catch((error) => { console.log(`Error! Scan failed to start: ${error}.`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svggraphicselement/index.md
--- title: SVGGraphicsElement slug: Web/API/SVGGraphicsElement page-type: web-api-interface browser-compat: api.SVGGraphicsElement --- {{APIRef("SVG")}} The **`SVGGraphicsElement`** interface represents SVG elements whose primary purpose is to directly render graphics into a group. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGGraphicsElement.requiredExtensions")}} {{ReadOnlyInline}} - : An {{domxref("SVGStringList")}} reflecting the {{SVGAttr("requiredExtensions")}} attribute of the given element. - {{domxref("SVGGraphicsElement.systemLanguage")}} {{ReadOnlyInline}} - : An {{domxref("SVGStringList")}} reflecting the {{SVGAttr("systemLanguage")}} attribute of the given element. - {{domxref("SVGGraphicsElement.transform")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedTransformList")}} reflecting the computed value of the {{cssxref("transform")}} property and its corresponding {{SVGAttr("transform")}} attribute of the given element. ## Instance methods _This interface also inherits methods from its parent, {{domxref("SVGElement")}}._ - {{domxref("SVGGraphicsElement.getBBox()")}} - : Returns a {{domxref("DOMRect")}} representing the computed bounding box of the current element. - {{domxref("SVGGraphicsElement.getCTM()")}} - : Returns a {{domxref("DOMMatrix")}} representing the matrix that transforms the current element's coordinate system to its SVG viewport's coordinate system. - {{domxref("SVGGraphicsElement.getScreenCTM()")}} - : Returns a {{domxref("DOMMatrix")}} representing the matrix that transforms the current element's coordinate system to the coordinate system of the SVG viewport for the SVG document fragment. ## Events Listen to these events using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) or by assigning an event listener to the equivalent `on...` handler property. - [`copy`](/en-US/docs/Web/API/SVGGraphicsElement/copy_event) - : Fired when the user initiates a copy action through the browser's user interface. - [`cut`](/en-US/docs/Web/API/SVGGraphicsElement/cut_event) - : Fired when the user has initiated a "cut" action through the browser's user interface. - [`paste`](/en-US/docs/Web/API/SVGGraphicsElement/paste_event) - : Fires when the user has initiated a "paste" action through the browser's user interface. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/svggraphicselement
data/mdn-content/files/en-us/web/api/svggraphicselement/copy_event/index.md
--- title: "SVGGraphicsElement: copy event" short-title: copy slug: Web/API/SVGGraphicsElement/copy_event page-type: web-api-event browser-compat: api.Element.copy_event --- {{APIRef("SVG")}} The **`copy`** event fires on {{domxref("SVGGraphicsElement", "SVGGraphicsElements")}} when the user initiates a copy action through the browser's user interface. The event's default action is to copy the selection (if any) to the clipboard. A handler for this event can _modify_ the clipboard contents by calling {{domxref("DataTransfer.setData", "setData(format, data)")}} on the event's {{domxref("ClipboardEvent.clipboardData")}} property, and cancelling the event's default action using [`event.preventDefault()`](/en-US/docs/Web/API/Event/preventDefault). However, the handler cannot _read_ the clipboard data. It's possible to construct and dispatch a [synthetic](/en-US/docs/Web/Events/Creating_and_triggering_events) `copy` event, but this will not affect the system clipboard. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("copy", (event) => {}); oncopy = (event) => {}; ``` ## Event type A {{domxref("ClipboardEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ClipboardEvent")}} ## Example ### HTML ```html <?xml version="1.0" encoding="UTF-8"?> <svg viewBox="0 0 100 30" width="600" height="320" xmlns="http://www.w3.org/2000/svg"> <text x="5" y="10" id="text-to-copy">Copy this text</text> <foreignObject x="5" y="20" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" placeholder="Paste it here" /> </foreignObject> </svg> ``` ### CSS ```css input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; } ``` ### JavaScript ```js document.querySelector("text").addEventListener("copy", (evt) => { evt.clipboardData.setData( "text/plain", document.getSelection().toString().toUpperCase(), ); evt.preventDefault(); }); ``` ### Result {{EmbedLiveSample("Example", "620", "340")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: [`cut`](/en-US/docs/Web/API/SVGGraphicsElement/cut_event), [`paste`](/en-US/docs/Web/API/SVGGraphicsElement/paste_event) - This event on HTML {{domxref("Element")}} targets: [`copy`](/en-US/docs/Web/API/Element/copy_event) - This event on {{domxref("Document")}} targets: [`copy`](/en-US/docs/Web/API/Document/copy_event) - This event on {{domxref("Window")}} targets: [`copy`](/en-US/docs/Web/API/Window/copy_event)
0
data/mdn-content/files/en-us/web/api/svggraphicselement
data/mdn-content/files/en-us/web/api/svggraphicselement/cut_event/index.md
--- title: "SVGGraphicsElement: cut event" short-title: cut slug: Web/API/SVGGraphicsElement/cut_event page-type: web-api-event browser-compat: api.Element.cut_event --- {{APIRef("SVG")}} The **`cut`** event is fired on an {{domxref("SVGGraphicsElement")}} when the user has initiated a "cut" action through the browser's user interface. If the user attempts a cut action on uneditable content, the `cut` event still fires but the event object contains no data. The event's default action is to copy the current selection (if any) to the system clipboard and remove it from the document. A handler for this event can _modify_ the clipboard contents by calling [`setData(format, data)`](/en-US/docs/Web/API/DataTransfer/setData) on the event's [`ClipboardEvent.clipboardData`](/en-US/docs/Web/API/ClipboardEvent/clipboardData) property, and cancelling the default action using [`event.preventDefault()`](/en-US/docs/Web/API/Event/preventDefault). Note though that cancelling the default action will also prevent the document from being updated. So an event handler which wants to emulate the default action for "cut" while modifying the clipboard must also manually remove the selection from the document. The handler cannot _read_ the clipboard data. It's possible to construct and dispatch a [synthetic](/en-US/docs/Web/Events/Creating_and_triggering_events) `cut` event, but this will not affect the system clipboard or the document's contents. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("cut", (event) => {}); oncut = (event) => {}; ``` ## Event type A {{domxref("ClipboardEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ClipboardEvent")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: [`copy`](/en-US/docs/Web/API/SVGGraphicsElement/copy_event), [`paste`](/en-US/docs/Web/API/SVGGraphicsElement/paste_event) - This event on HTML {{domxref("Element")}} targets: [`cut`](/en-US/docs/Web/API/Element/cut_event) - This event on {{domxref("Document")}} targets: [`cut`](/en-US/docs/Web/API/Document/cut_event) - This event on {{domxref("Window")}} targets: [`cut`](/en-US/docs/Web/API/Window/cut_event)
0
data/mdn-content/files/en-us/web/api/svggraphicselement
data/mdn-content/files/en-us/web/api/svggraphicselement/getbbox/index.md
--- title: "SVGGraphicsElement: getBBox() method" short-title: getBBox() slug: Web/API/SVGGraphicsElement/getBBox page-type: web-api-instance-method browser-compat: api.SVGGraphicsElement.getBBox --- {{APIRef("SVG")}} The **`SVGGraphicsElement.getBBox()`** method allows us to determine the coordinates of the smallest rectangle in which the object fits. The coordinates returned are with respect to the current SVG space (after the application of all geometry attributes on all the elements contained in the target element). > **Note:** `getBBox()` must return the actual bounding box at > the time the method was called—even in case the element has not yet been rendered. It > also does not account for any transformation applied to the element or its parents. > **Note:** `getBBox` returns different values than > {{domxref("Element.getBoundingClientRect()", "getBoundingClientRect()")}}, as the > latter returns value relative to the viewport ## Syntax ```js-nolint getBBox() getBBox(options) ``` ### Parameters - `options` {{experimental_inline}} {{optional_inline}} - : An options dictionary used to control which parts of the element are included in the bounding box. The available options are: - `fill` - : A boolean value indicating that the fill should be included in the bounding box, defaults to `true`. - `stroke` - : A boolean value indicating that the stroke should be included in the bounding box, defaults to `false`. - `markers` - : A boolean value indicating that the markers should be included in the bounding box, defaults to `false`. - `clipped` - : A boolean value indicating that the bounding box should be clipped, defaults to `false`. ### Return value The returned value is a {{domxref("SVGRect")}} object, which defines the bounding box. This value is irrespective of any transformation attribute applied to it or the parent elements. ## Examples ### HTML ```html <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <g id="group_text_1"> <text x="5" y="16" transform="scale(2, 2)">Hello World!</text> <text x="8" y="32" transform="translate(0 20) scale(1.25 1)"> Hello World Again! </text> </g> <!-- Shows BBox in green --> <rect id="rect_1" stroke="#00ff00" stroke-width="3" fill="none"></rect> <!-- Shows BoundingClientRect in red --> <rect id="rect_2" stroke="#ff0000" stroke-width="3" fill="none"></rect> </svg> ``` ### JavaScript ```js const rectBBox = document.querySelector("#rect_1"); const rectBoundingClientRect = document.querySelector("#rect_2"); const groupElement = document.querySelector("#group_text_1"); const bboxGroup = groupElement.getBBox(); rectBBox.setAttribute("x", bboxGroup.x); rectBBox.setAttribute("y", bboxGroup.y); rectBBox.setAttribute("width", bboxGroup.width); rectBBox.setAttribute("height", bboxGroup.height); const boundingClientRectGroup = groupElement.getBoundingClientRect(); rectBoundingClientRect.setAttribute("x", boundingClientRectGroup.x); rectBoundingClientRect.setAttribute("y", boundingClientRectGroup.y); rectBoundingClientRect.setAttribute("width", boundingClientRectGroup.width); rectBoundingClientRect.setAttribute("height", boundingClientRectGroup.height); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [getBBox in SVG Primer](https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#getBBox)
0
data/mdn-content/files/en-us/web/api/svggraphicselement
data/mdn-content/files/en-us/web/api/svggraphicselement/paste_event/index.md
--- title: "SVGGraphicsElement: paste event" short-title: paste slug: Web/API/SVGGraphicsElement/paste_event page-type: web-api-event browser-compat: api.Element.paste_event --- {{APIRef("SVG")}} The **`paste`** event is fired on an {{domxref("SVGGraphicsElement")}} when the user has initiated a "paste" action through the browser's user interface. If the cursor is in an editable context (for example, in a {{HTMLElement("textarea")}} or an element with [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) attribute set to `true`) then the default action is to insert the contents of the clipboard into the document at the cursor position. A handler for this event can access the clipboard contents by calling {{domxref("DataTransfer/getData", "getData()")}} on the event's `clipboardData` property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using {{domxref("Event/preventDefault", "event.preventDefault()")}}, and then insert its desired data manually. It's possible to construct and dispatch a [synthetic](/en-US/docs/Web/Events/Creating_and_triggering_events) `paste` event, but this will not affect the document's contents. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("paste", (event) => {}); onpaste = (event) => {}; ``` ## Event type A {{domxref("ClipboardEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ClipboardEvent")}} ## Example ### HTML ```html <?xml version="1.0" encoding="UTF-8"?> <svg viewBox="0 0 140 30" width="600" height="320" xmlns="http://www.w3.org/2000/svg"> <foreignObject x="5" y="-10" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" value="Copy this text" /> </foreignObject> <text x="5" y="30" id="element-to-paste-text" tabindex="1"> Paste it here </text> </svg> ``` ### CSS ```css input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; } ``` ### JavaScript ```js document .getElementById("element-to-paste-text") .addEventListener("paste", (evt) => { evt.target.textContent = evt.clipboardData .getData("text/plain") .toUpperCase(); evt.preventDefault(); }); ``` ### Result {{EmbedLiveSample("Example", "620", "340")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: [`cut`](/en-US/docs/Web/API/SVGGraphicsElement/cut_event), [`copy`](/en-US/docs/Web/API/SVGGraphicsElement/copy_event) - This event on HTML {{domxref("Element")}} targets: [`paste`](/en-US/docs/Web/API/Element/paste_event) - This event on {{domxref("Document")}} targets: [`paste`](/en-US/docs/Web/API/Document/paste_event) - This event on {{domxref("Window")}} targets: [`paste`](/en-US/docs/Web/API/Window/paste_event)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/windowclient/index.md
--- title: WindowClient slug: Web/API/WindowClient page-type: web-api-interface browser-compat: api.WindowClient --- {{APIRef("Service Workers API")}} The `WindowClient` interface of the [ServiceWorker API](/en-US/docs/Web/API/Service_Worker_API) represents the scope of a service worker client that is a document in a browsing context, controlled by an active worker. The service worker client independently selects and uses a service worker for its own loading and sub-resources. {{InheritanceDiagram}} ## Instance methods _`WindowClient` inherits methods from its parent interface, {{domxref("Client")}}._ - {{domxref("WindowClient.focus()")}} - : Gives user input focus to the current client. - {{domxref("WindowClient.navigate()")}} - : Loads a specified URL into a controlled client page. ## Instance properties _`WindowClient` inherits properties from its parent interface, {{domxref("Client")}}._ - {{domxref("WindowClient.ancestorOrigins")}} {{ReadOnlyInline}} {{experimental_inline}} - : An array of strings that indicates the ancestor origins of the browsing context represented by this `WindowClient` in reverse order. - {{domxref("WindowClient.focused")}} {{ReadOnlyInline}} - : A boolean that indicates whether the current client has focus. - {{domxref("WindowClient.visibilityState")}} {{ReadOnlyInline}} - : Indicates the visibility of the current client. This value can be one of `"hidden"`, `"visible"`, or `"prerender"`. ## Example ```js self.addEventListener("notificationclick", (event) => { console.log("On notification click: ", event.notification.tag); event.notification.close(); // This looks to see if the current is already open and // focuses if it is event.waitUntil( clients .matchAll({ type: "window", }) .then((clientList) => { for (const client of clientList) { if (client.url === "/" && "focus" in client) { client.focus(); break; } } if (clients.openWindow) return clients.openWindow("/"); }), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) - [Channel Messaging API](/en-US/docs/Web/API/Channel_Messaging_API)
0
data/mdn-content/files/en-us/web/api/windowclient
data/mdn-content/files/en-us/web/api/windowclient/focus/index.md
--- title: "WindowClient: focus() method" short-title: focus() slug: Web/API/WindowClient/focus page-type: web-api-instance-method browser-compat: api.WindowClient.focus --- {{APIRef("Service Workers API")}} The **`focus()`** method of the {{domxref("WindowClient")}} interface gives user input focus to the current client and returns a {{jsxref("Promise")}} that resolves to the existing {{domxref("WindowClient")}}. ## Syntax ```js-nolint focus() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves to the existing {{domxref("WindowClient")}}. ### Exceptions - `InvalidAccessError` {{domxref("DOMException")}} - : The promise is rejected with this exception if none of the windows in the app's origin have [transient activation](/en-US/docs/Web/Security/User_activation). ## Security requirements - At least one window in the app's origin must have [transient activation](/en-US/docs/Web/Security/User_activation). ## Examples ```js self.addEventListener("notificationclick", (event) => { console.log("On notification click: ", event.notification.tag); event.notification.close(); // This looks to see if the current is already open and // focuses if it is event.waitUntil( clients .matchAll({ type: "window", }) .then((clientList) => { for (const client of clientList) { if (client.url === "/" && "focus" in client) return client.focus(); } if (clients.openWindow) return clients.openWindow("/"); }), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/windowclient
data/mdn-content/files/en-us/web/api/windowclient/focused/index.md
--- title: "WindowClient: focused property" short-title: focused slug: Web/API/WindowClient/focused page-type: web-api-instance-property browser-compat: api.WindowClient.focused --- {{APIRef("Service Workers API")}} The **`focused`** read-only property of the {{domxref("WindowClient")}} interface is a boolean value that indicates whether the current client has focus. ## Value A boolean value. ## Examples ```js self.addEventListener("notificationclick", (event) => { console.log("On notification click: ", event.notification.tag); event.notification.close(); // This looks to see if the current is already open and // focuses if it is event.waitUntil( clients .matchAll({ type: "window", }) .then((clientList) => { for (const client of clientList) { if (client.url === "/" && "focus" in client) { if (!client.focused) return client.focus(); } } if (clients.openWindow) return clients.openWindow("/"); }), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/windowclient
data/mdn-content/files/en-us/web/api/windowclient/ancestororigins/index.md
--- title: "WindowClient: ancestorOrigins property" short-title: ancestorOrigins slug: Web/API/WindowClient/ancestorOrigins page-type: web-api-instance-property status: - experimental browser-compat: api.WindowClient.ancestorOrigins --- {{APIRef("Service Workers API")}}{{SeeCompatTable}} The **`ancestorOrigins`** read-only property of the {{domxref("WindowClient")}} interface is an array of strings listing the origins of all ancestors of the browsing context represented by this `WindowClient` in reverse order. The first element in the array is the origin of this window's parent, and the last element is the origin of the top-level browsing context. If this window is itself a top-level browsing context, then `ancestorOrigins` is an empty array. ## Value An array of strings. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/windowclient
data/mdn-content/files/en-us/web/api/windowclient/visibilitystate/index.md
--- title: "WindowClient: visibilityState property" short-title: visibilityState slug: Web/API/WindowClient/visibilityState page-type: web-api-instance-property browser-compat: api.WindowClient.visibilityState --- {{APIRef("Service Workers API")}} The **`visibilityState`** read-only property of the {{domxref("WindowClient")}} interface indicates the visibility of the current client. This value can be one of `"hidden"`, `"visible"`, or `"prerender"`. ## Value A string (See {{domxref("Document.visibilityState")}} for values). ## Examples ```js event.waitUntil( clients .matchAll({ type: "window", }) .then((clientList) => { for (const client of clientList) { if (client.url === "/" && "focus" in client) { if (client.visibilityState === "hidden") return client.focus(); } } if (clients.openWindow) { return clients.openWindow("/"); } }), ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/windowclient
data/mdn-content/files/en-us/web/api/windowclient/navigate/index.md
--- title: "WindowClient: navigate() method" short-title: navigate() slug: Web/API/WindowClient/navigate page-type: web-api-instance-method browser-compat: api.WindowClient.navigate --- {{APIRef("Service Workers API")}} The **`navigate()`** method of the {{domxref("WindowClient")}} interface loads a specified URL into a controlled client page then returns a {{jsxref("Promise")}} that resolves to the existing {{domxref("WindowClient")}}. ## Syntax ```js-nolint navigate(url) ``` ### Parameters - `url` - : The location to navigate to. ### Return value A {{jsxref("Promise")}} that resolves to the existing {{domxref("WindowClient")}} if the URL is from the same origin as the service worker, or {{jsxref("Operators/null", "null")}} otherwise. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssfontfeaturevaluesrule/index.md
--- title: CSSFontFeatureValuesRule slug: Web/API/CSSFontFeatureValuesRule page-type: web-api-interface browser-compat: api.CSSFontFeatureValuesRule --- {{APIRef("CSSOM")}} The **`CSSFontFeatureValuesRule`** interface represents an {{cssxref("@font-feature-values")}} [at-rule](/en-US/docs/Web/CSS/At-rule), letting developers assign for each font face a common name to specify features indices to be used in {{cssxref("font-variant-alternates")}}. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its ancestor {{domxref("CSSRule")}}._ - {{domxref("CSSFontFeatureValuesRule.fontFamily")}} - : A string that identifies the font family this rule applies to. ## Instance methods _Inherits methods from its ancestor {{domxref("CSSRule")}}._ ## Examples ### Read font family In this example, we declare two {{cssxref("@font-feature-values")}} one for the _Font One_ font family, and the other for _Font Two_. We then use the CSSOM to read these font families, displaying them into the log. #### HTML ```html <pre id="log"></pre> ``` #### CSS ```css /* At-rule for "nice-style" in Font One */ @font-feature-values Font One { @styleset { nice-style: 12; } } /* At-rule for "nice-style" in Font Two */ @font-feature-values Font Two { @styleset { nice-style: 4; } } /* Apply the at-rules with a single declaration */ .nice-look { font-variant-alternates: styleset(nice-style); } ``` #### JavaScript ```js const log = document.getElementById("log"); const rules = document.styleSheets[document.styleSheets.length - 1].cssRules; const fontOne = rules[0]; // A CSSFontFeatureValuesRule log.textContent = `The 1st '@font-feature-values' family: "${fontOne.fontFamily}".\n`; const fontTwo = rules[1]; // Another CSSFontFeatureValuesRule log.textContent += `The 2nd '@font-feature-values' family: "${fontTwo.fontFamily}".`; ``` {{EmbedLiveSample("read_font_family", "100%", "75px")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{cssxref("@font-feature-values")}}
0
data/mdn-content/files/en-us/web/api/cssfontfeaturevaluesrule
data/mdn-content/files/en-us/web/api/cssfontfeaturevaluesrule/fontfamily/index.md
--- title: "CSSFontFeatureValuesRule: fontFamily property" short-title: fontFamily slug: Web/API/CSSFontFeatureValuesRule/fontFamily page-type: web-api-instance-property browser-compat: api.CSSFontFeatureValuesRule.fontFamily --- {{ APIRef("CSSOM") }} The **`fontFamily`** property of the {{domxref("CSSConditionRule")}} interface represents the name of the font family it applies to. ## Value A string. ## Examples ### Read font family In this example, we declare two {{cssxref("@font-feature-values")}} one for the _Font One_ font family, and the other for _Font Two_. We then use the CSSOM to read these font families, displaying them into the log. ```html <pre id="log"></pre> ``` #### CSS ```css /* At-rule for "nice-style" in Font One */ @font-feature-values Font One { @styleset { nice-style: 12; } } /* At-rule for "nice-style" in Font Two */ @font-feature-values Font Two { @styleset { nice-style: 4; } } /* Apply the at-rules with a single declaration */ .nice-look { font-variant-alternates: styleset(nice-style); } ``` #### JavaScript ```js const log = document.getElementById("log"); const rules = document.styleSheets[document.styleSheets.length - 1].cssRules; const fontOne = rules[0]; // A CSSFontFeatureValuesRule log.textContent = `The 1st '@font-feature-values' family: "${fontOne.fontFamily}".\n`; const fontTwo = rules[1]; // Another CSSFontFeatureValuesRule log.textContent += `The 2nd '@font-feature-values' family: "${fontTwo.fontFamily}".`; ``` {{EmbedLiveSample("read_font_family", "100%", "75px")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also -
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/domstringlist/index.md
--- title: DOMStringList slug: Web/API/DOMStringList page-type: web-api-interface browser-compat: api.DOMStringList --- {{APIRef("DOM")}} The **`DOMStringList`** interface is a legacy type returned by some APIs and represents a non-modifiable list of strings (`DOMString`). Modern APIs use {{jsxref("Array")}} objects (in WebIDL: `sequence<DOMString>`) instead. This interface is used in [IndexedDB](/en-US/docs/Web/API/IndexedDB_API) and in the {{domxref("Location")}} API: - {{domxref("IDBDatabase.objectStoreNames")}} - {{domxref("IDBObjectStore.indexNames")}} - {{domxref("Location.ancestorOrigins")}} ## Instance properties - {{domxref("DOMStringList.length")}} {{ReadOnlyInline}} - : Returns the size of the list. ## Instance methods - {{domxref("DOMStringList.item()")}} - : Returns a string from the list with the given index. - {{domxref("DOMStringList.contains()")}} - : Returns a boolean indicating whether the given string is in the list. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/domstringlist
data/mdn-content/files/en-us/web/api/domstringlist/length/index.md
--- title: "DOMStringList: length property" short-title: length slug: Web/API/DOMStringList/length page-type: web-api-instance-property browser-compat: api.DOMStringList.length --- {{APIRef("DOM")}} The read-only **`length`** property indicates the number of strings in the {{domxref("DOMStringList")}}. ## Value A {{jsxref("Number")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/domstringlist
data/mdn-content/files/en-us/web/api/domstringlist/item/index.md
--- title: "DOMStringList: item() method" short-title: item() slug: Web/API/DOMStringList/item page-type: web-api-instance-method browser-compat: api.DOMStringList.item --- {{APIRef("DOM")}} The **`item()`** method returns a string from a [`DOMStringList`](/en-US/docs/Web/API/DOMStringList) by index. ## Syntax ```js-nolint item(index) ``` JavaScript also offers an array-like bracketed syntax for obtaining an item from a `DOMStringList` by index: ```js list[index]; ``` ### Parameters - `index` - : the index of the string to get. The index is zero-based. ### Return value The string at the index position in the `DOMStringList`; otherwise `null` if the provided index is out of range. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if no argument is provided. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/domstringlist
data/mdn-content/files/en-us/web/api/domstringlist/contains/index.md
--- title: "DOMStringList: contains() method" short-title: contains() slug: Web/API/DOMStringList/contains page-type: web-api-instance-method browser-compat: api.DOMStringList.contains --- {{APIRef("DOM")}} The **`contains()`** method returns a boolean indicating whether the given string is in the list. ## Syntax ```js-nolint contains(string) ``` ### Parameters - `string` - : A string you want to check for the existence of in the list. ### Return value A boolean indicating whether the given string is in the list. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if no argument is provided. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlpictureelement/index.md
--- title: HTMLPictureElement slug: Web/API/HTMLPictureElement page-type: web-api-interface browser-compat: api.HTMLPictureElement --- {{APIRef("HTML DOM")}} The **`HTMLPictureElement`** interface represents a {{HTMLElement("picture")}} HTML element. It doesn't implement specific properties or methods. {{InheritanceDiagram}} ## Instance properties _No specific property, but inherits properties from its parent, {{domxref("HTMLElement")}}._ ## Instance methods _No specific method, but inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("picture")}} HTML element that implements it. - The {{domxref("HTMLImageElement")}} and {{domxref("HTMLSourceElement")}} interfaces, often used in conjunction with a {{HTMLElement("picture")}} element.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrviewport/index.md
--- title: XRViewport slug: Web/API/XRViewport page-type: web-api-interface browser-compat: api.XRViewport --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The WebXR Device API's **`XRViewport`** interface provides properties used to describe the size and position of the current viewport within the {{domxref("XRWebGLLayer")}} being used to render the 3D scene. ## Instance properties - {{domxref("XRViewport.height", "height")}} {{ReadOnlyInline}} - : The height, in pixels, of the viewport. - {{domxref("XRViewport.width", "width")}} {{ReadOnlyInline}} - : The width, in pixels, of the viewport. - {{domxref("XRViewport.x", "x")}} {{ReadOnlyInline}} - : The offset from the origin of the destination graphics surface (typically a {{domxref("XRWebGLLayer")}}) to the left edge of the viewport, in pixels. - {{domxref("XRViewport.y", "y")}} {{ReadOnlyInline}} - : The offset from the origin of the viewport to the bottom edge of the viewport; WebGL's coordinate system places (0, 0) at the bottom left corner of the surface. ## Usage notes Currently, the only type of surface available is the {{domxref("XRWebGLLayer")}}. The precise orientation of the coordinate system may vary with other surface types, but in WebGL, the origin (0, 0) is located at the bottom-left corner of the surface. Thus the values specified in an `XRViewport` define a rectangle whose bottom-left corner is at (`x`, `y`) and which extends `width` pixels toward the left and `height` pixels upward. These values may be passed directly into the {{domxref("WebGLRenderingContext.viewport()")}} method: ```js const xrViewport = xrWebGLLayer.getViewport(xrView); gl.viewport(xrViewport.x, xrViewport.y, xrViewport.width, xrViewport.height); ``` ## Example This example sets up an animation frame callback using {{domxref("XRSession.requestAnimationFrame", "requestAnimationFrame()")}}. After initial setup, it iterates over each of the views within the viewer's pose, configuring the viewport as dictated by the {{domxref("XRWebGLLayer")}}. ```js xrSession.requestAnimationFrame((time, xrFrame) => { const viewerPose = xrFrame.getViewerPose(xrReferenceSpace); gl.bindFramebuffer(xrWebGLLayer.framebuffer); for (const xrView of viewerPose.views) { const xrViewport = xrWebGLLayer.getViewport(xrView); gl.viewport( xrViewport.x, xrViewport.y, xrViewport.width, xrViewport.height, ); // Now we can use WebGL to draw into a viewport matching // the viewer's needs } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrviewport
data/mdn-content/files/en-us/web/api/xrviewport/y/index.md
--- title: "XRViewport: y property" short-title: "y" slug: Web/API/XRViewport/y page-type: web-api-instance-property browser-compat: api.XRViewport.y --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The read-only {{domxref("XRViewport")}} interface's **`y`** property indicates the offset from the bottom edge of the destination surface (typically a {{domxref("XRWebGLLayer")}} to the bottom edge of the viewport within the surface into which WebXR content is to be rendered. The viewport's {{domxref("XRViewport.x", "x")}} property identifies the `x` component of the origin, and its is given by the {{domxref("XRViewPort.width", "width")}} and {{domxref("XRViewport.height", "height")}} properties. ## Value The offset from the bottom edge of the rendering surface to the bottom edge of the viewport, in pixels. > **Note:** Although other web APIs typically consider the `y` > axis to begin at the top and grow larger progressing downward, WebGL reverses this, > with `y` growing larger as it goes upward on the screen. ## Examples See the main {{domxref("XRViewport")}} page for examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrviewport
data/mdn-content/files/en-us/web/api/xrviewport/x/index.md
--- title: "XRViewport: x property" short-title: x slug: Web/API/XRViewport/x page-type: web-api-instance-property browser-compat: api.XRViewport.x --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The read-only {{domxref("XRViewport")}} interface's **`x`** property indicates the offset from the left edge of the destination surface (typically a {{domxref("XRWebGLLayer")}} to the left edge of the viewport within the surface into which WebXR content is to be rendered. The viewport's {{domxref("XRViewport.y", "y")}} property identifies the `y` component of the origin, and its is given by the {{domxref("XRViewPort.width", "width")}} and {{domxref("XRViewport.height", "height")}} properties. ## Value The offset from the left edge of the rendering surface to the left edge of the viewport, in pixels. ## Examples See the main {{domxref("XRViewport")}} page for examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrviewport
data/mdn-content/files/en-us/web/api/xrviewport/width/index.md
--- title: "XRViewport: width property" short-title: width slug: Web/API/XRViewport/width page-type: web-api-instance-property browser-compat: api.XRViewport.width --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The read-only {{domxref("XRViewport")}} property **`width`** specifies the width of the viewport, in pixels, onto the drawing surface the 3D scene is to be rendered into. This is defined using this property along with the viewport's {{domxref("XRViewport.height", "height")}} and its origin given by its properties {{domxref("XRViewport.x", "x")}} and {{domxref("XRViewport.y", "y")}}. ## Value The viewport's width in pixels. ## Examples See the main {{domxref("XRViewport")}} page for examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xrviewport
data/mdn-content/files/en-us/web/api/xrviewport/height/index.md
--- title: "XRViewport: height property" short-title: height slug: Web/API/XRViewport/height page-type: web-api-instance-property browser-compat: api.XRViewport.height --- {{APIRef("WebXR Device API")}}{{SecureContext_Header}} The read-only {{domxref("XRViewport")}} property **`height`** specifies the height, in pixels, of the viewport onto the drawing surface within which the WebXR view is to be rendered. Along with {{domxref("XRViewport.width", "width")}} and the origin point given by {{domxref("XRViewport.x", "x")}} and {{domxref("XRViewport.y", "y")}}, this defines the area within which rendered content will be drawn. ## Value The viewport's height in pixels. ## Examples See the main {{domxref("XRViewport")}} page for examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/positionsensorvrdevice/index.md
--- title: PositionSensorVRDevice slug: Web/API/PositionSensorVRDevice page-type: web-api-interface status: - deprecated - non-standard browser-compat: api.PositionSensorVRDevice --- {{APIRef("WebVR API")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`PositionSensorVRDevice`** interface of the [WebVR API](/en-US/docs/Web/API/WebVR_API) represents VR hardware's position sensor. You can access information such as the current position and orientation of the sensor in relation to the head mounted display through the {{domxref("PositionSensorVRDevice.getState()")}} method. ## Instance methods - {{domxref("PositionSensorVRDevice.getState()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns the current state of the position sensor for the current frame (e.g. within the current {{domxref("window.requestAnimationFrame")}} callback) or for the previous frame, contained with a {{domxref("VRPose")}} object. This is the method you'd normally want to use, versus `getImmediateState()`. - {{domxref("PositionSensorVRDevice.getImmediateState()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : Returns the current instantaneous position sensor state. This is intended to only be used rarely, for certain special uses, for example sampling the immediate position of a hand orientation sensor — or at least it will be, in the future. - {{domxref("PositionSensorVRDevice.resetSensor()")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : _Can be used to reset the sensor if desired, returning the_ position and orientation values to zero. ## Instance properties _This interface doesn't define any properties of its own, but it does inherit the properties of its parent interface, {{domxref("VRDisplay")}}._ - {{domxref("VRDisplay.displayId")}} {{ReadOnlyInline}} - : Returns the ID for this specific `VRDevice`. The ID shouldn't change across browser restarts, allowing configuration data to be saved based on it. - {{domxref("VRDisplay.displayName")}} {{ReadOnlyInline}} - : A human-readable name to identify the `VRDevice`. ## Examples The following example uses the WebVR API to update the view of a simple {{domxref("CanvasRenderingContext2D","2D canvas")}} scene on each frame of a {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} loop. ```js function setView() { const posState = gPositionSensor.getState(); if (posState.hasPosition) { posPara.textContent = `Position: x${roundToTwo( posState.position.x, )} y${roundToTwo(posState.position.y)} z${roundToTwo(posState.position.z)}`; xPos = -posState.position.x * WIDTH * 2; yPos = posState.position.y * HEIGHT * 2; zPos = -posState.position.z > 0.01 ? -posState.position.z : 0.01; } if (posState.hasOrientation) { orientPara.textContent = `Orientation: x${roundToTwo( posState.orientation.x, )} y${roundToTwo(posState.orientation.y)} z${roundToTwo( posState.orientation.z, )}`; xOrient = posState.orientation.x * WIDTH; yOrient = -posState.orientation.y * HEIGHT * 2; zOrient = posState.orientation.z * 180; } } ``` Here we are grabbing a {{domxref("VRPose")}} object using {{domxref("PositionSensorVRDevice.getState()")}} and storing it in `posState`. We then check to make sure that position and orientation info is present in the current frame using {{domxref("VRPose.position")}} and {{domxref("VRPose.orientation")}} (these return `null` if, for example the head mounted display is turned off or not pointing at the position sensor, which would cause an error.) We then output the x, y and z position and orientation values for informational purposes, and use those values to update the `xPos`, `yPos`, `zPos`, `xOrient`, `yOrient`, and `zOrient` variables, which are used to update the scene rendering on each frame. ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/positionsensorvrdevice
data/mdn-content/files/en-us/web/api/positionsensorvrdevice/resetsensor/index.md
--- title: "PositionSensorVRDevice: resetSensor() method" short-title: resetSensor() slug: Web/API/PositionSensorVRDevice/resetSensor page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.PositionSensorVRDevice.resetSensor --- {{deprecated_header}}{{APIRef("WebVR API")}}{{Non-standard_header}} The **`resetSensor()`** method of the {{domxref("VRDisplay")}} interface _can be used to reset the sensor if desired, returning the_ position and orientation values to zero. ## Syntax ```js-nolint resetSensor() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples The following demo uses the WebVR API to update the view of a simple {{domxref("CanvasRenderingContext2D","2D canvas")}} scene on each frame of a {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} loop. It features, among other things, a "Reset Sensor" button in the UI, which when pressed runs the `resetSensor()` function on the position sensor. The JavaScript looks like this: ```js document.querySelector("button").onclick = () => { gPositionSensor.resetSensor(); }; ``` When the button is pressed, the current position, orientation, etc. of the sensor/head mounted display is set to be 0 — this makes the method useful for calibration when an app is first loaded. ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/positionsensorvrdevice
data/mdn-content/files/en-us/web/api/positionsensorvrdevice/getimmediatestate/index.md
--- title: "PositionSensorVRDevice: getImmediateState() method" short-title: getImmediateState() slug: Web/API/PositionSensorVRDevice/getImmediateState page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.PositionSensorVRDevice.getImmediateState --- {{deprecated_header}}{{APIRef("WebVR API")}}{{Non-standard_header}} The **`getImmediateState()`** method of the {{domxref("VRDisplay")}} interface returns the current instantaneous position sensor state. This is intended to only be used rarely, for certain special uses, for example sampling the immediate position of a hand orientation sensor — or at least it will be, in the future. For most standard uses, you'll probably want to use {{domxref("PositionSensorVRDevice.getState")}} instead. ## Syntax ```js-nolint getImmediateState() ``` ### Parameters None. ### Return value A {{domxref("VRPose")}} object. ## Examples The following demo uses the WebVR API to update the view of a simple {{domxref("CanvasRenderingContext2D","2D canvas")}} scene on each frame of a {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} loop. The main function that updates the view data is as follows: ```js function setView() { const posState = gPositionSensor.getImmediateState(); if (posState.hasPosition) { posPara.textContent = `Position: x${roundToTwo( posState.position.x, )} y${roundToTwo(posState.position.y)} z${roundToTwo(posState.position.z)}`; xPos = -posState.position.x * WIDTH * 2; yPos = posState.position.y * HEIGHT * 2; zPos = -posState.position.z > 0.01 ? -posState.position.z : 0.01; } if (posState.hasOrientation) { orientPara.textContent = `Orientation: x${roundToTwo( posState.orientation.x, )} y${roundToTwo(posState.orientation.y)} z${roundToTwo( posState.orientation.z, )}`; xOrient = posState.orientation.x * WIDTH; yOrient = -posState.orientation.y * HEIGHT * 2; zOrient = posState.orientation.z * 180; } } ``` Here we are grabbing a {{domxref("VRPose")}} object using `getImmediateState()` and storing it in `posState` (the actual live demo uses `getState()`, but both seem to do the same thing currently.) We then check to make sure that position and orientation info is present in the current frame using {{domxref("VRPose.position")}} and {{domxref("VRPose.orientation")}} (these return `null` if, for example the head mounted display is turned off or not pointing at the position sensor, which would cause an error.) We then output the x, y and z position and orientation values for informational purposes, and use those values to update the `xPos`, `yPos`, `zPos`, `xOrient`, `yOrient`, and `zOrient` variables, which are used to update the scene rendering on each frame. ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/positionsensorvrdevice
data/mdn-content/files/en-us/web/api/positionsensorvrdevice/getstate/index.md
--- title: "PositionSensorVRDevice: getState() method" short-title: getState() slug: Web/API/PositionSensorVRDevice/getState page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.PositionSensorVRDevice.getState --- {{deprecated_header}}{{APIRef("WebVR API")}}{{Non-standard_header}} The **`getState()`** method of the {{domxref("PositionSensorVRDevice")}} interface returns the current state of the position sensor for the current frame (e.g. within the current {{domxref("window.requestAnimationFrame")}} callback) or for the previous frame, contained with a {{domxref("VRPose")}} object. This is the method you'd normally want to use, vs. {{domxref("PositionSensorVRDevice.getImmediateState")}}. ## Syntax ```js-nolint getState() ``` ### Parameters None. ### Return value A {{domxref("VRPose")}} object. ## Examples The following example uses the WebVR API to update the view of a simple {{domxref("CanvasRenderingContext2D","2D canvas")}} scene on each frame of a {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} loop. ```js function setView() { const posState = gPositionSensor.getState(); if (posState.hasPosition) { posPara.textContent = `Position: x${roundToTwo( posState.position.x, )} y${roundToTwo(posState.position.y)} z${roundToTwo(posState.position.z)}`; xPos = -posState.position.x * WIDTH * 2; yPos = posState.position.y * HEIGHT * 2; zPos = -posState.position.z > 0.01 ? -posState.position.z : 0.01; } if (posState.hasOrientation) { orientPara.textContent = `Orientation: x${roundToTwo( posState.orientation.x, )} y${roundToTwo(posState.orientation.y)} z${roundToTwo( posState.orientation.z, )}`; xOrient = posState.orientation.x * WIDTH; yOrient = -posState.orientation.y * HEIGHT * 2; zOrient = posState.orientation.z * 180; } } ``` Here we are grabbing a {{domxref("VRPose")}} object using `getState()` and storing it in `posState`. We then check to make sure that position and orientation info is present in the current frame using {{domxref("VRPose.position")}} and {{domxref("VRPose.orientation")}} (these return `null` if, for example the head mounted display is turned off or not pointing at the position sensor, which would cause an error.) We then output the x, y and z position and orientation values for informational purposes, and use those values to update the `xPos`, `yPos`, `zPos`, `xOrient`, `yOrient`, and `zOrient` variables, which are used to update the scene rendering on each frame. ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/storage/index.md
--- title: Storage slug: Web/API/Storage page-type: web-api-interface browser-compat: api.Storage --- {{APIRef("Web Storage API")}} The **`Storage`** interface of the [Web Storage API](/en-US/docs/Web/API/Web_Storage_API) provides access to a particular domain's session or local storage. It allows, for example, the addition, modification, or deletion of stored data items. To manipulate, for instance, the session storage for a domain, a call to {{domxref("Window.sessionStorage")}} is made; whereas for local storage the call is made to {{domxref("Window.localStorage")}}. ## Instance properties - {{domxref("Storage.length")}} {{ReadOnlyInline}} - : Returns an integer representing the number of data items stored in the `Storage` object. ## Instance methods - {{domxref("Storage.key()")}} - : When passed a number `n`, this method will return the name of the nth key in the storage. - {{domxref("Storage.getItem()")}} - : When passed a key name, will return that key's value. - {{domxref("Storage.setItem()")}} - : When passed a key name and value, will add that key to the storage, or update that key's value if it already exists. - {{domxref("Storage.removeItem()")}} - : When passed a key name, will remove that key from the storage. - {{domxref("Storage.clear()")}} - : When invoked, will empty all keys out of the storage. ## Examples Here we access a `Storage` object by calling `localStorage`. We first test whether the local storage contains data items using `!localStorage.getItem('bgcolor')`. If it does, we run a function called `setStyles()` that grabs the data items using {{domxref("Storage.getItem()")}} and uses those values to update page styles. If it doesn't, we run another function, `populateStorage()`, which uses {{domxref("Storage.setItem()")}} to set the item values, then runs `setStyles()`. ```js if (!localStorage.getItem("bgcolor")) { populateStorage(); } else { setStyles(); } function populateStorage() { localStorage.setItem("bgcolor", document.getElementById("bgcolor").value); localStorage.setItem("font", document.getElementById("font").value); localStorage.setItem("image", document.getElementById("image").value); setStyles(); } function setStyles() { const currentColor = localStorage.getItem("bgcolor"); const currentFont = localStorage.getItem("font"); const currentImage = localStorage.getItem("image"); document.getElementById("bgcolor").value = currentColor; document.getElementById("font").value = currentFont; document.getElementById("image").value = currentImage; htmlElem.style.backgroundColor = `#${currentColor}`; pElem.style.fontFamily = currentFont; imgElem.setAttribute("src", currentImage); } ``` > **Note:** To see this running as a complete working example, see our [Web Storage Demo](https://mdn.github.io/dom-examples/web-storage/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) - {{domxref("Window.localStorage")}} - {{domxref("Window.sessionStorage")}} - {{domxref("CacheStorage")}}
0
data/mdn-content/files/en-us/web/api/storage
data/mdn-content/files/en-us/web/api/storage/removeitem/index.md
--- title: "Storage: removeItem() method" short-title: removeItem() slug: Web/API/Storage/removeItem page-type: web-api-instance-method browser-compat: api.Storage.removeItem --- {{APIRef("Web Storage API")}} The **`removeItem()`** method of the {{domxref("Storage")}} interface, when passed a key name, will remove that key from the given `Storage` object if it exists. The **`Storage`** interface of the [Web Storage API](/en-US/docs/Web/API/Web_Storage_API) provides access to a particular domain's session or local storage. If there is no item associated with the given key, this method will do nothing. ## Syntax ```js-nolint removeItem(keyName) ``` ### Parameters - `keyName` - : A string containing the name of the key you want to remove. ### Return value None ({{jsxref("undefined")}}). ## Examples The following function creates three data items inside local storage, then removes the `image` data item. ```js function populateStorage() { localStorage.setItem("bgcolor", "red"); localStorage.setItem("font", "Helvetica"); localStorage.setItem("image", "myCat.png"); localStorage.removeItem("image"); } ``` We can do the same for the session storage. ```js function populateStorage() { sessionStorage.setItem("bgcolor", "red"); sessionStorage.setItem("font", "Helvetica"); sessionStorage.setItem("image", "myCat.png"); sessionStorage.removeItem("image"); } ``` > **Note:** To see this used within a real-world example, see our [Web Storage Demo](https://mdn.github.io/dom-examples/web-storage/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)
0
data/mdn-content/files/en-us/web/api/storage
data/mdn-content/files/en-us/web/api/storage/length/index.md
--- title: "Storage: length property" short-title: length slug: Web/API/Storage/length page-type: web-api-instance-property browser-compat: api.Storage.length --- {{APIRef("Web Storage API")}} The **`length`** read-only property of the {{domxref("Storage")}} interface returns the number of data items stored in a given `Storage` object. ## Value The number of items stored in the `Storage` object. ## Examples The following function adds three data items to the local storage for the current domain, then returns the number of items in the storage: ```js function populateStorage() { localStorage.setItem("bgcolor", "yellow"); localStorage.setItem("font", "Helvetica"); localStorage.setItem("image", "cats.png"); return localStorage.length; // Should return 3 } ``` > **Note:** For a real-world example, see our [Web Storage Demo](https://mdn.github.io/dom-examples/web-storage/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)
0
data/mdn-content/files/en-us/web/api/storage
data/mdn-content/files/en-us/web/api/storage/clear/index.md
--- title: "Storage: clear() method" short-title: clear() slug: Web/API/Storage/clear page-type: web-api-instance-method browser-compat: api.Storage.clear --- {{APIRef("Web Storage API")}} The **`clear()`** method of the {{domxref("Storage")}} interface clears all keys stored in a given `Storage` object. ## Syntax ```js-nolint clear() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples The following function creates three data entries in local storage, and then deletes them by using `clear()`. ```js function populateStorage() { localStorage.setItem("bgcolor", "red"); localStorage.setItem("font", "Helvetica"); localStorage.setItem("image", "miGato.png"); localStorage.clear(); } ``` > **Note:** For a real-world example, see our [Web Storage Demo](https://mdn.github.io/dom-examples/web-storage/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)
0
data/mdn-content/files/en-us/web/api/storage
data/mdn-content/files/en-us/web/api/storage/setitem/index.md
--- title: "Storage: setItem() method" short-title: setItem() slug: Web/API/Storage/setItem page-type: web-api-instance-method browser-compat: api.Storage.setItem --- {{APIRef("Web Storage API")}} The **`setItem()`** method of the {{domxref("Storage")}} interface, when passed a key name and value, will add that key to the given `Storage` object, or update that key's value if it already exists. ## Syntax ```js-nolint setItem(keyName, keyValue) ``` ### Parameters - `keyName` - : A string containing the name of the key you want to create/update. - `keyValue` - : A string containing the value you want to give the key you are creating/updating. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `QuotaExceededError` {{domxref("DOMException")}} - : Thrown if the storage run out of disk quota or the user declined to grant you more space. ## Examples The following function creates three data items inside local storage. ```js function populateStorage() { localStorage.setItem("bgcolor", "red"); localStorage.setItem("font", "Helvetica"); localStorage.setItem("image", "myCat.png"); } ``` > **Note:** To see this used within a real-world example, see our [Web Storage Demo](https://mdn.github.io/dom-examples/web-storage/). `Storage` only supports storing and retrieving strings. If you want to save other data types, you have to convert them to strings. For plain objects and arrays, you can use {{jsxref("JSON.stringify()")}}. ```js const person = { name: "Alex" }; localStorage.setItem("user", person); console.log(localStorage.getItem("user")); // "[object Object]"; not useful! localStorage.setItem("user", JSON.stringify(person)); console.log(JSON.parse(localStorage.getItem("user"))); // { name: "Alex" } ``` However, there's no generic way to store arbitrary data types. Furthermore, the retrieved object is a [deep copy](/en-US/docs/Glossary/Deep_copy) of the original object and mutations to it do not affect the original object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Storage.getItem()](/en-US/docs/Web/API/Storage/getItem) - [Storage.removeItem()](/en-US/docs/Web/API/Storage/removeItem) - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)
0
data/mdn-content/files/en-us/web/api/storage
data/mdn-content/files/en-us/web/api/storage/getitem/index.md
--- title: "Storage: getItem() method" short-title: getItem() slug: Web/API/Storage/getItem page-type: web-api-instance-method browser-compat: api.Storage.getItem --- {{APIRef("Web Storage API")}} The **`getItem()`** method of the {{domxref("Storage")}} interface, when passed a key name, will return that key's value, or `null` if the key does not exist, in the given `Storage` object. ## Syntax ```js-nolint getItem(keyName) ``` ### Parameters - `keyName` - : A string containing the name of the key you want to retrieve the value of. ### Return value A string containing the value of the key. If the key does not exist, `null` is returned. ## Examples The following function retrieves three data items from local storage, then uses them to set custom styles on a page. ```js function setStyles() { const currentColor = localStorage.getItem("bgcolor"); const currentFont = localStorage.getItem("font"); const currentImage = localStorage.getItem("image"); document.getElementById("bgcolor").value = currentColor; document.getElementById("font").value = currentFont; document.getElementById("image").value = currentImage; htmlElem.style.backgroundColor = `#${currentColor}`; pElem.style.fontFamily = currentFont; imgElem.setAttribute("src", currentImage); } ``` > **Note:** To see this used within a real-world example, see our [Web Storage Demo](https://mdn.github.io/dom-examples/web-storage/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Storage.setItem()](/en-US/docs/Web/API/Storage/setItem) - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)
0
data/mdn-content/files/en-us/web/api/storage
data/mdn-content/files/en-us/web/api/storage/key/index.md
--- title: "Storage: key() method" short-title: key() slug: Web/API/Storage/key page-type: web-api-instance-method browser-compat: api.Storage.key --- {{APIRef("Web Storage API")}} The **`key()`** method of the {{domxref("Storage")}} interface, when passed a number n, returns the name of the nth key in a given `Storage` object. The order of keys is user-agent defined, so you should not rely on it. ## Syntax ```js-nolint key(index) ``` ### Parameters - `index` - : An integer representing the number of the key you want to get the name of. This is a zero-based index. ### Return value A string containing the name of the key. If the index does not exist, `null` is returned. ## Examples The following function iterates over the local storage keys: ```js function forEachKey(callback) { for (let i = 0; i < localStorage.length; i++) { callback(localStorage.key(i)); } } ``` The following function iterates over the local storage keys and gets the value set for each key: ```js for (let i = 0; i < localStorage.length; i++) { console.log(localStorage.getItem(localStorage.key(i))); } ``` > **Note:** For a real-world example, see our [Web Storage Demo](https://mdn.github.io/dom-examples/web-storage/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/federatedcredential/index.md
--- title: FederatedCredential slug: Web/API/FederatedCredential page-type: web-api-interface status: - experimental browser-compat: api.FederatedCredential --- {{SeeCompatTable}}{{APIRef("Credential Management API")}}{{SecureContext_Header}} The **`FederatedCredential`** interface of the [Credential Management API](/en-US/docs/Web/API/Credential_Management_API) provides information about credentials from a federated identity provider. A federated identity provider is an entity that a website trusts to correctly authenticate a user, and that provides an API for that purpose. [OpenID Connect](https://openid.net/developers/specs/) is an example of a federated identity provider framework. > **Note:** The [Federated Credential Management API (FedCM)](/en-US/docs/Web/API/FedCM_API) provides a more complete solution for handling identity federation in the browser, and uses the {{domxref("IdentityCredential")}} type. In browsers that support it, an instance of this interface may be passed in the `credential` member of the `init` object for global {{domxref('fetch()')}}. {{InheritanceDiagram}} ## Constructor - {{domxref("FederatedCredential.FederatedCredential()","FederatedCredential()")}} {{Experimental_Inline}} - : Creates a new `FederatedCredential` object. ## Instance properties _Inherits properties from its ancestor, {{domxref("Credential")}}._ - {{domxref("FederatedCredential.provider")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a string containing a credential's federated identity provider. - {{domxref("FederatedCredential.protocol")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a string containing a credential's federated identity protocol. ## Instance methods None. ## Examples ```js const cred = new FederatedCredential({ id, name, provider: "https://account.google.com", iconURL, }); // Store it navigator.credentials.store(cred).then(() => { // Do something else. }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/federatedcredential
data/mdn-content/files/en-us/web/api/federatedcredential/federatedcredential/index.md
--- title: "FederatedCredential: FederatedCredential() constructor" short-title: FederatedCredential() slug: Web/API/FederatedCredential/FederatedCredential page-type: web-api-constructor status: - experimental browser-compat: api.FederatedCredential.FederatedCredential --- {{APIRef("Credential Management API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`FederatedCredential()`** constructor creates a new {{domxref("FederatedCredential")}} object. In supporting browsers, an instance of this class may be passed the `credential` received from the `init` object for global {{domxref('fetch()')}}. ## Syntax ```js-nolint new FederatedCredential(init) ``` ### Parameters - `init` - : Options are: - `provider` - : A string; identifying the credential provider. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/federatedcredential
data/mdn-content/files/en-us/web/api/federatedcredential/protocol/index.md
--- title: "FederatedCredential: protocol property" short-title: protocol slug: Web/API/FederatedCredential/protocol page-type: web-api-instance-property status: - experimental browser-compat: api.FederatedCredential.protocol --- {{SeeCompatTable}}{{APIRef("Credential Management API")}}{{securecontext_header}} The **`protocol`** property of the {{domxref("FederatedCredential")}} interface returns a read-only string containing a credential's federated identity protocol. If this property is [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), the protocol may be inferred from the {{domxref("FederatedCredential.provider")}} property. ## Value A string containing a credential's federated identity protocol (e.g. `openidconnect`). ## Examples ```js // TBD ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/federatedcredential
data/mdn-content/files/en-us/web/api/federatedcredential/provider/index.md
--- title: "FederatedCredential: provider property" short-title: provider slug: Web/API/FederatedCredential/provider page-type: web-api-instance-property status: - experimental browser-compat: api.FederatedCredential.provider --- {{SeeCompatTable}}{{APIRef("Credential Management API")}}{{SecureContext_Header}} The **`provider`** property of the {{domxref("FederatedCredential")}} interface returns a string containing a credential's federated identity provider. ## Value A string containing a credential's federated identity provider. ## Examples ```js // TBD ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gravitysensor/index.md
--- title: GravitySensor slug: Web/API/GravitySensor page-type: web-api-interface browser-compat: api.GravitySensor --- {{securecontext_header}}{{APIRef("Sensor API")}} The **`GravitySensor`** interface of the [Sensor APIs](/en-US/docs/Web/API/Sensor_APIs) provides on each reading the gravity applied to the device along all three axes. To use this sensor, the user must grant permission to the `'accelerometer'` device sensor through the [Permissions API](/en-US/docs/Web/API/Permissions_API). In addition, this feature may be blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) set on your server. {{InheritanceDiagram}} ## Constructor - {{domxref("GravitySensor.GravitySensor", "GravitySensor()")}} - : Creates a new `GravitySensor` object. ## Instance properties _Inherits properties from its ancestors, {{domxref('Accelerometer')}}, {{domxref('Sensor')}}, and {{domxref('EventTarget')}}._ ## Instance methods _`GravitySensor` doesn't have own methods. However, it inherits methods from its parent interfaces, {{domxref("Sensor")}} and {{domxref("EventTarget")}}._ ## Events _`GravitySensor` doesn't have own events. However, it inherits events from its parent interface, {{domxref('Sensor')}}._ ## Example Gravity is typically read in the {{domxref('Sensor.reading_event', 'reading')}} event callback. In the example below this occurs sixty times a second. ```js let gravitySensor = new GravitySensor({ frequency: 60 }); gravitySensor.addEventListener("reading", (e) => { console.log(`Gravity along the X-axis ${gravitySensor.x}`); console.log(`Gravity along the Y-axis ${gravitySensor.y}`); console.log(`Gravity along the Z-axis ${gravitySensor.z}`); }); gravitySensor.start(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/gravitysensor
data/mdn-content/files/en-us/web/api/gravitysensor/gravitysensor/index.md
--- title: "GravitySensor: GravitySensor() constructor" short-title: GravitySensor() slug: Web/API/GravitySensor/GravitySensor page-type: web-api-constructor browser-compat: api.GravitySensor.GravitySensor --- {{securecontext_header}}{{APIRef("Sensor API")}} The **`GravitySensor()`** constructor creates a new {{domxref("GravitySensor")}} object which provides on each reading the gravity applied to the device along all three axes. ## Syntax ```js-nolint new GravitySensor() new GravitySensor(options) ``` ### Parameters - `options` {{optional_inline}} - : Options are as follows: - `frequency` {{optional_inline}} - : The desired number of times per second a sample should be taken, meaning the number of times per second that the {{domxref('sensor.reading_event', 'reading')}} event will be called. A whole number or decimal may be used, the latter for frequencies less than a second. The actual reading frequency depends on device hardware and consequently may be less than requested. The default frequency is the one defined by the underlying platform. - `referenceFrame` {{optional_inline}} - : The local coordinate system representing the reference frame. It can be either `'device'` or `'screen'`. The default is `'device'`. ### Exceptions - `SecurityError` {{domxref("DOMException")}} - : Use of this feature was blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref('sensor.reading_event', 'reading')}} event
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlmapelement/index.md
--- title: HTMLMapElement slug: Web/API/HTMLMapElement page-type: web-api-interface browser-compat: api.HTMLMapElement --- {{ APIRef("HTML DOM") }} The **`HTMLMapElement`** interface provides special properties and methods (beyond those of the regular object {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating the layout and presentation of map elements. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLMapElement.name")}} - : A string representing the {{HTMLElement("map")}} element for referencing it other context. If the `id` attribute is set, this must have the same value; and it cannot be `null` or empty. - {{domxref("HTMLMapElement.areas")}} {{ReadOnlyInline}} - : A live {{domxref("HTMLCollection")}} representing the {{HTMLElement("area")}} elements associated to this {{HTMLElement("map")}}. ## Instance methods _No specific method; inherits methods from its parent, {{domxref("HTMLElement")}} ._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML element implementing this interface: {{ HTMLElement("map") }}.
0
data/mdn-content/files/en-us/web/api/htmlmapelement
data/mdn-content/files/en-us/web/api/htmlmapelement/name/index.md
--- title: "HTMLMapElement: name property" short-title: name slug: Web/API/HTMLMapElement/name page-type: web-api-instance-property browser-compat: api.HTMLMapElement.name --- {{ApiRef("HTML DOM")}} The **`name`** property of the {{domxref("HTMLMapElement")}} represents the unique name `<map>` element. Its value can be used with the `useMap` attribute of the {{HTMLElement("img")}} element to reference a `<map>` element. If an `id` attribute is set on the {{HTMLElement("map")}} element, then this `name` property should be the same as this `id`. ## Value A non-empty string without whitespaces. ## Example ```html <map name="image-map"> <area shape="circle" coords="15,15,5" /> </map> ``` ```js const mapElement = document.getElementsByName("image-map")[0]; console.log(mapElement.name); // output: "image-map" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLImageElement.useMap")}} property - {{domxref("HTMLAreaElement")}} element
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svguseelement/index.md
--- title: SVGUseElement slug: Web/API/SVGUseElement page-type: web-api-interface browser-compat: api.SVGUseElement --- {{APIRef("SVG")}} ## SVG use DOM interface The **`SVGUseElement`** interface corresponds to the {{SVGElement("use")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGGraphicsElement")}}._ - {{domxref("SVGUseElement.href")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("href")}} or {{SVGAttr("xlink:href")}} {{deprecated_inline}} attribute of the given element. - {{domxref("SVGUseElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGUseElement.y")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element. - {{domxref("SVGUseElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element. - {{domxref("SVGUseElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element. ## Instance methods _This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGGraphicsElement")}}._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{SVGElement("use")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/vttcue/index.md
--- title: VTTCue slug: Web/API/VTTCue page-type: web-api-interface browser-compat: api.VTTCue --- {{APIRef("WebVTT")}} The `VTTCue` interface—part of the API for handling WebVTT (text tracks on media presentations)—describes and controls the text track associated with a particular {{HTMLElement("track")}} element. {{InheritanceDiagram}} ## Constructor - {{domxref("VTTCue.VTTCue", "VTTCue()")}} - : Returns a newly created `VTTCue` object that covers the given time range and has the given text. ## Instance properties _This interface also inherits properties from {{domxref("TextTrackCue")}}._ - {{domxref("VTTCue.region")}} - : A {{domxref("VTTRegion")}} object describing the video's sub-region that the cue will be drawn onto, or `null` if none is assigned. - {{domxref("VTTCue.vertical")}} - : Returns an enum representing the cue writing direction. - {{domxref("VTTCue.snapToLines")}} - : Returns true if the {{domxref("VTTCue.line")}} attribute is an integer number of lines or a percentage of the video size. - {{domxref("VTTCue.line")}} - : Returns the line positioning of the cue. This can be the string `auto` or a number whose interpretation depends on the value of {{domxref("VTTCue.snapToLines")}}. - {{domxref("VTTCue.lineAlign")}} - : Returns an enum representing the alignment of the {{domxref("VTTCue.line")}}. - {{domxref("VTTCue.position")}} - : Returns the indentation of the cue within the line. This can be the string `auto` or a number representing the percentage of the {{domxref("VTTCue.region")}}, or the video size if {{domxref("VTTCue.region")}} is `null`. - {{domxref("VTTCue.positionAlign")}} - : Returns an enum representing the alignment of the cue. This is used to determine what the {{domxref("VTTCue.position")}} is anchored to. The default is `auto`. - {{domxref("VTTCue.size")}} - : Returns a `double` representing the size of the cue, as a percentage of the video size. - {{domxref("VTTCue.align")}} - : Returns an enum representing the alignment of all the lines of text within the cue box. - {{domxref("VTTCue.text")}} - : Returns a string with the contents of the cue. ## Instance methods - {{domxref("VTTCue.getCueAsHTML", "getCueAsHTML()")}} - : Returns the cue text as a {{domxref("DocumentFragment")}}. ## Example ### HTML The following example adds a new {{domxref("TextTrack")}} to the video, then adds cues using the {{domxref("TextTrack.addCue()")}} method, with a `VTTCue` object as the value. ```html <video controls src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/friday.mp4"></video> ``` ### CSS ```css video { width: 420px; height: 300px; } ``` ### JavaScript ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; track.addCue(new VTTCue(0, 0.9, "Hildy!")); track.addCue(new VTTCue(1, 1.4, "How are you?")); track.addCue(new VTTCue(1.5, 2.9, "Tell me, is the lord of the universe in?")); track.addCue(new VTTCue(3, 4.2, "Yes, he's in - in a bad humor")); track.addCue(new VTTCue(4.3, 6, "Somebody must've stolen the crown jewels")); console.log(track.cues); ``` ### Result {{EmbedLiveSample('Example','400','330')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/snaptolines/index.md
--- title: "VTTCue: snapToLines property" short-title: snapToLines slug: Web/API/VTTCue/snapToLines page-type: web-api-instance-property browser-compat: api.VTTCue.snapToLines --- {{APIRef("WebVTT")}} The **`snapToLines`** property of the {{domxref("VTTCue")}} interface is a {{jsxref("Boolean")}} indicating if the {{domxref("VTTCue.line")}} property is an integer number of lines, or a percentage of the video size. ## Value A {{jsxref("Boolean")}}. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `snapToLines` is set to `true`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.snapToLines = true; console.log(cue1.snapToLines); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/vertical/index.md
--- title: "VTTCue: vertical property" short-title: vertical slug: Web/API/VTTCue/vertical page-type: web-api-instance-property browser-compat: api.VTTCue.vertical --- {{APIRef("WebVTT")}} The **`vertical`** property of the {{domxref("VTTCue")}} interface is a string representing the cue's writing direction. ## Value A string containing one of the following values: - `""` (an empty string) - : Represents a horizontal writing direction. - `"rl"` - : Represents a vertical writing direction growing to the left. - `"lr"` - : Represents a vertical writing direction growing to the right. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `vertical` is set to `"rl"`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.vertical = "rl"; console.log(cue1.vertical); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/position/index.md
--- title: "VTTCue: position property" short-title: position slug: Web/API/VTTCue/position page-type: web-api-instance-property browser-compat: api.VTTCue.position --- {{APIRef("WebVTT")}} The **`position`** property of the {{domxref("VTTCue")}} interface represents the indentation of the cue within the line. ## Value A number, or `"auto"` representing the indentation of the cue within the line. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `position` is set to `2`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.position = "2"; console.log(cue1.position); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/region/index.md
--- title: "VTTCue: region property" short-title: region slug: Web/API/VTTCue/region page-type: web-api-instance-property browser-compat: api.VTTCue.region --- {{APIRef("WebVTT")}} The **`region`** property of the {{domxref("VTTCue")}} interface returns and sets the {{domxref("VTTRegion")}} that this cue belongs to. ## Value A {{domxref("VTTRegion")}} object. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `region` is printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); console.log(cue1.region); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/linealign/index.md
--- title: "VTTCue: lineAlign property" short-title: lineAlign slug: Web/API/VTTCue/lineAlign page-type: web-api-instance-property browser-compat: api.VTTCue.lineAlign --- {{APIRef("WebVTT")}} The **`lineAlign`** property of the {{domxref("VTTCue")}} interface represents the alignment of this VTT cue. ## Value A string containing one of the following values: - `"start"` - : Start alignment. - `"center"` - : Center alignment. - `"end"` - : End alignment. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `lineAlign` is set to `"center"`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.lineAlign = "center"; console.log(cue1.lineAlign); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/text/index.md
--- title: "VTTCue: text property" short-title: text slug: Web/API/VTTCue/text page-type: web-api-instance-property browser-compat: api.VTTCue.text --- {{APIRef("WebVTT")}} The **`text`** property of the {{domxref("VTTCue")}} interface represents the text contents of the cue. ## Value A string containing the raw text of the cue. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `size` is set to the string `"new cue value"`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.text = "new cue value"; console.log(cue1.text); // 'new cue value'; track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/size/index.md
--- title: "VTTCue: size property" short-title: size slug: Web/API/VTTCue/size page-type: web-api-instance-property browser-compat: api.VTTCue.size --- {{APIRef("WebVTT")}} The **`size`** property of the {{domxref("VTTCue")}} interface represents the size of the cue as a percentage of the video size. ## Value A number representing the size of the cue as a percentage of the video size. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `size` is set to `50`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.size = 50; console.log(cue1.size); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/positionalign/index.md
--- title: "VTTCue: positionAlign property" short-title: positionAlign slug: Web/API/VTTCue/positionAlign page-type: web-api-instance-property browser-compat: api.VTTCue.positionAlign --- {{APIRef("WebVTT")}} The **`positionAlign`** property of the {{domxref("VTTCue")}} interface is used to determine what {{domxref("VTTCue.position")}} is anchored to. ## Value A string containing one of the following values: - `"line-left"` - : Line-left alignment. - `"center"` - : Center alignment. - `"line-right"` - : Line-right alignment. - `"auto"` - : Automatic alignment, which depends on the text alignment of the cue, interpreted as follows: - **line-left:** if the text alignment is left, the cue is using a LTR language and the text alignment is start, or the cue is using a RTL language and the text alignment is end. - **line-right:** if the text alignment is right, the cue is using a RTL language and the text alignment is start, or the cue is using a LTR language and the text-alignment is end. - **center:** if there is no text alignment position set. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `positionAlign` is set to `"line-right"`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.positionAlign = "line-right"; console.log(cue1.positionAlign); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/vttcue/index.md
--- title: "VTTCue: VTTCue() constructor" short-title: VTTCue() slug: Web/API/VTTCue/VTTCue page-type: web-api-constructor browser-compat: api.VTTCue.VTTCue --- {{APIRef("WebVTT")}} The **`VTTCue()`** constructor creates and returns a new {{domxref("VTTCue")}} object. ## Syntax ```js-nolint new VTTCue(startTime, endTime, text) ``` ### Parameters - `startTime` - : This is a `double` representing the initial text track cue start time. This is the time, given in seconds and fractions of a second, denoting the beginning of the range of the media data to which this cue applies. For example, if a cue is to be visible from 50 seconds to a one minute, five and a half seconds in the media's playback, `startTime` will be 50.0. - `endTime` - : This is a `double` representing the ending time for this text track cue. This is the time at which the cue should stop being presented to the user, given in seconds and fractions thereof. Given the example cue mentioned under `startTime`, the value of `endTime` would be 65.5. - `text` - : A string providing the text that will be shown during the time span indicated by `startTime` and `endTime`. ### Return value A new {{domxref("VTTCue")}} object representing a cue which will be presented during the time span given. ## Examples ```js // Create a cue that is shown from 2 to 3 seconds and uses the given text. let cue = new VTTCue(2, 3, "Cool text to be displayed"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/getcueashtml/index.md
--- title: "VTTCue: getCueAsHTML() method" short-title: getCueAsHTML() slug: Web/API/VTTCue/getCueAsHTML page-type: web-api-instance-method browser-compat: api.VTTCue.getCueAsHTML --- {{APIRef("WebVTT")}} The **`getCueAsHTML()`** method of the {{domxref("VTTCue")}} interface returns a {{domxref("DocumentFragment")}} containing the cue content. ## Syntax ```js-nolint getCueAsHTML() ``` ### Parameters None. ### Return value A {{domxref("DocumentFragment")}} . ## Examples In the following example a new {{domxref("VTTCue")}} is created. The value as a document fragment is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); console.log(cue1.getCueAsHTML()); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/line/index.md
--- title: "VTTCue: line property" short-title: line slug: Web/API/VTTCue/line page-type: web-api-instance-property browser-compat: api.VTTCue.line --- {{DefaultAPISidebar("")}} The **`line`** property of the {{domxref("VTTCue")}} interface represents the cue line of this WebVTT cue. ## Value A number, or `"auto"` representing the cue line of this WebVTT cue. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `line` is set to `1`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.line = "1"; console.log(cue1.line); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/vttcue
data/mdn-content/files/en-us/web/api/vttcue/align/index.md
--- title: "VTTCue: align property" short-title: align slug: Web/API/VTTCue/align page-type: web-api-instance-property browser-compat: api.VTTCue.align --- {{APIRef("WebVTT")}} The **`align`** property of the {{domxref("VTTCue")}} interface represents the alignment of all of the lines of text in the text box. ## Value A string containing one of the following values: - `"start"` - : Start alignment. - `"center"` - : Center alignment. - `"end"` - : End alignment. - `"left"` - : Left alignment. - `"right"` - : Right alignment. ## Examples In the following example a new {{domxref("VTTCue")}} is created, then the value of `align` is set to `"start"`. The value is then printed to the console. ```js let video = document.querySelector("video"); let track = video.addTextTrack("captions", "Captions", "en"); track.mode = "showing"; let cue1 = new VTTCue(0, 0.9, "Hildy!"); cue1.align = "start"; console.log(cue1.align); track.addCue(cue1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmldialogelement/index.md
--- title: HTMLDialogElement slug: Web/API/HTMLDialogElement page-type: web-api-interface browser-compat: api.HTMLDialogElement --- {{APIRef("HTML DOM")}} The **`HTMLDialogElement`** interface provides methods to manipulate {{HTMLElement("dialog")}} elements. It inherits properties and methods from the {{domxref("HTMLElement")}} interface. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLDialogElement.open")}} - : A boolean value reflecting the [`open`](/en-US/docs/Web/HTML/Element/dialog#open) HTML attribute, indicating whether the dialog is available for interaction. - {{domxref("HTMLDialogElement.returnValue")}} - : A string that sets or returns the return value for the dialog. ## Instance methods _Inherits methods from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLDialogElement.close()")}} - : Closes the dialog. An optional string may be passed as an argument, updating the `returnValue` of the dialog. - {{domxref("HTMLDialogElement.show()")}} - : Displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog. - {{domxref("HTMLDialogElement.showModal()")}} - : Displays the dialog as a modal, over the top of any other dialogs that might be present. Everything outside the dialog are [inert](/en-US/docs/Web/API/HTMLElement/inert) with interactions outside the dialog being blocked. ## Events _Also inherits events from its parent interface, {{DOMxRef("HTMLElement")}}._ Listen to these events using {{DOMxRef("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface. - {{domxref("HTMLDialogElement/close_event", "close")}} - : Fired when the dialog is closed, whether with the escape key, the `HTMLDialogElement.close()` method, or via submitting a form within the dialog with [`method="dialog"`](/en-US/docs/Web/HTML/Element/form#method). ## Examples ### Opening a modal dialog The following example shows a button that, when clicked, opens a modal {{htmlelement("dialog")}} containing a form via the {{domxref("HTMLDialogElement.showModal()")}} function. While open, everything other than the modal dialog's contents is inert. From there you can click the _Cancel_ button to close the dialog (via the {{domxref("HTMLDialogElement.close()")}} function), or submit the form via the submit button. Selecting the cancel button closes the dialog, creating a {{domxref("HTMLDialogElement/close_event", "close")}} event, not a {{domxref("HTMLElement/cancel_event", "cancel")}} event. #### HTML ```html <!-- pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <p> <label for="favAnimal">Favorite animal:</label> <select id="favAnimal" name="favAnimal"> <option></option> <option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </p> <div> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </div> </form> </dialog> <div> <button id="updateDetails">Update details</button> </div> ``` #### JavaScript ```js const updateButton = document.getElementById("updateDetails"); const cancelButton = document.getElementById("cancel"); const dialog = document.getElementById("favDialog"); dialog.returnValue = "favAnimal"; function openCheck(dialog) { if (dialog.open) { console.log("Dialog open"); } else { console.log("Dialog closed"); } } // Update button opens a modal dialog updateButton.addEventListener("click", () => { dialog.showModal(); openCheck(dialog); }); // Form cancel button closes the dialog box cancelButton.addEventListener("click", () => { dialog.close("animalNotChosen"); openCheck(dialog); }); ``` #### Result {{EmbedLiveSample("Opening a modal dialog")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("dialog") }}.
0
data/mdn-content/files/en-us/web/api/htmldialogelement
data/mdn-content/files/en-us/web/api/htmldialogelement/showmodal/index.md
--- title: "HTMLDialogElement: showModal() method" short-title: showModal() slug: Web/API/HTMLDialogElement/showModal page-type: web-api-instance-method browser-compat: api.HTMLDialogElement.showModal --- {{ APIRef("HTML DOM") }} The **`showModal()`** method of the {{domxref("HTMLDialogElement")}} interface displays the dialog as a modal, over the top of any other dialogs that might be present. It displays in the {{glossary("top layer")}}, along with a {{cssxref('::backdrop')}} pseudo-element. Interaction outside the dialog is blocked and the content outside it is rendered inert. ## Syntax ```js-nolint showModal() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the dialog is already open (i.e. if the `open` attribute is already set on the {{htmlelement("dialog")}} element), or if the dialog is also a [popover](/en-US/docs/Web/API/Popover_API) that is already being shown. ## Examples ### Opening a modal dialog The following example shows a button that, when clicked, opens a modal {{htmlelement("dialog")}} containing a form via the {{domxref("HTMLDialogElement.showModal()")}} function. While open, everything other than the modal dialog's contents is inert. From there you can click the _Cancel_ button to close the dialog (via the {{domxref("HTMLDialogElement.close()")}} function), or submit the form via the submit button. Selecting the cancel button closes the dialog, creating a {{domxref("HTMLDialogElement/close_event", "close")}} event, not a {{domxref("HTMLElement/cancel_event", "cancel")}} event. #### HTML ```html <!-- pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <p> <label for="favAnimal">Favorite animal:</label> <select id="favAnimal" name="favAnimal"> <option></option> <option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </p> <div> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </div> </form> </dialog> <div> <button id="updateDetails">Update details</button> </div> ``` #### JavaScript ```js const updateButton = document.getElementById("updateDetails"); const cancelButton = document.getElementById("cancel"); const dialog = document.getElementById("favDialog"); dialog.returnValue = "favAnimal"; function openCheck(dialog) { if (dialog.open) { console.log("Dialog open"); } else { console.log("Dialog closed"); } } // Update button opens a modal dialog updateButton.addEventListener("click", () => { dialog.showModal(); openCheck(dialog); }); // Form cancel button closes the dialog box cancelButton.addEventListener("click", () => { dialog.close("animalNotChosen"); openCheck(dialog); }); ``` #### Result {{EmbedLiveSample("Opening a modal dialog")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("dialog") }}.
0
data/mdn-content/files/en-us/web/api/htmldialogelement
data/mdn-content/files/en-us/web/api/htmldialogelement/close_event/index.md
--- title: "HTMLDialogElement: close event" short-title: close slug: Web/API/HTMLDialogElement/close_event page-type: web-api-event browser-compat: api.HTMLDialogElement.close_event --- {{ APIRef() }} The `close` event is fired on an `HTMLDialogElement` object when the {{htmlelement("dialog")}} it represents has been closed. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("close", (event) => {}); onclose = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ### Live example #### HTML ```html <dialog class="example-dialog"> <form method="dialog"> <button>Close via method="dialog"</button> </form> <button class="close">Close via .close() method</button> <p>Or hit the <kbd>Esc</kbd> key</p> </dialog> <button class="open-dialog">Open dialog</button> <div class="result"></div> ``` ```css hidden button, div { margin: 0.5rem; } ``` #### JavaScript ```js const result = document.querySelector(".result"); const dialog = document.querySelector(".example-dialog"); dialog.addEventListener("close", (event) => { result.textContent = "dialog was closed"; }); const openDialog = document.querySelector(".open-dialog"); openDialog.addEventListener("click", () => { dialog.showModal(); result.textContent = ""; }); const closeButton = document.querySelector(".close"); closeButton.addEventListener("click", () => { dialog.close(); }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '200px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML [`<dialog>`](/en-US/docs/Web/HTML/Element/dialog) element
0
data/mdn-content/files/en-us/web/api/htmldialogelement
data/mdn-content/files/en-us/web/api/htmldialogelement/returnvalue/index.md
--- title: "HTMLDialogElement: returnValue property" short-title: returnValue slug: Web/API/HTMLDialogElement/returnValue page-type: web-api-instance-property browser-compat: api.HTMLDialogElement.returnValue --- {{ APIRef("HTML DOM") }} The **`returnValue`** property of the {{domxref("HTMLDialogElement")}} interface gets or sets the return value for the {{htmlelement("dialog")}}, usually to indicate which button the user pressed to close it. ## Value A string representing the `returnValue` of the dialog. ## Examples The following example displays a button to open a {{htmlelement("dialog")}} containing a form via the `showModal()` method. The script assigns the `returnValue` an initial value of `initialValue`. The confirm button (`confirmBtn`) submits the form with validation and the "X" button submits the form without validation. Submitting a form with a `method="dialog"` closes the dialog and sets the return value to the `value`, if any, of the `button` or `input` elements of `type=submit`. The reset button has an event handler that closes the dialog; it has no impact on the `returnValue`. Neither does closing the dialog with the <kbd>Esc</kbd> key. ```html <!-- Simple pop-up dialog box containing a form --> <dialog id="favDialog"> <form method="dialog"> <input type="submit" aria-label="close" value="X" name="Xbutton" formnovalidate /> <p> <label >Favorite animal: <select name="favAnimal" required> <option></option> <option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </label> </p> <menu> <button type="reset" value="resetBtn">Reset</button> <button type="submit" value="confirmBtn">Confirm</button> </menu> </form> </dialog> <p> <button id="openDialog">Open Dialog</button> </p> <p id="text"></p> <script> (() => { const openDialog = document.getElementById("openDialog"); const dialog = document.getElementById("favDialog"); const text = document.getElementById("text"); const reset = document.querySelector("[type='reset']"); dialog.returnValue = "initialValue"; function openCheck(dialog) { if (dialog.open) { text.innerText = "Dialog open"; } else { text.innerText = "Dialog closed"; } } function handleUserInput(returnValue) { if (!returnValue) { text.innerText += ". There was no return value"; } else { text.innerText += ". Return value: " + returnValue; } } // "Open Dialog" button opens the <dialog> modally openDialog.addEventListener("click", () => { dialog.showModal(); openCheck(dialog); handleUserInput(dialog.returnValue); }); reset.addEventListener("click", () => { dialog.close(); }); // when the dialog is closed, no matter how it is closed dialog.addEventListener("close", () => { openCheck(dialog); handleUserInput(dialog.returnValue); }); })(); </script> <style> [aria-label="close"] { appearance: none; border-radius: 50%; border: 1px solid; float: right; } </style> ``` ### Result {{ EmbedLiveSample('Examples', '100%', '200px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("dialog") }}.
0
data/mdn-content/files/en-us/web/api/htmldialogelement
data/mdn-content/files/en-us/web/api/htmldialogelement/show/index.md
--- title: "HTMLDialogElement: show() method" short-title: show() slug: Web/API/HTMLDialogElement/show page-type: web-api-instance-method browser-compat: api.HTMLDialogElement.show --- {{ APIRef("HTML DOM") }} The **`show()`** method of the {{domxref("HTMLDialogElement")}} interface displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog. ## Syntax ```js-nolint show() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example shows a simple button that, when clicked, opens a {{htmlelement("dialog")}} containing a form via the `show()` method. From there you can click the _Cancel_ button to close the dialog (via the {{domxref("HTMLDialogElement.close()")}} method), or submit the form via the submit button. ```html <!-- Simple pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <section> <p> <label for="favAnimal">Favorite animal:</label> <select id="favAnimal" name="favAnimal"> <option></option> <option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </p> </section> <menu> <button id="cancel" type="reset">Cancel</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (() => { const updateButton = document.getElementById("updateDetails"); const cancelButton = document.getElementById("cancel"); const dialog = document.getElementById("favDialog"); dialog.returnValue = "favAnimal"; function openCheck(dialog) { if (dialog.open) { console.log("Dialog open"); } else { console.log("Dialog closed"); } } // Update button opens a modeless dialog updateButton.addEventListener("click", () => { dialog.show(); openCheck(dialog); }); // Form cancel button closes the dialog box cancelButton.addEventListener("click", () => { dialog.close("animalNotChosen"); openCheck(dialog); }); })(); </script> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("dialog") }}.
0
data/mdn-content/files/en-us/web/api/htmldialogelement
data/mdn-content/files/en-us/web/api/htmldialogelement/close/index.md
--- title: "HTMLDialogElement: close() method" short-title: close() slug: Web/API/HTMLDialogElement/close page-type: web-api-instance-method browser-compat: api.HTMLDialogElement.close --- {{ APIRef("HTML DOM") }} The **`close()`** method of the {{domxref("HTMLDialogElement")}} interface closes the {{htmlelement("dialog")}}. An optional string may be passed as an argument, updating the `returnValue` of the dialog. ## Syntax ```js-nolint close() close(returnValue) ``` ### Parameters - `returnValue` {{optional_inline}} - : A string representing an updated value for the {{domxref("HTMLDialogElement.returnValue")}} of the dialog. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example shows a simple button that, when clicked, opens a {{htmlelement("dialog")}} containing a form via the `showModal()` method. From there you can click the _X_ button to close the dialog (via the {{domxref("HTMLDialogElement.close()")}} method), or submit the form via the submit button. ```html <!-- Simple pop-up dialog box, containing a form --> <dialog id="favDialog"> <form method="dialog"> <button id="close" aria-label="close" formnovalidate>X</button> <section> <p> <label for="favAnimal">Favorite animal:</label> <select id="favAnimal" name="favAnimal"> <option></option> <option>Brine shrimp</option> <option>Red panda</option> <option>Spider monkey</option> </select> </p> </section> <menu> <button type="reset">Reset</button> <button type="submit">Confirm</button> </menu> </form> </dialog> <menu> <button id="updateDetails">Update details</button> </menu> <script> (() => { const updateButton = document.getElementById("updateDetails"); const closeButton = document.getElementById("close"); const dialog = document.getElementById("favDialog"); dialog.returnValue = "favAnimal"; function openCheck(dialog) { if (dialog.open) { console.log("Dialog open"); } else { console.log("Dialog closed"); } } // Update button opens a modal dialog updateButton.addEventListener("click", () => { dialog.showModal(); openCheck(dialog); }); // Form close button closes the dialog box closeButton.addEventListener("click", () => { dialog.close("animalNotChosen"); openCheck(dialog); }); })(); </script> ``` If the "X" button was of `type="submit"`, the dialog would have closed without requiring JavaScript. A form submission closes the `<dialog>` it is nested within if the [form's method is `dialog`](/en-US/docs/Web/HTML/Element/form#method), so no "close" button is required. ### Result {{ EmbedLiveSample('Examples', '100%', '200px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("dialog") }}.
0
data/mdn-content/files/en-us/web/api/htmldialogelement
data/mdn-content/files/en-us/web/api/htmldialogelement/open/index.md
--- title: "HTMLDialogElement: open property" short-title: open slug: Web/API/HTMLDialogElement/open page-type: web-api-instance-property browser-compat: api.HTMLDialogElement.open --- {{ APIRef("HTML DOM") }} The **`open`** property of the {{domxref("HTMLDialogElement")}} interface is a boolean value reflecting the [`open`](/en-US/docs/Web/HTML/Element/dialog#open) HTML attribute, indicating whether the {{htmlelement("dialog")}} is available for interaction. ## Value A boolean value representing the state of the [`open`](/en-US/docs/Web/HTML/Element/dialog#open) HTML attribute. `true` means it is set, and therefore the dialog is shown. `false` means it not set, and therefore the dialog is not shown. The property is not read only — it is possible to set the value to programmatically show or hide the dialog. ## Examples The following example shows a simple button that, when clicked, opens a {{htmlelement("dialog")}} containing a form via the `showModal()` method. From there you can click the _Cancel_ button to close the dialog (via the {{domxref("HTMLDialogElement.close()")}} method), or submit the form via the submit button. ```html <!-- Simple pop-up dialog box --> <dialog id="dialog"> <form method="dialog"> <button type="submit">Close</button> </form> </dialog> <p> <button id="openDialog">Open Dialog</button> </p> <p id="dialogStatus"></p> <script> (() => { const openDialog = document.getElementById("openDialog"); const dialog = document.getElementById("dialog"); const text = document.getElementById("dialogStatus"); function openCheck(dialog) { if (dialog.open) { text.innerText = "Dialog open"; } else { text.innerText = "Dialog closed"; } } // Update button opens a modal dialog openDialog.addEventListener("click", () => { dialog.showModal(); openCheck(dialog); }); dialog.addEventListener("close", () => { openCheck(dialog); }); })(); </script> ``` ### Result {{ EmbedLiveSample('Examples', '100%', '200px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{ HTMLElement("dialog") }}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpuqueryset/index.md
--- title: GPUQuerySet slug: Web/API/GPUQuerySet page-type: web-api-interface status: - experimental browser-compat: api.GPUQuerySet --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPUQuerySet`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} is used to record the results of queries on passes, such as occlusion or timestamp queries. - Occlusion queries are available on render passes to query whether any fragment samples pass all the per-fragment tests for a set of drawing commands (including scissor, sample mask, alpha to coverage, stencil, and depth tests). To run an occlusion query, an appropriate `GPUQuerySet` must be provided as the value of the `occlusionQuerySet` descriptor property when invoking {{domxref("GPUCommandEncoder.beginRenderPass()")}} to run a render pass. - Timestamp queries allow applications to write timestamps to a `GPUQuerySet`. To run a timestamp query, appropriate `GPUQuerySet`s must be provided inside the value of the `timestampWrites` descriptor property when invoking {{domxref("GPUCommandEncoder.beginRenderPass()")}} to run a render pass, or {{domxref("GPUCommandEncoder.beginComputePass()")}} to run a compute pass. Alternatively, you can run a single timestamp query at any time by invoking {{domxref("GPUCommandEncoder.writeTimeStamp()")}} with an appropriate `GPUQuerySet` as a parameter. > **Note:** To use timestamp queries, the `timestamp-query` {{domxref("GPUSupportedFeatures", "feature", "", "nocode")}} must be enabled in the {{domxref("GPUDevice")}}. A `GPUQuerySet` object instance is created using the {{domxref("GPUDevice.createQuerySet()")}} method. {{InheritanceDiagram}} ## Instance properties - {{domxref("GPUQuerySet.count", "count")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : A number specifying the number of queries managed by the `GPUQuerySet`. - {{domxref("GPUQuerySet.label", "label")}} {{Experimental_Inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. - {{domxref("GPUQuerySet.type", "type")}} {{Experimental_Inline}} {{ReadOnlyInline}} - : An enumerated value specifying the type of queries managed by the `GPUQuerySet`. ## Instance methods - {{domxref("GPUQuerySet.destroy", "destroy()")}} {{Experimental_Inline}} - : Destroys the `GPUQuerySet`. ## Examples The following snippet creates a `GPUQuerySet` that holds 32 occlusion query results, and then returns the `type` and `count`: ```js const querySet = device.createQuerySet({ type: "occlusion", count: 32, }); console.log(querySet.count); // 32 console.log(querySet.type); // "occlusion" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuqueryset
data/mdn-content/files/en-us/web/api/gpuqueryset/destroy/index.md
--- title: "GPUQuerySet: destroy() method" short-title: destroy() slug: Web/API/GPUQuerySet/destroy page-type: web-api-instance-method status: - experimental browser-compat: api.GPUQuerySet.destroy --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`destroy()`** method of the {{domxref("GPUQuerySet")}} interface destroys the `GPUQuerySet`. ## Syntax ```js-nolint destroy() ``` ### Parameters None. ### Return value None ({{jsxref("Undefined")}}). ## Examples ```js const querySet = device.createQuerySet({ type: "occlusion", count: 32, }); // Some time later querySet.destroy(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuqueryset
data/mdn-content/files/en-us/web/api/gpuqueryset/label/index.md
--- title: "GPUQuerySet: label property" short-title: label slug: Web/API/GPUQuerySet/label page-type: web-api-instance-property status: - experimental browser-compat: api.GPUQuerySet.label --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`label`** property of the {{domxref("GPUQuerySet")}} interface is a string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. This can be set by providing a `label` property in the descriptor object passed into the originating {{domxref("GPUDevice.createQuerySet()")}} call, or you can get and set it directly on the `GPUQuerySet` object. ## Value A string. If this has not been previously set as described above, it will be an empty string. ## Examples Setting and getting a label via `GPUQuerySet.label`: ```js const querySet = device.createQuerySet({ type: "occlusion", count: 32, }); querySet.label = "myqueryset"; console.log(querySet.label); // "myqueryset" ``` Setting a label via the originating {{domxref("GPUDevice.createQuerySet()")}} call, and then getting it via `GPUQuerySet.label`: ```js const querySet = device.createQuerySet({ type: "occlusion", count: 32, label: "myqueryset", }); console.log(querySet.label); // "myqueryset" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuqueryset
data/mdn-content/files/en-us/web/api/gpuqueryset/type/index.md
--- title: "GPUQuerySet: type property" short-title: type slug: Web/API/GPUQuerySet/type page-type: web-api-instance-property status: - experimental browser-compat: api.GPUQuerySet.type --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`type`** read-only property of the {{domxref("GPUQuerySet")}} interface is an enumerated value specifying the type of queries managed by the `GPUQuerySet`. ## Value An enumerated value. Possible values are: - `"occlusion"` - : The `GPUQuerySet` manages occlusion queries. - `"timestamp"` - : The `GPUQuerySet` manages timestamp queries. ## Examples See the main [`GPUQuerySet`](/en-US/docs/Web/API/GPUQuerySet#examples) page for an example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api/gpuqueryset
data/mdn-content/files/en-us/web/api/gpuqueryset/count/index.md
--- title: "GPUQuerySet: count property" short-title: count slug: Web/API/GPUQuerySet/count page-type: web-api-instance-property status: - experimental browser-compat: api.GPUQuerySet.count --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`count`** read-only property of the {{domxref("GPUQuerySet")}} interface is a number specifying the number of queries managed by the `GPUQuerySet`. ## Value A number. ## Examples See the main [`GPUQuerySet`](/en-US/docs/Web/API/GPUQuerySet#examples) page for an example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/dommatrixreadonly/index.md
--- title: DOMMatrixReadOnly slug: Web/API/DOMMatrixReadOnly page-type: web-api-interface browser-compat: api.DOMMatrixReadOnly --- {{APIRef("Geometry Interfaces")}} The **`DOMMatrixReadOnly`** interface represents a read-only 4×4 matrix, suitable for 2D and 3D operations. The {{domxref("DOMMatrix")}} interface — which is based upon `DOMMatrixReadOnly`—adds [mutability](https://en.wikipedia.org/wiki/Immutable_object), allowing you to alter the matrix after creating it. This interface should be available inside [web workers](/en-US/docs/Web/API/Web_Workers_API), though some implementations doesn't allow it yet. ## Constructor - {{domxref("DOMMatrixReadOnly.DOMMatrixReadOnly", "DOMMatrixReadOnly()")}} - : Creates a new `DOMMatrixReadOnly` object. ## Instance properties _This interface doesn't inherit any properties._ - `is2D` {{ReadOnlyInline}} - : A Boolean flag whose value is `true` if the matrix was initialized as a 2D matrix. If `false`, the matrix is 3D. - `isIdentity` {{ReadOnlyInline}} - : A Boolean whose value is `true` if the matrix is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix). The identity matrix is one in which every value is `0` _except_ those on the main diagonal from top-left to bottom-right corner (in other words, where the offsets in each direction are equal). - `m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44` - : Double-precision floating-point values representing each component of a 4×4 matrix, where `m11` through `m14` are the first column, `m21` through `m24` are the second column, and so forth. - `a`, `b`, `c`, `d`, `e`, `f` - : Double-precision floating-point values representing the components of a 4×4 matrix which are required in order to perform 2D rotations and translations. These are aliases for specific components of a 4×4 matrix, as shown below. | 2D | 3D equivalent | | --- | ------------- | | `a` | `m11` | | `b` | `m12` | | `c` | `m21` | | `d` | `m22` | | `e` | `m41` | | `f` | `m42` | ## Instance methods _This interface doesn't inherit any methods. None of the following methods alter the original matrix._ - {{domxref("DOMMatrixReadOnly.flipX()")}} - : Returns a new {{domxref("DOMMatrix")}} created by flipping the source matrix around its X-axis. This is equivalent to multiplying the matrix by `DOMMatrix(-1, 0, 0, 1, 0, 0)`. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.flipY()")}} - : Returns a new {{domxref("DOMMatrix")}} created by flipping the source matrix around its Y-axis. This is equivalent to multiplying the matrix by `DOMMatrix(1, 0, 0, -1, 0, 0)`. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.inverse()")}} - : Returns a new {{domxref("DOMMatrix")}} created by inverting the source matrix. If the matrix cannot be inverted, the new matrix's components are all set to `NaN` and its `is2D` property is set to `false`. The original matrix is not altered. - {{domxref("DOMMatrixReadOnly.multiply()")}} - : Returns a new {{domxref("DOMMatrix")}} created by computing the dot product of the source matrix and the specified matrix: `A⋅B`. If no matrix is specified as the multiplier, the matrix is multiplied by a matrix in which every element is `0` _except_ the bottom-right corner and the element immediately above and to its left: `m33` and `m34`. These have the default value of `1`. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.rotateAxisAngle()")}} - : Returns a new {{domxref("DOMMatrix")}} created by rotating the source matrix by the given angle around the specified vector. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.rotate()")}} - : Returns a new {{domxref("DOMMatrix")}} created by rotating the source matrix around each of its axes by the specified number of degrees. The original matrix is not altered. - {{domxref("DOMMatrixReadOnly.rotateFromVector()")}} - : Returns a new {{domxref("DOMMatrix")}} created by rotating the source matrix by the angle between the specified vector and `(1, 0)`. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.scale()")}} - : Returns a new {{domxref("DOMMatrix")}} created by scaling the source matrix by the amount specified for each axis, centered on the given origin. By default, the X and Z axes are scaled by `1` and the Y axis has no default scaling value. The default origin is `(0, 0, 0)`. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.scale3d()")}} - : Returns a new {{domxref("DOMMatrix")}} created by scaling the source 3D matrix by the given factor along all its axes, centered on the specified origin point. The default origin is `(0, 0, 0)`. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.scaleNonUniform()")}} {{deprecated_inline}} - : Returns a new {{domxref("DOMMatrix")}} created by applying the specified scaling on the X, Y, and Z axes, centered at the given origin. By default, the Y and Z axes' scaling factors are both `1`, but the scaling factor for X must be specified. The default origin is `(0, 0, 0)`. The original matrix is not changed. - {{domxref("DOMMatrixReadOnly.skewX()")}} - : Returns a new {{domxref("DOMMatrix")}} created by applying the specified skew transformation to the source matrix along its X-axis. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.skewY()")}} - : Returns a new {{domxref("DOMMatrix")}} created by applying the specified skew transformation to the source matrix along its Y-axis. The original matrix is not modified. - {{domxref("DOMMatrixReadOnly.toFloat32Array()")}} - : Returns a new {{jsxref("Float32Array")}} containing all 16 elements (`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`) which comprise the matrix. The elements are stored into the array as single-precision floating-point numbers in column-major (colexographical access, or "colex") order. (In other words, down the first column from top to bottom, then the second column, and so forth.) - {{domxref("DOMMatrixReadOnly.toFloat64Array()")}} - : Returns a new {{jsxref("Float64Array")}} containing all 16 elements (`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`) which comprise the matrix. The elements are stored into the array as double-precision floating-point numbers in column-major (colexographical access, or "colex") order. (In other words, down the first column from top to bottom, then the second column, and so forth.) - {{domxref("DOMMatrixReadOnly.toJSON()")}} - : Returns a JSON representation of the `DOMMatrixReadOnly` object. - {{domxref("DOMMatrixReadOnly.toString()")}} - : Creates and returns a string object which contains a string representation of the matrix in CSS matrix syntax, using the appropriate CSS matrix notation. See the {{cssxref("transform-function/matrix", "matrix()")}} CSS function for details on this syntax. For a 2D matrix, the elements `a` through `f` are listed, for a total of six values and the form `matrix(a, b, c, d, e, f)`. For a 3D matrix, the returned string contains all 16 elements and takes the form `matrix3d(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44)`. See the CSS {{cssxref("transform-function/matrix3d", "matrix3d()")}} function for details on the 3D notation's syntax. Throws an `InvalidStateError` exception if any of the elements in the matrix are non-finite (even if, in the case of a 2D matrix, the non-finite values are in elements not used by the 2D matrix representation). - {{domxref("DOMMatrixReadOnly.transformPoint()")}} - : Transforms the specified point using the matrix, returning a new {{domxref("DOMPoint")}} object containing the transformed point. Neither the matrix nor the original point are altered. - {{domxref("DOMMatrixReadOnly.translate()")}} - : Returns a new {{domxref("DOMMatrix")}} containing a matrix calculated by translating the source matrix using the specified vector. By default, the vector is `(0, 0, 0)`. The original matrix is not changed. ## Static methods - {{domxref("DOMMatrixReadOnly.fromFloat32Array", "fromFloat32Array()")}} - : Creates a new mutable `DOMMatrix` object given an array of single-precision (32-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a {{jsxref("TypeError")}} exception is thrown. - {{domxref("DOMMatrixReadOnly.fromFloat64Array", "fromFloat64Array()")}} - : Creates a new mutable `DOMMatrix` object given an array of double-precision (64-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a {{jsxref("TypeError")}} exception is thrown. - {{domxref("DOMMatrixReadOnly.fromMatrix", "fromMatrix()")}} - : Creates a new mutable `DOMMatrix` object given an existing matrix or a {{domxref("DOMMatrixInit")}} dictionary which provides the values for its properties. If no matrix is specified, the matrix is initialized with every element set to `0` _except_ the bottom-right corner and the element immediately above and to its left: `m33` and `m34`. These have the default value of `1`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The mutable matrix type, {{domxref("DOMMatrix")}}, which is based on this one. - The CSS {{cssxref("transform-function/matrix", "matrix()")}} and {{cssxref("transform-function/matrix3d", "matrix3d()")}} functional notation that can be generated from this interface to be used in a CSS {{cssxref("transform")}}.
0
data/mdn-content/files/en-us/web/api/dommatrixreadonly
data/mdn-content/files/en-us/web/api/dommatrixreadonly/scale/index.md
--- title: "DOMMatrixReadOnly: scale() method" short-title: scale() slug: Web/API/DOMMatrixReadOnly/scale page-type: web-api-instance-method browser-compat: api.DOMMatrixReadOnly.scale --- {{APIRef("Geometry Interfaces")}} The **`scale()`** method of the {{domxref("DOMMatrixReadOnly")}} interface creates a new matrix being the result of the original matrix with a scale transform applied. ## Syntax The `scale()` method is specified with either one or six values. ```js DOMMatrixReadOnly.scale(scaleX); DOMMatrixReadOnly.scale(scaleX, scaleY); DOMMatrixReadOnly.scale(scaleX, scaleY, scaleZ); DOMMatrixReadOnly.scale(scaleX, scaleY, scaleZ, originX); DOMMatrixReadOnly.scale(scaleX, scaleY, scaleZ, originX, originY); DOMMatrixReadOnly.scale(scaleX, scaleY, scaleZ, originX, originY, originZ); ``` ### Parameters - `scaleX` - : A multiplier for the scale value on the x-axis. - `scaleY` {{optional_inline}} - : A multiplier for the scale value on the y-axis. If not supplied, this defaults to the value of `scaleX`. - `scaleZ` {{optional_inline}} - : A multiplier for the scale value on the z-axis. If this value is anything other than 1, the resulting matrix will be 3D. - `originX` {{optional_inline}} - : An x-coordinate for the origin of the transformation. If no origin is supplied, this defaults to 0. - `originY` {{optional_inline}} - : A y-coordinate for the origin of the transformation. If no origin is supplied, this defaults to 0. - `originZ` {{optional_inline}} - : A z-coordinate for the origin of the transformation. If no origin is supplied, this defaults to 0. If this value is anything other than 0, the resulting matrix will be 3D. ### Return value Returns a [`DOMMatrix`](/en-US/docs/Web/API/DOMMatrix) containing a new matrix being the result of the matrix x and y dimensions being scaled by the given factor, centered on the origin given. The original matrix is not modified. If a scale is applied about the z-axis, the resulting matrix will be a 4✕4 3D matrix. ## Examples This SVG contains three squares, one red, one blue, and one green, each positioned at the document origin: ```html <svg width="250" height="250" viewBox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedOrigin" width="25" height="25" fill="green" /> </svg> ``` This JavaScript first creates an identity matrix, then uses the `scale()` method to create a new matrix with a single parameter. We test if the browser supports a six parameter `scale()` method by creating a new matrix using three parameters and observing its `is2D` property. If this is `false` then the third parameter has been accepted by the browser as a `scaleZ` parameter, making this a 3D matrix. We then create a new matrix scaled about a given origin, using either three or six parameters depending on the browser support. These new matrices are then applied to the blue and green squares as a `transform`, changing their dimensions and position. The red square is left in place. ```js const matrix = new DOMMatrixReadOnly(); const scaledMatrix = matrix.scale(0.5); let scaledMatrixWithOrigin = matrix.scale(0.5, 25, 25); // if the browser has interpreted these parameters as scaleX, scaleY, scaleZ, the resulting matrix is 3D const browserExpectsSixParamScale = !scaledMatrixWithOrigin.is2D; if (browserExpectsSixParamScale) { scaledMatrixWithOrigin = matrix.scale(0.5, 0.5, 1, 25, 25, 0); } document .querySelector("#transformed") .setAttribute("transform", scaledMatrix.toString()); document .querySelector("#transformedOrigin") .setAttribute("transform", scaledMatrixWithOrigin.toString()); ``` {{EmbedLiveSample('Examples', '250', '250')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/dommatrixreadonly
data/mdn-content/files/en-us/web/api/dommatrixreadonly/translate/index.md
--- title: "DOMMatrixReadOnly: translate() method" short-title: translate() slug: Web/API/DOMMatrixReadOnly/translate page-type: web-api-instance-method browser-compat: api.DOMMatrixReadOnly.translate --- {{APIRef("Geometry Interfaces")}} The `translate()` method of the {{domxref("DOMMatrixReadOnly")}} interface creates a new matrix being the result of the original matrix with a translation applied. ## Syntax ```js-nolint DOMMatrix.translate(translateX, translateY) DOMMatrix.translate(translateX, translateY, translateZ) ``` ### Parameters - `translateX` - : A number representing the abscissa (x-coordinate) of the translating vector. - `translateY` - : A number representing the ordinate (y-coordinate) of the translating vector. - `translateZ` {{optional_inline}} - : A number representing the z component of the translating vector. If not supplied, this defaults to 0. If this is anything other than 0, the resulting matrix will be 3D. ### Return value Returns a [`DOMMatrix`](/en-US/docs/Web/API/DOMMatrix) containing a new matrix being the result of the matrix being translated by the given vector. The original matrix is not modified. If a translation is applied about the z-axis, the resulting matrix will be a 4x4 3D matrix. ## Examples This SVG contains two squares, one red and one blue, each positioned at the document origin: ```html <svg width="250" height="250" viewBox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> ``` The following JavaScript first creates an identity matrix, then uses the `translate()` method to create a new, translated matrix — which is then applied to the blue square as a `transform`. The red square is left in place. ```js const matrix = new DOMMatrixReadOnly().translate(25, 25); document .querySelector("#transformed") .setAttribute("transform", matrix.toString()); ``` {{EmbedLiveSample('Examples', '250', '250')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/dommatrixreadonly
data/mdn-content/files/en-us/web/api/dommatrixreadonly/dommatrixreadonly/index.md
--- title: "DOMMatrixReadOnly: DOMMatrixReadOnly() constructor" short-title: DOMMatrixReadOnly() slug: Web/API/DOMMatrixReadOnly/DOMMatrixReadOnly page-type: web-api-constructor browser-compat: api.DOMMatrixReadOnly.DOMMatrixReadOnly --- {{APIRef("Geometry Interfaces")}} The **`DOMMatrixReadOnly`** constructor creates a new {{domxref("DOMMatrixReadOnly")}} object which represents 4x4 matrices, suitable for 2D and 3D operations. ## Syntax ```js-nolint DOMMatrixReadOnly() DOMMatrixReadOnly(init) ``` ### Parameters - `init` {{optional_inline}} - : Either a string containing a sequence of numbers or an array of numbers specifying the matrix you want to create. In case an array of numbers is passed, the behavior depends on the length of the array: - for a 6-element array of components in the form `[a, b, c, d, e, f]`, a 2D read-only matrix is created, initialized with the provided components. - for a 16-element array of components (in the column-major order) in the form `[m11, m12, m13, …, m42, m43, m44]`, a 3D read-only matrix is created, initialized with the provided components. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/dommatrixreadonly
data/mdn-content/files/en-us/web/api/dommatrixreadonly/flipx/index.md
--- title: "DOMMatrixReadOnly: flipX() method" short-title: flipX() slug: Web/API/DOMMatrixReadOnly/flipX page-type: web-api-instance-method browser-compat: api.DOMMatrixReadOnly.flipX --- {{APIRef("Geometry Interfaces")}} The `flipX()` method of the {{domxref("DOMMatrixReadOnly")}} interface creates a new matrix being the result of the original matrix flipped about the x-axis. ## Syntax ```js-nolint DOMMatrixReadOnly.flipX() ``` ### Return value Returns a [`DOMMatrix`](/en-US/docs/Web/API/DOMMatrix) containing a new matrix being the result of the original matrix flipped about the x-axis, which is equivalent to multiplying the matrix by `DOMMatrix(-1, 0, 0, 1, 0, 0)`. The original matrix is not modified. ## Examples ### Inverting a triangle In this example, the SVG contains two paths in the shape of a triangle, both drawn to the same position. Note that the x co-ordinate of the viewBox attribute is negative, showing us content from both sides of the x-axis. The JavaScript first creates an identity matrix, then uses the `flipX()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis. The red triangle is left in place. #### HTML ```html <svg width="100" height="100" viewBox="-50 0 100 100"> <path fill="red" d="M 0 50 L 50 0 L 50 100 Z" /> <path id="flipped" fill="blue" d="M 0 50 L 50 0 L 50 100 Z" /> </svg> ``` #### JavaScript ```js const flipped = document.getElementById("flipped"); const matrix = new DOMMatrixReadOnly(); const flippedMatrix = matrix.flipX(); flipped.setAttribute("transform", flippedMatrix.toString()); ``` #### Result {{EmbedLiveSample('Inverting a triangle')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/webhid_api/index.md
--- title: WebHID API slug: Web/API/WebHID_API page-type: web-api-overview status: - experimental browser-compat: api.HID --- {{DefaultAPISidebar("WebHID API")}}{{SeeCompatTable}} A Human Interface Device (HID) is a type of device that takes input from or provides output to humans. It also refers to the HID protocol, a standard for bi-directional communication between a host and a device that is designed to simplify the installation procedure. The HID protocol was originally developed for USB devices but has since been implemented over many other protocols, including Bluetooth. ## Interfaces - {{domxref("HID")}} - : Provides methods for connecting to HID devices, listing attached HID devices and event handlers for connected HID devices. - {{domxref("HIDDevice")}} - : Represents an HID device. It's possible for a single physical device to be represented by multiple `HIDDevice` objects. - {{domxref("HIDInputReportEvent")}} - : Passed to {{domxref("HIDDevice.inputreport_event")}} when an input report is received from any associated HID device. - {{domxref("HIDConnectionEvent")}} - : Passed to `HID` {{domxref("HID.connect_event", "connect")}} and {{domxref("HID.disconnect_event", "disconnect")}} events when a device is connected or disconnected. ## Examples You can connect to a device with the {{domxref("HID.requestDevice","requestDevice()")}} method. In this case, we select from all the available devices. ```js const device = await navigator.hid.requestDevice({ filters: [] }); // A popup titled `... wants to connect to a HID Device` with `Cancel` and `Connect` buttons will show up with a device list to select from. // Select one and click on `Connect` button. Then the device will be an array with the selected device in it. ``` We can retrieve all the devices the website has been granted access to previously and log the device names to the console. ```js let devices = await navigator.hid.getDevices(); devices.forEach((device) => { console.log(`HID: ${device.productName}`); }); ``` We can register event listeners for disconnection of any HID devices. ```js navigator.hid.addEventListener("disconnect", (event) => { console.log(`HID disconnected: ${event.device.productName}`); console.dir(event); }); // For example, when my connected keyboard gets disconnected, the log in the console will show: // HID disconnected: USB Keyboard // { // bubbles: false // cancelBubble: false // cancelable: false // composed: false // currentTarget: HID {onconnect: null, ondisconnect: null} // defaultPrevented: false // device: HIDDevice {oninputreport: null, opened: false, vendorId: 6700, productId: 11555, productName: "USB Keyboard", …} // eventPhase: 0 // isTrusted: true // path: [] // returnValue: true // srcElement: HID {onconnect: null, ondisconnect: null} // target: HID {onconnect: null, ondisconnect: null} // timeStamp: 18176.600000023842 // type: "disconnect" // } // The event above is an instance of the HIDConnectionEvent interface. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrlayerevent/index.md
--- title: XRLayerEvent slug: Web/API/XRLayerEvent page-type: web-api-interface status: - experimental browser-compat: api.XRLayerEvent --- {{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}} The **`XRLayerEvent`** interface of the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) is the event type for events related to a change of state of an {{domxref("XRLayer")}} object. These events occur, for example, when the layer needs to be redrawn. {{InheritanceDiagram}} ## Constructor - {{domxref("XRLayerEvent.XRLayerEvent", "XRLayerEvent()")}} {{Experimental_Inline}} - : Creates and returns a new `XRLayerEvent` object. ## Instance properties _In addition to properties inherited from its parent interface, {{domxref("Event")}}, `XRLayerEvent` provides the following:_ - {{domxref("XRLayerEvent.layer", "layer")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : The {{domxref("XRLayer")}} which generated the event. ## Instance methods _While `XRSessionEvent` defines no methods, it inherits methods from its parent interface, {{domxref("Event")}}._ ## Event types _The following events are represented using the `XRLayerEvent` interface, and are permitted values for its `type` parameter._ ### `redraw` event The `redraw` event is tent to the layer object when the underlying resources of the layer are lost or when the XR Compositor can no longer reproject the layer. If this event is sent, authors should redraw the content of the layer in the next XR animation frame. It is available on the following layer objects: - {{domxref("XRQuadLayer")}}: {{domxref("XRQuadLayer.redraw_event", "redraw")}} - {{domxref("XRCylinderLayer")}}: {{domxref("XRCylinderLayer.redraw_event", "redraw")}} - {{domxref("XREquirectLayer")}}: {{domxref("XREquirectLayer.redraw_event", "redraw")}} - {{domxref("XRCubeLayer")}}: {{domxref("XRCubeLayer.redraw_event", "redraw")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRCompositionLayer.needsRedraw")}}
0
data/mdn-content/files/en-us/web/api/xrlayerevent
data/mdn-content/files/en-us/web/api/xrlayerevent/xrlayerevent/index.md
--- title: "XRLayerEvent: XRLayerEvent() constructor" short-title: XRLayerEvent() slug: Web/API/XRLayerEvent/XRLayerEvent page-type: web-api-constructor status: - experimental browser-compat: api.XRLayerEvent.XRLayerEvent --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`XRLayerEvent`** constructor creates and returns a new {{domxref("XRLayerEvent")}} object. These events relate to a change of state of an {{domxref("XRLayer")}} object. ## Syntax ```js-nolint new XRLayerEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers always set it to `redraw`. - `options` - : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties: - `layer` - : The {{domxref("XRLayer")}} to which the event is to be delivered. ### Return value A new {{domxref("XRLayer")}} object representing an object of the specified type and configured as described by the `eventInitDict` parameter. ## Examples ### Creating a new `XRLayerEvent` In this example, a new `redraw` event is created for an {{domxref("XRQuadLayer")}}. ```js const redrawEvent = new XRLayerEvent("redraw", { layer: quadLayer, }); quadLayer.dispatchEvent(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRLayer")}} - {{domxref("EventTarget.dispatchEvent()")}}
0
data/mdn-content/files/en-us/web/api/xrlayerevent
data/mdn-content/files/en-us/web/api/xrlayerevent/layer/index.md
--- title: "XRLayerEvent: layer property" short-title: layer slug: Web/API/XRLayerEvent/layer page-type: web-api-instance-property status: - experimental browser-compat: api.XRLayerEvent.layer --- {{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`layer`** property of the {{domxref("XRLayerEvent")}} interface is a reference to the {{domxref("XRLayer")}} which generated the event. ## Value An {{domxref("XRLayer")}}. ## Examples ### Using the `layer` property In this example, the `layer` property is used to obtain the {{domxref("XRLayer")}} object that sent the event. ```js myLayer.addEventListener("redraw", (e) => { if (typeof e.layer === "XRQuadLayer") { // redraw quad layer } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XRLayer")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/serviceworkerregistration/index.md
--- title: ServiceWorkerRegistration slug: Web/API/ServiceWorkerRegistration page-type: web-api-interface browser-compat: api.ServiceWorkerRegistration --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`ServiceWorkerRegistration`** interface of the [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) represents the service worker registration. You register a service worker to control one or more pages that share the same origin. The lifetime of a service worker registration is beyond that of the `ServiceWorkerRegistration` objects that represent them within the lifetime of their corresponding service worker clients. The browser maintains a persistent list of active `ServiceWorkerRegistration` objects. {{AvailableInWorkers}} {{InheritanceDiagram}} ## Instance properties _Also inherits properties from its parent interface,_ {{domxref("EventTarget")}}. - {{domxref("ServiceWorkerRegistration.active")}} {{ReadOnlyInline}} - : Returns a service worker whose state is `activating` or `activated`. This is initially set to `null`. An active worker will control a {{domxref("Client")}} if the client's URL falls within the scope of the registration (the `scope` option set when {{domxref("ServiceWorkerContainer.register")}} is first called.) - {{domxref("ServiceWorkerRegistration.backgroundFetch")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to a {{domxref("BackgroundFetchManager")}} object, which manages background fetch operations. - {{domxref("ServiceWorkerRegistration.cookies")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to the {{domxref("CookieStoreManager")}} interface, which allows subscribe and unsubscribe to cookie change events. - {{domxref("ServiceWorkerRegistration.index")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to the {{domxref("ContentIndex")}} interface, for managing indexed content for offline viewing. - {{domxref("ServiceWorkerRegistration.installing")}} {{ReadOnlyInline}} - : Returns a service worker whose state is `installing`. This is initially set to `null`. - {{domxref("ServiceWorkerRegistration.navigationPreload")}} {{ReadOnlyInline}} - : Returns the instance of {{domxref("NavigationPreloadManager")}} associated with the current service worker registration. - {{domxref("ServiceWorkerRegistration.paymentManager")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a payment app's {{domxref("PaymentManager")}} instance, which is used to manage various payment app functionality. - {{domxref("ServiceWorkerRegistration.periodicSync")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to the {{domxref("PeriodicSyncManager")}} interface, which allows for registering of tasks to run at specific intervals. - {{domxref("ServiceWorkerRegistration.pushManager")}} {{ReadOnlyInline}} - : Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. - {{domxref("ServiceWorkerRegistration.scope")}} {{ReadOnlyInline}} - : Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}. - {{domxref("ServiceWorkerRegistration.sync")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a reference to the {{domxref("SyncManager")}} interface, which manages background synchronization processes. - {{domxref("ServiceWorkerRegistration.updateViaCache")}} {{ReadOnlyInline}} - : Returns a string indicating what is the cache strategy to use when updating the service worker scripts. It can be one of the following: `imports`, `all`, or `none`. - {{domxref("ServiceWorkerRegistration.waiting")}} {{ReadOnlyInline}} - : Returns a service worker whose state is `installed`. This is initially set to `null`. ## Instance methods _Also inherits methods from its parent interface,_ {{domxref("EventTarget")}}. - {{domxref("ServiceWorkerRegistration.getNotifications()")}} - : Returns a list of the notifications in the order that they were created from the current origin via the current service worker registration. - {{domxref("ServiceWorkerRegistration.showNotification()")}} - : Displays the notification with the requested title. - {{domxref("ServiceWorkerRegistration.unregister()")}} - : Unregisters the service worker registration and returns a {{jsxref("Promise")}}. The service worker will finish any ongoing operations before it is unregistered. - {{domxref("ServiceWorkerRegistration.update()")}} - : Checks the server for an updated version of the service worker without consulting caches. ## Events - {{domxref("ServiceWorkerRegistration.updatefound_event", "updatefound")}} - : Fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker. ## Examples In this example, the code first checks whether the browser supports service workers and if so registers one. Next, it adds an `updatefound` listener in which it uses the service worker registration to listen for further changes to the service worker's state. If the service worker hasn't changed since the last time it was registered, then the `updatefound` event will not be fired. ```js if ("serviceWorker" in navigator) { navigator.serviceWorker .register("/sw.js") .then((registration) => { registration.addEventListener("updatefound", () => { // If updatefound is fired, it means that there's // a new service worker being installed. const installingWorker = registration.installing; console.log( "A new service worker is being installed:", installingWorker, ); // You can listen for changes to the installing service worker's // state via installingWorker.onstatechange }); }) .catch((error) => { console.error(`Service worker registration failed: ${error}`); }); } else { console.error("Service workers are not supported."); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/backgroundfetch/index.md
--- title: "ServiceWorkerRegistration: backgroundFetch property" short-title: backgroundFetch slug: Web/API/ServiceWorkerRegistration/backgroundFetch page-type: web-api-instance-property status: - experimental browser-compat: api.ServiceWorkerRegistration.backgroundFetch --- {{APIRef("Background Fetch API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`backgroundFetch`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface returns a reference to a {{domxref("BackgroundFetchManager")}} object, which can be used to initiate background fetch operations. {{AvailableInWorkers}} ## Value A {{domxref("BackgroundFetchManager")}} object. ## Examples ### Initiating a background fetch The following code accesses the `backgroundFetch` property and uses it to initiate a background fetch operation. ```js // main.js async function requestBackgroundFetch(movieData) { const swRegistration = await navigator.serviceWorker.ready; const fetchRegistration = await swRegistration.backgroundFetch.fetch( "download-movie", ["/my-movie-part-1.webm", "/my-movie-part-2.webm"], { icons: movieIcons, title: "Downloading my movie", downloadTotal: 60 * 1024 * 1024, label: "Downloading a show", }, ); //... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/cookies/index.md
--- title: "ServiceWorkerRegistration: cookies property" short-title: cookies slug: Web/API/ServiceWorkerRegistration/cookies page-type: web-api-instance-property status: - experimental browser-compat: api.ServiceWorkerRegistration.cookies --- {{APIRef("Cookie Store API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`cookies`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface returns a reference to the {{domxref("CookieStoreManager")}} interface, which enables a web app to subscribe to and unsubscribe from cookie change events in a [service worker](/en-US/docs/Web/API/Service_Worker_API). This is an entry point for the [Cookie Store API](/en-US/docs/Web/API/Cookie_Store_API). ## Value A {{domxref("CookieStoreManager")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/scope/index.md
--- title: "ServiceWorkerRegistration: scope property" short-title: scope slug: Web/API/ServiceWorkerRegistration/scope page-type: web-api-instance-property browser-compat: api.ServiceWorkerRegistration.scope --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`scope`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface returns a unique identifier for a service worker registration. The service worker must be on the same origin as the document that registers the {{domxref("ServiceWorker")}}. {{AvailableInWorkers}} ## Value A unique identifier. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/updatefound_event/index.md
--- title: "ServiceWorkerRegistration: updatefound event" short-title: updatefound slug: Web/API/ServiceWorkerRegistration/updatefound_event page-type: web-api-event browser-compat: api.ServiceWorkerRegistration.updatefound_event --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`updatefound`** event of the {{domxref("ServiceWorkerRegistration")}} interface is fired any time the {{domxref("ServiceWorkerRegistration.installing")}} property acquires a new service worker. {{AvailableInWorkers}} ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("updatefound", (event) => {}); onupdatefound = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ```js const registration = await navigator.serviceWorker.getRegistration(); if (registration) { registration.addEventListener("updatefound", () => { console.log("Service Worker update found!"); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/updateviacache/index.md
--- title: "ServiceWorkerRegistration: updateViaCache property" short-title: updateViaCache slug: Web/API/ServiceWorkerRegistration/updateViaCache page-type: web-api-instance-property browser-compat: api.ServiceWorkerRegistration.updateViaCache --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`updateViaCache`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface updates the cache using the mode specified in the call to {{domxref('ServiceWorkerContainer.register')}}. Requests for `importScripts` still go via the HTTP cache. `updateViaCache` offers control over this behavior. {{AvailableInWorkers}} ## Value Returns one of the following values: - `imports`, meaning the HTTP cache is not consulted for update of the service worker, but is consulted for `importScripts`. - `all`, meaning the HTTP cache is consulted in both cases - `none`, meaning the HTTP cache is never consulted. ## Examples The following example shows the use of updateViaCache. ```js if ("serviceWorker" in navigator) { navigator.serviceWorker .register("/service-worker.js", { updateViaCache: "none", }) .then((registration) => { registration.addEventListener("updatefound", () => { // If updatefound is fired, it means that there's // a new service worker being installed. console.log(`Value of updateViaCache: ${registration.updateViaCache}`); }); }) .catch((error) => { console.error(`Service worker registration failed: ${error}`); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/paymentmanager/index.md
--- title: "ServiceWorkerRegistration: paymentManager property" short-title: paymentManager slug: Web/API/ServiceWorkerRegistration/paymentManager page-type: web-api-instance-property status: - experimental browser-compat: api.ServiceWorkerRegistration.paymentManager --- {{APIRef("Payment Handler API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`paymentManager`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface returns a payment app's {{domxref("PaymentManager")}} instance, which is used to manage various payment app functionality. {{AvailableInWorkers}} ## Value A {{domxref("PaymentManager")}} object instance. ## Examples ```js navigator.serviceWorker.register("serviceworker.js").then((registration) => { registration.paymentManager.userHint = "Card number should be 16 digits"; registration.paymentManager .enableDelegations(["shippingAddress", "payerName"]) .then(() => { // ... }); // ... }); ``` - {{domxref("PaymentManager.userHint")}} is used to provide a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI. - {{domxref("PaymentManager.enableDelegations()")}} is used to delegate responsibility for providing various parts of the required payment information to the payment app rather than collecting it from within the merchant website. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Payment Handler API", "", "", "nocode")}} - [Web-based payment apps overview](https://web.dev/articles/web-based-payment-apps-overview) - [Setting up a payment method](https://web.dev/articles/setting-up-a-payment-method) - [Life of a payment transaction](https://web.dev/articles/life-of-a-payment-transaction) - [Using the Payment Request API](/en-US/docs/Web/API/Payment_Request_API/Using_the_Payment_Request_API) - [Payment processing concepts](/en-US/docs/Web/API/Payment_Request_API/Concepts)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/getnotifications/index.md
--- title: "ServiceWorkerRegistration: getNotifications() method" short-title: getNotifications() slug: Web/API/ServiceWorkerRegistration/getNotifications page-type: web-api-instance-method browser-compat: api.ServiceWorkerRegistration.getNotifications --- {{APIRef("Web Notifications")}}{{SecureContext_Header}} The **`getNotifications()`** method of the {{domxref("ServiceWorkerRegistration")}} interface returns a list of the notifications in the order that they were created from the current origin via the current service worker registration. Origins can have many active but differently-scoped service worker registrations. Notifications created by one service worker on the same origin will not be available to other active service workers on that same origin. {{AvailableInWorkers}} ## Syntax ```js-nolint getNotifications() getNotifications(options) ``` ### Parameters - `options` {{optional_inline}} - : An object containing options to filter the notifications returned. The available options are: - `tag` {{optional_inline}} - : A string representing a notification tag. If specified, only notifications that have this tag will be returned. ### Return value A {{jsxref("Promise")}} that resolves to a list of {{domxref("Notification")}} objects. ## Examples ```js navigator.serviceWorker.register("sw.js"); const options = { tag: "user_alerts" }; navigator.serviceWorker.ready.then((registration) => { registration.getNotifications(options).then((notifications) => { // do something with your notifications }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/pushmanager/index.md
--- title: "ServiceWorkerRegistration: pushManager property" short-title: pushManager slug: Web/API/ServiceWorkerRegistration/pushManager page-type: web-api-instance-property browser-compat: api.ServiceWorkerRegistration.pushManager --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`pushManager`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions; this includes support for subscribing, getting an active subscription, and accessing push permission status. {{AvailableInWorkers}} ## Value A {{domxref("PushManager")}} object. ## Examples ```js this.onpush = (event) => { console.log(event.data); // From here we can write the data to IndexedDB, send it to any open // windows, display a notification, etc. }; navigator.serviceWorker .register("serviceworker.js") .then((serviceWorkerRegistration) => { serviceWorkerRegistration.pushManager.subscribe().then( (pushSubscription) => { console.log(pushSubscription.subscriptionId); console.log(pushSubscription.endpoint); // The push subscription details needed by the application // server are now available, and can be sent to it using, // for example, the fetch() API. }, (error) => { // During development it often helps to log errors to the // console. In a production environment it might make sense to // also report information about errors back to the // application server. console.error(error); }, ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Push API](/en-US/docs/Web/API/Push_API)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/waiting/index.md
--- title: "ServiceWorkerRegistration: waiting property" short-title: waiting slug: Web/API/ServiceWorkerRegistration/waiting page-type: web-api-instance-property browser-compat: api.ServiceWorkerRegistration.waiting --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`waiting`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface returns a service worker whose {{domxref("ServiceWorker.state")}} is `installed`. This property is initially set to `null`. {{AvailableInWorkers}} ## Value A {{domxref("ServiceWorker")}} object, if it is currently in an `installed` state. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/unregister/index.md
--- title: "ServiceWorkerRegistration: unregister() method" short-title: unregister() slug: Web/API/ServiceWorkerRegistration/unregister page-type: web-api-instance-method browser-compat: api.ServiceWorkerRegistration.unregister --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`unregister()`** method of the {{domxref("ServiceWorkerRegistration")}} interface unregisters the service worker registration and returns a {{jsxref("Promise")}}. The promise will resolve to `false` if no registration was found, otherwise it resolves to `true` irrespective of whether unregistration happened or not (it may not unregister if someone else just called {{domxref("ServiceWorkerContainer.register()")}} with the same scope.) The service worker will finish any ongoing operations before it is unregistered. {{AvailableInWorkers}} ## Syntax ```js-nolint unregister() ``` ### Parameters None. ### Return value {{jsxref("Promise")}} resolves with a boolean indicating whether the service worker has unregistered or not. ## Examples The following simple example registers a service worker example, but then immediately unregisters it again: ```js if ("serviceWorker" in navigator) { navigator.serviceWorker .register("/sw.js", { scope: "/" }) .then((registration) => { // registration worked console.log("Registration succeeded."); registration.unregister().then((boolean) => { // if boolean = true, unregister is successful }); }) .catch((error) => { // registration failed console.error(`Registration failed with ${error}`); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/installing/index.md
--- title: "ServiceWorkerRegistration: installing property" short-title: installing slug: Web/API/ServiceWorkerRegistration/installing page-type: web-api-instance-property browser-compat: api.ServiceWorkerRegistration.installing --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`installing`** read-only property of the {{domxref("ServiceWorkerRegistration")}} interface returns a service worker whose {{domxref("ServiceWorker.state")}} is `installing`. This property is initially set to `null`. {{AvailableInWorkers}} ## Value A {{domxref("ServiceWorker")}} object, if it is currently in an `installing` state. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0
data/mdn-content/files/en-us/web/api/serviceworkerregistration
data/mdn-content/files/en-us/web/api/serviceworkerregistration/update/index.md
--- title: "ServiceWorkerRegistration: update() method" short-title: update() slug: Web/API/ServiceWorkerRegistration/update page-type: web-api-instance-method browser-compat: api.ServiceWorkerRegistration.update --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`update()`** method of the {{domxref("ServiceWorkerRegistration")}} interface attempts to update the service worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker. The fetch of the worker bypasses any browser caches if the previous fetch occurred over 24 hours ago. {{AvailableInWorkers}} ## Syntax ```js-nolint update() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with a {{domxref("ServiceWorkerRegistration")}} object. ## Examples The following simple example registers a service worker example then adds an event handler to a button so you can explicitly update the service worker whenever desired: ```js if ("serviceWorker" in navigator) { navigator.serviceWorker .register("/sw.js", { scope: "/" }) .then((registration) => { // registration worked console.log("Registration succeeded."); button.onclick = () => { registration.update(); }; }) .catch((error) => { // registration failed console.error(`Registration failed with ${error}`); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using Service Workers](/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers) - [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) - [Using web workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)
0