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/htmltableelement
data/mdn-content/files/en-us/web/api/htmltableelement/tbodies/index.md
--- title: "HTMLTableElement: tBodies property" short-title: tBodies slug: Web/API/HTMLTableElement/tBodies page-type: web-api-instance-property browser-compat: api.HTMLTableElement.tBodies --- {{APIRef("HTML DOM")}} The **`HTMLTableElement.tBodies`** read-only property returns a live {{domxref("HTMLCollection")}} of the bodies in a {{htmlElement("table")}}. Although the property is read-only, the returned object is live and allows the modification of its content. The collection returned includes implicit {{HTMLElement("tbody")}} elements. For example: ```html <table> <tr> <td>cell one</td> </tr> </table> ``` The HTML DOM generated from the above HTML will have a {{HTMLElement("tbody")}} element even though the tags are not included in the source HTML. ## Value A live {{domxref("HTMLCollection")}}. ## Examples This snippet gets the number of bodies in a table. ```js mytable.tBodies.length; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCollection")}} - {{HTMLElement("tbody")}}
0
data/mdn-content/files/en-us/web/api/htmltableelement
data/mdn-content/files/en-us/web/api/htmltableelement/align/index.md
--- title: "HTMLTableElement: align property" short-title: align slug: Web/API/HTMLTableElement/align page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLTableElement.align --- {{APIRef("HTML DOM")}}{{Deprecated_Header}} The **`HTMLTableElement.align`** property represents the alignment of the table. ## Value One of the following string values: - `left` - `center` - `right` ## Examples ```js // Set the alignment of a table const t = document.getElementById("TableA"); t.align = "center"; ``` ## Specifications - W3C DOM 2 HTML Specification [_HTMLTableElement.align_](https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-23180977). ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/documentpictureinpicture/index.md
--- title: DocumentPictureInPicture slug: Web/API/DocumentPictureInPicture page-type: web-api-interface status: - experimental browser-compat: api.DocumentPictureInPicture --- {{APIRef("Document Picture-in-Picture API")}}{{SeeCompatTable}}{{securecontext_header}} The **`DocumentPictureInPicture`** interface of the {{domxref("Document Picture-in-Picture API", "Document Picture-in-Picture API", "", "nocode")}} is the entry point for creating and handling document picture-in-picture windows. It is accessed via the {{domxref("Window.documentPictureInPicture")}} property. {{InheritanceDiagram}} ## Instance properties - {{domxref("DocumentPictureInPicture.window", "window")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("Window")}} instance representing the browsing context inside the Picture-in-Picture window. ## Instance methods - {{domxref("DocumentPictureInPicture.requestWindow", "requestWindow()")}} {{Experimental_Inline}} - : Opens the Picture-in-Picture window for the current main browsing context. Returns a {{jsxref("Promise")}} that fulfills with a {{domxref("Window")}} instance representing the browsing context inside the Picture-in-Picture window. ## Events - {{domxref("DocumentPictureInPicture/enter_event", "enter")}} {{Experimental_Inline}} - : Fired when the Picture-in-Picture window is successfully opened. ## Examples ```js const videoPlayer = document.getElementById("player"); // ... // Open a Picture-in-Picture window. const pipWindow = await window.documentPictureInPicture.requestWindow({ width: videoPlayer.clientWidth, height: videoPlayer.clientHeight, }); // ... ``` See [Document Picture-in-Picture API Example](https://mdn.github.io/dom-examples/document-picture-in-picture/) for a full working demo (see the full [source code](https://github.com/chrisdavidmills/dom-examples/tree/main/document-picture-in-picture) also). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Document Picture-in-Picture API", "Document Picture-in-Picture API", "", "nocode")}} - [Using the Document Picture-in-Picture API](/en-US/docs/Web/API/Document_Picture-in-Picture_API/Using)
0
data/mdn-content/files/en-us/web/api/documentpictureinpicture
data/mdn-content/files/en-us/web/api/documentpictureinpicture/enter_event/index.md
--- title: "DocumentPictureInPicture: enter event" short-title: enter slug: Web/API/DocumentPictureInPicture/enter_event page-type: web-api-event status: - experimental browser-compat: api.DocumentPictureInPicture.enter_event --- {{APIRef("Document Picture-in-Picture API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`enter`** event of the {{domxref("DocumentPictureInPicture")}} interface is fired when the Picture-in-Picture window is successfully opened. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("enter", (event) => {}); onenter = (event) => {}; ``` ## Event type A {{domxref("DocumentPictureInPictureEvent")}}. ## Examples ```js documentPictureInPicture.addEventListener("enter", (event) => { const pipWindow = event.window; console.log("Video player has entered the pip window"); const pipMuteButton = pipWindow.document.createElement("button"); pipMuteButton.textContent = "Mute"; pipMuteButton.addEventListener("click", () => { const pipVideo = pipWindow.document.querySelector("#video"); if (!pipVideo.muted) { pipVideo.muted = true; pipMuteButton.textContent = "Unmute"; } else { pipVideo.muted = false; pipMuteButton.textContent = "Mute"; } }); pipWindow.document.body.append(pipMuteButton); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Document Picture-in-Picture API", "Document Picture-in-Picture API", "", "nocode")}} - [Using the Document Picture-in-Picture API](/en-US/docs/Web/API/Document_Picture-in-Picture_API/Using)
0
data/mdn-content/files/en-us/web/api/documentpictureinpicture
data/mdn-content/files/en-us/web/api/documentpictureinpicture/requestwindow/index.md
--- title: "DocumentPictureInPicture: requestWindow() method" short-title: requestWindow() slug: Web/API/DocumentPictureInPicture/requestWindow page-type: web-api-instance-method status: - experimental browser-compat: api.DocumentPictureInPicture.requestWindow --- {{APIRef("Document Picture-in-Picture API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`requestWindow()`** method of the {{domxref("DocumentPictureInPicture")}} interface opens the Picture-in-Picture window for the current main browsing context. It returns a {{jsxref("Promise")}} that fulfills with a {{domxref("Window")}} instance representing the browsing context inside the Picture-in-Picture window. The `requestWindow()` method requires [transient activation](/en-US/docs/Glossary/Transient_activation), i.e. it must be invoked in response to a user action such as a mouse click or button press. ## Syntax ```js-nolint requestWindow() requestWindow(options) ``` ### Parameters - `options` {{optional_inline}} - : An options object containing the following properties: - `height` - : A non-negative number representing the height to set for the Picture-in-Picture window's viewport, in pixels. If `options` is not specified, the default value 0 is used. - `width` - : A non-negative number representing the width to set for the Picture-in-Picture window's viewport, in pixels. If `options` is not specified, the default value 0 is used. > **Note:** If one of the options is specified, the other one must be too, otherwise an error is thrown. If both values are not specified, specified as 0, or set too large, the browser will clamp or ignore the values as appropriate to provide a reasonable user experience. The clamped size will vary depending on implementation, display size, and other factors. ### Return value A {{jsxref("Promise")}} that fulfills with a {{domxref("Window")}} object instance representing the browsing context inside the Picture-in-Picture window. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the API has been explicitly disabled (for example via browser settings). - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if: - `requestWindow()` is not called from a top-level `window` object. - `requestWindow()` is called from the `window` object of the Picture-in-Picture window (i.e. {{domxref("DocumentPictureInPicture.window")}}). - `requestWindow()` is called without {{Glossary("Transient_activation", "transient activation")}}. - `RangeError` {{domxref("DOMException")}} - : Thrown if only one of `height` and `width` are set, or if `height` and `width` are set with negative values. ## Examples ```js const videoPlayer = document.getElementById("player"); // ... // Open a Picture-in-Picture window. const pipWindow = await window.documentPictureInPicture.requestWindow({ width: videoPlayer.clientWidth, height: videoPlayer.clientHeight, }); // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Document Picture-in-Picture API", "Document Picture-in-Picture API", "", "nocode")}} - [Using the Document Picture-in-Picture API](/en-US/docs/Web/API/Document_Picture-in-Picture_API/Using)
0
data/mdn-content/files/en-us/web/api/documentpictureinpicture
data/mdn-content/files/en-us/web/api/documentpictureinpicture/window/index.md
--- title: "DocumentPictureInPicture: window property" short-title: window slug: Web/API/DocumentPictureInPicture/window page-type: web-api-instance-property status: - experimental browser-compat: api.DocumentPictureInPicture.window --- {{APIRef("Document Picture-in-Picture API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`window`** read-only property of the {{domxref("DocumentPictureInPicture")}} interface returns a {{domxref("Window")}} instance representing the browsing context inside the Picture-in-Picture window. ## Value A {{domxref("Window")}} object instance if the Picture-in-Picture window has already been opened using {{domxref("DocumentPictureInPicture.requestWindow()")}}, or `null` otherwise. ## Examples ```js const videoPlayer = document.getElementById("player"); // ... await window.documentPictureInPicture.requestWindow({ width: videoPlayer.clientWidth, height: videoPlayer.clientHeight, }); // ... const pipWindow = window.documentPictureInPicture.window; if (pipWindow) { // Mute video playing in the Picture-in-Picture window. const pipVideo = pipWindow.document.querySelector("#video"); pipVideo.muted = true; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Document Picture-in-Picture API", "Document Picture-in-Picture API", "", "nocode")}} - [Using the Document Picture-in-Picture API](/en-US/docs/Web/API/Document_Picture-in-Picture_API/Using)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgcomponenttransferfunctionelement/index.md
--- title: SVGComponentTransferFunctionElement slug: Web/API/SVGComponentTransferFunctionElement page-type: web-api-interface browser-compat: api.SVGComponentTransferFunctionElement --- {{APIRef("SVG")}} The **`SVGComponentTransferFunctionElement`** interface defines a base interface used by the component transfer function interfaces. {{InheritanceDiagram}} ## Constants <table class="no-markdown"> <tbody> <tr> <th>Name</th> <th>Value</th> <th>Description</th> </tr> <tr> <td><code>SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN</code></td> <td>0</td> <td> The type is not one of predefined types. It is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type. </td> </tr> <tr> <td><code>SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY</code></td> <td>1</td> <td>Corresponds to the value <code>identity</code>.</td> </tr> <tr> <td><code>SVG_FECOMPONENTTRANSFER_TYPE_TABLE</code></td> <td>2</td> <td>Corresponds to the value <code>table</code>.</td> </tr> <tr> <td><code>SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE</code></td> <td>3</td> <td>Corresponds to the value <code>discrete</code>.</td> </tr> <tr> <td><code>SVG_FECOMPONENTTRANSFER_TYPE_LINEAR</code></td> <td>4</td> <td>Corresponds to the value <code>linear</code>.</td> </tr> <tr> <td><code>SVG_FECOMPONENTTRANSFER_TYPE_GAMMA</code></td> <td>5</td> <td>Corresponds to the value <code>gamma</code>.</td> </tr> </tbody> </table> ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGComponentTransferFunctionElement.type")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("type")}} attribute of the given element. It takes one of the `SVG_FECOMPONENTTRANSFER_TYPE_*` constants defined on this interface. - {{domxref("SVGComponentTransferFunctionElement.tableValues")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumberList")}} corresponding to the {{SVGAttr("tableValues")}} attribute of the given element. - {{domxref("SVGComponentTransferFunctionElement.slope")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("slope")}} attribute of the given element. - {{domxref("SVGComponentTransferFunctionElement.intercept")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("intercept")}} attribute of the given element. - {{domxref("SVGComponentTransferFunctionElement.amplitude")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("amplitude")}} attribute of the given element. - {{domxref("SVGComponentTransferFunctionElement.exponent")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("exponent")}} attribute of the given element. - {{domxref("SVGComponentTransferFunctionElement.offset")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedNumber")}} corresponding to the {{SVGAttr("offset")}} 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 - {{domxref("SVGFEFuncAElement")}} - {{domxref("SVGFEFuncBElement")}} - {{domxref("SVGFEFuncGElement")}} - {{domxref("SVGFEFuncRElement")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/index.md
--- title: RTCInboundRtpStreamStats slug: Web/API/RTCInboundRtpStreamStats page-type: web-api-interface browser-compat: api.RTCStatsReport.type_inbound-rtp --- {{APIRef("WebRTC")}} The **`RTCInboundRtpStreamStats`** dictionary of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) is used to report statistics related to the receiving end of an RTP stream on the local end of the {{domxref("RTCPeerConnection")}}. The statistics can be obtained by iterating the {{domxref("RTCStatsReport")}} returned by {{domxref("RTCPeerConnection.getStats()")}} or {{domxref("RTCRtpReceiver.getStats()")}} until you find a report with the [`type`](#type) of `inbound-rtp`. ## Instance properties - {{domxref("RTCInboundRtpStreamStats.averageRtcpInterval", "averageRtcpInterval")}} - : A floating-point value indicating the average {{Glossary("RTCP")}} interval between two consecutive compound RTCP packets. - {{domxref("RTCInboundRtpStreamStats.bytesReceived", "bytesReceived")}} - : A 64-bit integer which indicates the total number of bytes that have been received so far for this media source. - {{domxref("RTCInboundRtpStreamStats.fecPacketsDiscarded", "fecPacketsDiscarded")}} - : An integer value indicating the number of RTP Forward Error Correction (FEC) packets which have been received for this source, for which the error correction payload was discarded. - {{domxref("RTCInboundRtpStreamStats.fecPacketsReceived", "fecPacketsReceived")}} - : An integer value indicating the total number of RTP FEC packets received for this source. This counter may also be incremented when FEC packets arrive in-band along with media content; this can happen with Opus, for example. - {{domxref("RTCInboundRtpStreamStats.firCount", "firCount")}} - : An integer value which indicates the total number of Full Intra Request (FIR) packets which this receiver has sent to the sender. This is an indicator of how often the stream has lagged, requiring frames to be skipped in order to catch up. This value is only available for video streams. - {{domxref("RTCInboundRtpStreamStats.framesDecoded", "framesDecoded")}} - : A long integer value indicating the total number of frames of video which have been correctly decoded so far for this media source. This is the number of frames that would have been rendered if none were dropped. _Only valid for video streams._ - {{domxref("RTCInboundRtpStreamStats.lastPacketReceivedTimestamp", "lastPacketReceivedTimestamp")}} - : A {{domxref("DOMHighResTimeStamp")}} indicating the time at which the last packet was received for this source. The [`timestamp`](#timestamp) property, on the other hand, indicates the time at which the statistics object was generated. - {{domxref("RTCInboundRtpStreamStats.nackCount", "nackCount")}} - : An integer value indicating the total number of Negative ACKnolwedgement (NACK) packets this receiver has sent. - {{domxref("RTCInboundRtpStreamStats.packetsDuplicated", "packetsDuplicated")}} - : An integer value indicating the total number of packets that have been discarded because they were duplicates. These packets are not counted by {{domxref("RTCInboundRtpStreamStats.packetsDiscarded", "packetsDiscarded")}}. - {{domxref("RTCInboundRtpStreamStats.packetsFailedDecryption", "packetsFailedDecryption")}} - : An integer totaling the number of RTP packets that could not be decrypted. These packets are not counted by {{domxref("RTCInboundRtpStreamStats.packetsDiscarded", "packetsDiscarded")}}. - {{domxref("RTCInboundRtpStreamStats.perDscpPacketsReceived", "perDscpPacketsReceived")}} - : A record of key-value pairs with strings as the keys mapped to 32-bit integer values, each indicating the total number of packets this receiver has received on this RTP stream from this source for each Differentiated Services Code Point (DSCP). - {{domxref("RTCInboundRtpStreamStats.pliCount", "pliCount")}} - : An integer specifying the number of times the receiver has notified the sender that some amount of encoded video data for one or more frames has been lost, using Picture Loss Indication (PLI) packets. This is only available for video streams. - {{domxref("RTCInboundRtpStreamStats.qpSum", "qpSum")}} - : A 64-bit value containing the sum of the QP values for every frame decoded by this RTP receiver. You can determine the average QP per frame by dividing this value by {{domxref("RTCInboundRtpStreamStats.framesDecoded", "framesDecoded")}}. _Valid only for video streams._ - {{domxref("RTCInboundRtpStreamStats.receiverId", "receiverId")}} - : A string indicating which identifies the {{domxref("RTCAudioReceiverStats")}} or {{domxref("RTCVideoReceiverStats")}} object associated with the stream's receiver. This ID is stable across multiple calls to `getStats()`. - {{domxref("RTCInboundRtpStreamStats.remoteId", "remoteId")}} - : A string which identifies the {{domxref("RTCRemoteOutboundRtpStreamStats")}} object that provides statistics for the remote peer for this same SSRC. This ID is stable across multiple calls to `getStats()`. - {{domxref("RTCInboundRtpStreamStats.sliCount", "sliCount")}} - : An integer indicating the number of times the receiver sent a Slice Loss Indication (SLI) frame to the sender to tell it that one or more consecutive (in terms of scan order) video macroblocks have been lost or corrupted. Available only for video streams. - `trackIdentifier` - : A string that contains the {{domxref("MediaStreamTrack.id", "id")}} value of the `MediaStreamTrack` associated with the inbound stream. - {{domxref("RTCInboundRtpStreamStats.trackId", "trackId")}} {{deprecated_inline}} - : A string which identifies the statistics object representing the receiving track; this object is one of two types: {{domxref("RTCReceiverAudioTrackAttachmentStats")}} or {{domxref("RTCReceiverVideoTrackAttachmentStats")}}. This ID is stable across multiple calls to `getStats()`. ### Statistics measured at the receiver of an RTP stream <!-- RTCReceivedRtpStreamStats --> These statistics are measured at the receiving end of an RTP stream, regardless of whether it's local or remote. - {{domxref("RTCInboundRtpStreamStats.packetsReceived", "packetsReceived")}} - : The total number of RTP packets received for this synchronizing source, including retransmissions. - {{domxref("RTCInboundRtpStreamStats.packetsLost", "packetsLost")}} - : The total number of RTP packets lost for this synchronizing source. Note that this can be negative if more packets are received than sent. - {{domxref("RTCInboundRtpStreamStats.jitter", "jitter")}} - : Packet jitter for this synchronizing source, measured in seconds. ### Standard fields included for all media types <!-- RTCRtpStreamStats --> - {{domxref("RTCInboundRtpStreamStats.codecId", "codecId")}} - : A string which uniquely identifies the object which was inspected to produce the {{domxref("RTCCodecStats")}} object associated with this {{Glossary("RTP")}} stream. - {{domxref("RTCInboundRtpStreamStats.kind", "kind")}} - : A string whose value is `"audio"` if the associated {{domxref("MediaStreamTrack")}} is audio-only or `"video"` if the track contains video. This value will match that of the media type indicated by {{domxref("RTCCodecStats.codec")}}, as well as the track's {{domxref("MediaStreamTrack.kind", "kind")}} property. Previously called `mediaType`. - {{domxref("RTCInboundRtpStreamStats.ssrc", "ssrc")}} - : The 32-bit integer which identifies the source of the RTP packets this `RTCRtpStreamStats` object covers. This value is generated per the {{RFC(3550)}} specification. - {{domxref("RTCInboundRtpStreamStats.trackId", "trackId")}} - : A string which uniquely identifies the {{domxref("RTCMediaStreamTrackStats")}} object representing the associated {{domxref("MediaStreamTrack")}}. This is _not_ the same as the value of {{domxref("MediaStreamTrack.id")}}. - {{domxref("RTCInboundRtpStreamStats.transportId", "transportId")}} - : A string uniquely identifying the object which was inspected to produce the {{domxref("RTCTransportStats")}} object associated with this RTP stream. ### Local-only measurements These properties are computed locally, and are only available to the device receiving the media stream. Their primary purpose is to examine the error resiliency of the connection, as they provide information about lost packets, lost frames, and how heavily compressed the data is. - {{domxref("RTCInboundRtpStreamStats.firCount", "firCount")}} - : A count of the total number of Full Intra Request (FIR) packets received by the sender. This statistic is only available to the device which is receiving the stream and is only available for video tracks. A FIR packet is sent by the receiving end of the stream when it falls behind or has lost packets and is unable to continue decoding the stream; the sending end of the stream receives the FIR packet and responds by sending a full frame instead of a delta frame, thereby letting the receiver "catch up." The higher this number is, the more often a problem of this nature arose, which can be a sign of network congestion or an overburdened receiving device. - {{domxref("RTCInboundRtpStreamStats.nackCount", "nackCount")}} - : The number of times the receiver notified the sender that one or more RTP packets has been lost by sending a Negative ACKnowledgement (NACK, also called "Generic NACK") packet to the sender. This value is only available to the receiver. - {{domxref("RTCInboundRtpStreamStats.pliCount", "pliCount")}} - : The number of times the receiving end of the stream sent a Picture Loss Indication (PLI) packet to the sender, indicating that it has lost some amount of encoded video data for one or more frames. Only the receiver has this value, and it's only valid for video tracks. - {{domxref("RTCInboundRtpStreamStats.qpSum", "qpSum")}} - : The sum of the Quantization Parameter (QP) values associated with every frame received to date on the video track described by this `RTCRtpStreamStats` object. In general, the higher this number is, the more heavily compressed the video track was. Combined with {{domxref("RTCReceivedRtpStreamStats.framesDecoded")}} or {{domxref("RTCInboundRtpStreamStats.framesEncoded")}}, you can approximate the average QP over those frames, keeping in mind that codecs often vary the quantizer values even within frames. Also keep in mind that the values of QP can vary from codec to codec, so this value is only potentially useful when compared against the same codec. ### Common instance properties The following properties are common to all WebRTC statistics objects. <!-- RTCStats --> - {{domxref("RTCInboundRtpStreamStats.id", "id")}} - : A string that uniquely identifies the object that is being monitored to produce this set of statistics. - {{domxref("RTCInboundRtpStreamStats.timestamp", "timestamp")}} - : A {{domxref("DOMHighResTimeStamp")}} object indicating the time at which the sample was taken for this statistics object. - {{domxref("RTCInboundRtpStreamStats.type", "type")}} - : A string with the value `"inbound-rtp"`, indicating the type of statistics that the object contains. ## Examples ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("RTCStatsReport")}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/slicount/index.md
--- title: "RTCInboundRtpStreamStats: sliCount property" short-title: sliCount slug: Web/API/RTCInboundRtpStreamStats/sliCount page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.sliCount --- {{APIRef("WebRTC")}} The **`sliCount`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary indicates how many **Slice Loss Indication** (**SLI**) packets the {{domxref("RTCRtpReceiver")}} for which this object provides statistics sent to the remote {{domxref("RTCRtpSender")}}. An SLI packet is used by a decoder to let the encoder know that it's detected corruption of one or more consecutive macroblocks (in scan order) in the received media. In general, what's usually of interest is that the higher this number is, the more the stream data is becoming corrupted between the sender and the receiver, requiring resends or dropping frames. ## Value An unsigned integer indicating the number of SLI packets this receiver sent to the remote sender due to lost runs of macroblocks. A high value of `sliCount` may be an indication of an unreliable network. This is a very technical part of how video codecs work. For details, see {{RFC(4585, "6.3.2")}}. > **Note:** This value is only present for video media. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{RFC(4585, "", "6.3.2")}}: Definition of "Slice Loss Indication" in the document _Extended RTP Profile for Real-time Transport Control Protocol (RTCP)-Based Feedback (RTP/AVPF)_.
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/plicount/index.md
--- title: "RTCInboundRtpStreamStats: pliCount property" short-title: pliCount slug: Web/API/RTCInboundRtpStreamStats/pliCount page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.pliCount --- {{APIRef("WebRTC")}} The **`pliCount`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary states the number of times the {{domxref("RTCRtpReceiver")}} described by these statistics sent a **Picture Loss Indication** (**PLI**) packet to the sender. A PLI packet indicates that some amount of encoded video data has been lost for one or more frames. ## Value An integer value indicating the number of times a PLI packet was sent by the {{domxref("RTCRtpReceiver")}} to the sender. These are sent by the receiver's decoder to notify the encoder (the sender) that an undefined amount of coded video data, which may span frame boundaries, has been lost. This information is only available for video streams. This may trigger the sender to send a full frame in order to allow the receiver to re-synchronize, since lost data may be an irrecoverable situation for decoding media. However, the primary purpose of this message is to allow the sender to consider techniques to mitigate network performance issues. This is often achieved by methods such as increasing the compression, lowering resolution, or finding other ways to reduce the bit rate of the stream. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{RFC(4585, "", "6.3.1")}}: Definition of "PLI messages" in the document _Extended RTP Profile for Real-time Transport Control Protocol (RTCP)-Based Feedback (RTP/AVPF)_.
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/lastpacketreceivedtimestamp/index.md
--- title: "RTCInboundRtpStreamStats: lastPacketReceivedTimestamp property" short-title: lastPacketReceivedTimestamp slug: Web/API/RTCInboundRtpStreamStats/lastPacketReceivedTimestamp page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.lastPacketReceivedTimestamp --- {{APIRef("WebRTC")}} The **`lastPacketReceivedTimestamp`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary indicates the time at which the most recently received packet arrived from this source. ## Value A {{domxref("DOMHighResTimeStamp")}} which specifies the time at which the most recently received packet arrived on this RTP stream. > **Note:** This value differs from the {{domxref("RTCInboundRtpStreamStats.timestamp", "timestamp")}}, > which represents the time at which the statistics object was created. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/trackid/index.md
--- title: "RTCInboundRtpStreamStats: trackId property" short-title: trackId slug: Web/API/RTCInboundRtpStreamStats/trackId page-type: web-api-instance-property status: - deprecated browser-compat: api.RTCInboundRtpStreamStats.trackId --- {{APIRef("WebRTC")}} {{Deprecated_Header}} The **`trackId`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary indicates the {{domxref("RTCInboundRtpStreamStats.id", "id")}} of the {{domxref("RTCReceiverAudioTrackAttachmentStats")}} or {{domxref("RTCReceiverVideoTrackAttachmentStats")}} object representing the {{domxref("MediaStreamTrack")}} which is receiving the incoming media. ## Value A string containing the ID of the {{domxref("RTCReceiverAudioTrackAttachmentStats")}} or {{domxref("RTCReceiverVideoTrackAttachmentStats")}} object representing the track which is receiving the media from this RTP session. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/averagertcpinterval/index.md
--- title: "RTCInboundRtpStreamStats: averageRtcpInterval property" short-title: averageRtcpInterval slug: Web/API/RTCInboundRtpStreamStats/averageRtcpInterval page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.averageRtcpInterval --- {{APIRef("WebRTC")}} The **`averageRtcpInterval`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary is a floating-point value indicating the average {{Glossary("RTCP")}} transmission interval, in seconds. The RTCP interval is the amount of time that should elapse between transmissions of RTCP packets. ## Value A floating-point value indicating the average interval, in seconds, between transmissions of RTCP packets. This interval is computed following the formula outlined in {{RFC(1889, "A.7")}}. Because the interval's value is determined in part by the number of active senders, it will be different for each user of a service. Since this value is also used to determine the number of seconds after a stream starts to flow before the first RTCP packet should be sent, the result is that if many users try to start using the service at the same time, the server won't be flooded with RTCP packets coming in all at once. The sending endpoint computes this value when sending compound RTCP packets, which must contain at least an RTCP RR or SR packet and an SDES packet with the CNAME item. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/fircount/index.md
--- title: "RTCInboundRtpStreamStats: firCount property" short-title: firCount slug: Web/API/RTCInboundRtpStreamStats/firCount page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.firCount --- {{APIRef("WebRTC")}} The **`firCount`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary indicates the number of **Full Intra Request** (**FIR**) packets have been sent by the receiver to the sender. The receiver sends a FIR packet when the stream falls behind and needs to skip frames in order to catch up. ## Value An integer value indicating how many FIR packets have been received by the sender during the current connection. This statistic is available only for video tracks. The receiver sends a FIR packet to the sender any time it falls behind or loses packets and cannot decode the incoming stream any longer because of the lost data. This tells the sender to send a full frame instead of a delta frame, so that the receiver can catch up. The higher `firCount` is, the more often frames were dropped, which may be an indication that the media's bit rate is too high for the available bandwidth, or that the receiving device is overburdened and is therefore unable to process the incoming data. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/fecpacketsdiscarded/index.md
--- title: "RTCInboundRtpStreamStats: fecPacketsDiscarded property" short-title: fecPacketsDiscarded slug: Web/API/RTCInboundRtpStreamStats/fecPacketsDiscarded page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.fecPacketsDiscarded --- {{APIRef("WebRTC")}} The **`fecPacketsDiscarded`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary is a numeric value indicating the number of {{Glossary("RTP")}} Forward Error Correction (FEC) packets that have been discarded. ## Value An unsigned integer value indicating how many FEC packets have been received whose error correction payload has been discarded. This can happen if all the packets covered by the FEC packet have already been received or recovered using another FEC packet, or if the FEC packet arrived outside the recovery window and the lost RTP packets have already been skipped during playback as a result. The value of `fecPacketsReceived` includes these discarded packets. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/bytesreceived/index.md
--- title: "RTCInboundRtpStreamStats: bytesReceived property" short-title: bytesReceived slug: Web/API/RTCInboundRtpStreamStats/bytesReceived page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.bytesReceived --- {{APIRef("WebRTC")}} The {{domxref("RTCInboundRtpStreamStats")}} dictionary's **`bytesReceived`** property is an integer value which indicates the total number of bytes received so far from this synchronization source (SSRC). ## Value An unsigned integer value indicating the total number of bytes received so far on this RTP stream, not including header and padding bytes. This value can be used to calculate an approximation of the average media data rate: ```js avgDataRate = rtcInboundRtpStreamStats.bytesReceived / elapsedTime; ``` This value gets reset to zero if the sender's SSRC identifier changes for any reason. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/receiverid/index.md
--- title: "RTCInboundRtpStreamStats: receiverId property" short-title: receiverId slug: Web/API/RTCInboundRtpStreamStats/receiverId page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.receiverId --- {{APIRef("WebRTC")}} The **`receiverId`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary specifies the {{domxref("RTCInboundRtpStreamStats.id", "id")}} of the {{domxref("RTCAudioReceiverStats")}} or {{domxref("RTCVideoReceiverStats")}} object representing the {{domxref("RTCRtpReceiver")}} receiving the stream. ## Value A string which contains the ID of the `RTCAudioReceiverStats` or `RTCVideoReceiverStats` object which provides information about the `RTCRtpReceiver` which is receiving the streamed media. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/packetsduplicated/index.md
--- title: "RTCInboundRtpStreamStats: packetsDuplicated property" short-title: packetsDuplicated slug: Web/API/RTCInboundRtpStreamStats/packetsDuplicated page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.packetsDuplicated --- {{APIRef("WebRTC")}} The **`packetsDuplicated`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary indicates the total number of packets discarded because they were duplicates of previously-received packets. These packets are not counted by the {{domxref("RTCInboundRtpStreamStats.packetsDiscarded", "packetsDiscarded")}} property. ## Value An integer value which specifies how many duplicate packets have been received by the local end of this RTP stream so far. These duplicate packets are not included in the {{domxref("RTCInboundRtpStreamStats.packetsDiscarded", "packetsDiscarded")}} property. ## Usage notes Duplicate packets are detected when a packet has the same RTP sequence number as another packet that has previously been processed. Each time a packet is repeated, the value of `packetsDuplicated` is incremented, even if the same packet is received more than twice. You can get a more accurate tally of how many packets have been lost on the stream by adding `packetsDuplicated` to {{domxref("RTCInboundRtpStreamStats.packetsLost", "packetsLost")}}. The resulting value will be positive, although it will not match the count as computed in {{RFC(3660)}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/qpsum/index.md
--- title: "RTCInboundRtpStreamStats: qpSum property" short-title: qpSum slug: Web/API/RTCInboundRtpStreamStats/qpSum page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.qpSum --- {{APIRef("WebRTC")}} The **`qpSum`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary is a value generated by adding the **Quantization Parameter** (**QP**) values for every frame sent or received to date on the video track corresponding to this `RTCInboundRtpStreamStats` object. In general, the higher this number is, the more heavily compressed the video data is. ## Value An unsigned 64-bit integer value which indicates the sum of the quantization parameter (QP) value for every frame sent or received so far on the track described by the {{domxref("RTCInboundRtpStreamStats")}} object. Since the value of QP is typically larger to indicate higher compression factors, the larger this sum is, the more heavily compressed the stream generally has been. > **Note:** This value is only available for video media. ## Usage notes [Quantization](https://en.wikipedia.org/wiki/Quantization) is the process of applying lossy compression to a range of values, resulting in a single **quantum value**. This value takes the place of the range of values, thereby reducing the number of different values that appear in the overall data set, making the data more compressible. The quantization process and the amount of compression can be controlled using one or more parameters. It's important to keep in mind that the value of QP can change periodically—even every frame—so it's difficult to know for certain how substantial the compression is. The best you can do is make an estimate. You can, for example, use the value of {{domxref("RTCReceivedRtpStreamStats.framesDecoded")}} if receiving the media or {{domxref("RTCSentRtpStreamStats.framesEncoded")}} if sending it to get the number of frames handled so far, and compute an average from there. See [Calculating average quantization](#calculating_average_quantization) below for a function that does this. Also, the exact meaning of the QP value depends on the {{Glossary("codec")}} being used. For example, for the VP8 codec, the QP value can be anywhere from 1 to 127 and is found in the frame header element `"y_ac_qi"`, whose value is defined in {{RFC(6386, "", "19.2")}}. H.264 uses a QP which ranges from 0 to 51; in this case, it's an index used to derive a scaling matrix used during the quantization process. Additionally, QP is not likely to be the only parameter the codec uses to adjust the compression. See the individual codec specifications for details. ## Examples ### Calculating average quantization The `calculateAverageQP()` function shown below computes the average QP for the given {{domxref("RTCStatsReport")}} object that contains RTP stream statistics, returning 0 if the object doesn't describe an RTP stream. ```js function calculateAverageQP(stats) { let frameCount = 0; switch (stats.type) { case "inbound-rtp": case "remote-inbound-rtp": frameCount = stats.framesDecoded; break; case "outbound-rtp": case "remote-outbound-rtp": frameCount = stats.framesEncoded; break; default: return 0; } return status.qpSum / frameCount; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/perdscppacketsreceived/index.md
--- title: "RTCInboundRtpStreamStats: perDscpPacketsReceived property" short-title: perDscpPacketsReceived slug: Web/API/RTCInboundRtpStreamStats/perDscpPacketsReceived page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.perDscpPacketsReceived --- {{APIRef("WebRTC")}} The **`perDscpPacketsReceived`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary is a record comprised of key/value pairs in which each key is a string representation of a Differentiated Services Code Point and the value is the number of packets received for that DCSP. > **Note:** Not all operating systems make data available on a per-DSCP > basis, so this property shouldn't be relied upon on those systems. ## Value A record comprised of string/value pairs. Each key is the string representation of a single Differentiated Services Code Point (DSCP)'s ID number. > **Note:** Due to network bleaching and remapping, the numbers seen on > this record are not necessarily going to match the values as they were when the data > was sent. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{RFC(2474)}}: The Differentiated Service field in IPv4 and IPv6 headers
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/packetsfaileddecryption/index.md
--- title: "RTCInboundRtpStreamStats: packetsFailedDecryption property" short-title: packetsFailedDecryption slug: Web/API/RTCInboundRtpStreamStats/packetsFailedDecryption page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.packetsFailedDecryption --- {{APIRef("WebRTC")}} The **`packetsFailedDecryption`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary indicates the total number of {{Glossary("RTP")}} packets which failed to be decrypted successfully after being received by the local end of the connection during this session. ## Value An integer value which indicates how many packets the local end of the RTP connection could not be successfully decrypted. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{RFC(3711, "", "3.3")}}: Description of the decryption process for secure RTP packets
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/id/index.md
--- title: "RTCInboundRtpStreamStats: id property" short-title: id slug: Web/API/RTCInboundRtpStreamStats/id page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.id --- {{APIRef("WebRTC")}} The **`id`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary is a string that uniquely identifies the object for which this object provides statistics. Using the `id`, you can correlate this statistics object with others, in order to monitor statistics over time for a given WebRTC object, such as an {{domxref("RTCPeerConnection")}}, or an {{domxref("RTCDataChannel")}}. ## Value A string that uniquely identifies the object for which this `RTCInboundRtpStreamStats` object provides statistics. The format of the ID string is not defined by the specification, so you cannot reliably make any assumptions about the contents of the string, or assume that the format of the string will remain unchanged for a given object type. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/type/index.md
--- title: "RTCInboundRtpStreamStats: type property" short-title: type slug: Web/API/RTCInboundRtpStreamStats/type page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.type --- {{APIRef("WebRTC")}} The **`type`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary is a string with the value `"inbound-rtp"`. Different statistics are obtained by iterating the {{domxref("RTCStatsReport")}} object returned by a call to {{domxref("RTCPeerConnection.getStats()")}}. The type indicates the set of statistics available through the object in a particular iteration step. A value of `"inbound-rtp"` indicates that the statistics available in the current step are those defined in {{domxref("RTCInboundRtpStreamStats")}}. ## Value A string with the value `"inbound-rtp"`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/timestamp/index.md
--- title: "RTCInboundRtpStreamStats: timestamp property" short-title: timestamp slug: Web/API/RTCInboundRtpStreamStats/timestamp page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.timestamp --- {{APIRef("WebRTC")}} The **`timestamp`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary is a {{domxref("DOMHighResTimeStamp")}} object specifying the time at which the data in the object was sampled. ## Value A {{domxref("DOMHighResTimeStamp")}} value indicating the time at which the activity described by the statistics in this object was recorded, in milliseconds elapsed since the beginning of January 1, 1970, UTC. The value should be accurate to within a few milliseconds but may not be entirely precise, either because of hardware or operating system limitations or because of [fingerprinting](/en-US/docs/Glossary/Fingerprinting) protection in the form of reduced clock precision or accuracy. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/remoteid/index.md
--- title: "RTCInboundRtpStreamStats: remoteId property" short-title: remoteId slug: Web/API/RTCInboundRtpStreamStats/remoteId page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.remoteId --- {{APIRef("WebRTC")}} The **`remoteId`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary specifies the {{domxref("RTCInboundRtpStreamStats.id", "id")}} of the {{domxref("RTCRemoteOutboundRtpStreamStats")}} object representing the remote peer's {{domxref("RTCRtpSender")}} which is sending the media to the local peer. ## Value A string containing the ID of the {{domxref("RTCRemoteOutboundRtpStreamStats")}} object that represents the remote peer's {{domxref("RTCRtpSender")}} for the synchronization source represented by this stats object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/fecpacketsreceived/index.md
--- title: "RTCInboundRtpStreamStats: fecPacketsReceived property" short-title: fecPacketsReceived slug: Web/API/RTCInboundRtpStreamStats/fecPacketsReceived page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.fecPacketsReceived --- {{APIRef("WebRTC")}} The **`fecPacketsReceived`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary indicates how many Forward Error Correction (FEC) packets have been received by this RTP receiver from the remote peer. An FEC packet provides parity information which can be used to attempt to reconstruct RTP data packets which have been corrupted in transit. ## Syntax ```js-nolint const fecPacketsReceived = rtcInboundRtpStreamStats.fecPacketsReceived ``` ### Value An unsigned integer value which indicates the total number of FEC packets which have been received from the remote peer during this RTP session. Forward Error Correction uses an exclusive-or method to perform parity checks on the received data. By using the FEC parity information to attempt to reconstruct damaged packets, it is possible to avoid the need to retransmit damaged packets, which in turn helps to reduce lag, or the need to skip damaged frames entirely. > **Note:** This counter may also be incremented when FEC packets arrive > in-band along with media content; this can happen with Opus, for example. ## Usage notes It's possible that a subset of the FEC packets which have been received were discarded instead of being used. This can happen if the packets covered by the FEC packets have already been received successfully or have already been reconstructed using a previously-received FEC packet. This may also happen if the FEC packet arrives outside the window of time in which the client will attempt to use it. If you wish to know how many of the received packets were discarded, you can examine the value of {{domxref("RTCInboundRtpStreamStats.fecPacketsDiscarded", "fecPacketsDiscarded")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{RFC(5109)}} (RTP Payload Format for Generic Forward Error Correction)
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/nackcount/index.md
--- title: "RTCInboundRtpStreamStats: nackCount property" short-title: nackCount slug: Web/API/RTCInboundRtpStreamStats/nackCount page-type: web-api-instance-property browser-compat: api.RTCStatsReport.type_inbound-rtp.nackCount --- {{APIRef("WebRTC")}} The **`nackCount`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary is a numeric value indicating the number of times the receiver sent a **NACK** packet to the sender. A NACK (Negative ACKnowledgement, also called "Generic NACK") packet tells the sender that one or more of the {{Glossary("RTP")}} packets it sent were lost in transport. ## Value An integer value indicating how many times the receiver sent a NACK packet to the sender after detecting that one or more packets were lost during transport. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats
data/mdn-content/files/en-us/web/api/rtcinboundrtpstreamstats/framesdecoded/index.md
--- title: "RTCInboundRtpStreamStats: framesDecoded property" short-title: framesDecoded slug: Web/API/RTCInboundRtpStreamStats/framesDecoded page-type: web-api-instance-property browser-compat: api.RTCInboundRtpStreamStats.framesDecoded --- {{APIRef("WebRTC")}} The **`framesDecoded`** property of the {{domxref("RTCInboundRtpStreamStats")}} dictionary indicates the total number of frames which have been decoded successfully for this media source. ## Value An integer value indicating the total number of video frames which have been decoded for this stream so far. This represents the number of frames that would have been displayed assuming no frames were skipped. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/cssfontfacerule/index.md
--- title: CSSFontFaceRule slug: Web/API/CSSFontFaceRule page-type: web-api-interface browser-compat: api.CSSFontFaceRule --- {{APIRef("CSSOM")}} The **`CSSFontFaceRule`** interface represents an {{cssxref("@font-face")}} [at-rule](/en-US/docs/Web/CSS/At-rule). {{InheritanceDiagram}} ## Instance properties _Inherits properties from its ancestor {{domxref("CSSRule")}}._ - {{domxref("CSSFontFaceRule.style")}} {{ReadOnlyInline}} - : Returns a {{domxref("CSSStyleDeclaration")}}. ## Instance methods _Inherits methods from its ancestor {{domxref("CSSRule")}}._ ## Examples This example uses the CSS found as an example on the {{cssxref("@font-face")}} page. The first {{domxref("CSSRule")}} returned will be a `CSSFontFaceRule`. ```css @font-face { font-family: MyHelvetica; src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"), url(MgOpenModernaBold.ttf); font-weight: bold; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0]); //a CSSFontFaceRule ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/cssfontfacerule
data/mdn-content/files/en-us/web/api/cssfontfacerule/style/index.md
--- title: "CSSFontFaceRule: style property" short-title: style slug: Web/API/CSSFontFaceRule/style page-type: web-api-instance-property browser-compat: api.CSSFontFaceRule.style --- {{APIRef("CSSOM")}} The read-only **`style`** property of the {{domxref("CSSFontFaceRule")}} interface returns the style information from the {{cssxref("@font-face")}} [at-rule](/en-US/docs/Web/CSS/At-rule). This will be in the form of a {{domxref("CSSStyleDeclaration")}} object. ## Value A {{domxref("CSSStyleDeclaration")}}. ## Examples This example uses the CSS found as an example on the {{cssxref("@font-face")}} page. The first {{domxref("CSSRule")}} returned will be a `CSSFontFaceRule`. The `style` property returns a {{domxref("CSSStyleDeclaration")}} with the properties `fontFamily`, `fontWeight`, and `src` populated with the information from the rule. ```css @font-face { font-family: MyHelvetica; src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"), url(MgOpenModernaBold.ttf); font-weight: bold; } ``` ```js let myRules = document.styleSheets[0].cssRules; console.log(myRules[0].style); //a CSSStyleDeclaration ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpupipelinelayout/index.md
--- title: GPUPipelineLayout slug: Web/API/GPUPipelineLayout page-type: web-api-interface status: - experimental browser-compat: api.GPUPipelineLayout --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPUPipelineLayout`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} defines the {{domxref("GPUBindGroupLayout")}}s used by a pipeline. {{domxref("GPUBindGroup")}}s used with the pipeline during command encoding must have compatible {{domxref("GPUBindGroupLayout")}}s. A `GPUPipelineLayout` object instance is created using the {{domxref("GPUDevice.createPipelineLayout()")}} method. {{InheritanceDiagram}} ## Instance properties - {{domxref("GPUPipelineLayout.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. ## Examples > **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples. ### Basic pipeline layout example The following snippet: - Creates a {{domxref("GPUBindGroupLayout")}} that describes a binding with a buffer, a texture, and a sampler. - Creates a {{domxref("GPUPipelineLayout")}} based on the {{domxref("GPUBindGroupLayout")}}. ```js // ... const bindGroupLayout = device.createBindGroupLayout({ entries: [ { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: {}, }, { binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: {}, }, { binding: 2, visibility: GPUShaderStage.FRAGMENT, sampler: {}, }, ], }); const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout], }); // ... ``` ## 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/gpupipelinelayout
data/mdn-content/files/en-us/web/api/gpupipelinelayout/label/index.md
--- title: "GPUPipelineLayout: label property" short-title: label slug: Web/API/GPUPipelineLayout/label page-type: web-api-instance-property status: - experimental browser-compat: api.GPUPipelineLayout.label --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`label`** property of the {{domxref("GPUPipelineLayout")}} interface provides 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.createPipelineLayout()")}} call, or you can get and set it directly on the `GPUPipelineLayout` 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 `GPUPipelineLayout.label`: ```js // ... const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout], }); pipelineLayout.label = "mypipelinelayout"; console.log(pipelineLayout.label); // "mypipelinelayout"; ``` Setting a label via the originating {{domxref("GPUDevice.createPipelineLayout()")}} call, and then getting it via `GPUPipelineLayout.label`: ```js // ... const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [bindGroupLayout], label: "mypipelinelayout", }); console.log(pipelineLayout.label); // "mypipelinelayout"; ``` ## 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/webtransporterror/index.md
--- title: WebTransportError slug: Web/API/WebTransportError page-type: web-api-interface browser-compat: api.WebTransportError --- {{APIRef("WebTransport API")}}{{SecureContext_Header}} The **`WebTransportError`** interface of the {{domxref("WebTransport API", "WebTransport API", "", "nocode")}} represents an error related to the API, which can arise from server errors, network connection problems, or client-initiated abort operations (for example, arising from a {{domxref("WritableStream.abort()")}} call). {{InheritanceDiagram}} {{AvailableInWorkers}} ## Constructor - {{domxref("WebTransportError.WebTransportError", "WebTransportError()")}} - : Creates a new `WebTransportError` object instance. ## Instance properties _Inherits properties from its parent, {{DOMxRef("DOMException")}}._ - {{domxref("WebTransportError.source", "source")}} {{ReadOnlyInline}} - : Returns an enumerated value indicating the source of the error—can be either `stream` or `session`. - {{domxref("WebTransportError.streamErrorCode", "streamErrorCode")}} {{ReadOnlyInline}} - : Returns a number in the range 0-255 indicating the application protocol error code for this error, or `null` if one is not available. ## Examples ```js const url = "notaurl"; async function initTransport(url) { try { // Initialize transport connection const transport = new WebTransport(url); // The connection can be used once ready fulfills await transport.ready; // ... } catch (error) { const msg = `Transport initialization failed. Reason: ${error.message}. Source: ${error.source}. Error code: ${error.streamErrorCode}.`; console.log(msg); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport) - {{domxref("WebSockets API", "WebSockets API", "", "nocode")}} - {{domxref("Streams API", "Streams API", "", "nocode")}} - [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
0
data/mdn-content/files/en-us/web/api/webtransporterror
data/mdn-content/files/en-us/web/api/webtransporterror/source/index.md
--- title: "WebTransportError: source property" short-title: source slug: Web/API/WebTransportError/source page-type: web-api-instance-property browser-compat: api.WebTransportError.source --- {{APIRef("WebTransport API")}}{{SecureContext_Header}} The **`source`** read-only property of the {{domxref("WebTransportError")}} interface returns an enumerated value indicating the source of the error. {{AvailableInWorkers}} ## Value An enumerated value; can be either `stream` or `session`. ## Examples ```js const url = "notaurl"; async function initTransport(url) { try { // Initialize transport connection const transport = new WebTransport(url); // The connection can be used once ready fulfills await transport.ready; // ... } catch (error) { const msg = `Transport initialization failed. Reason: ${error.message}. Source: ${error.source}. Error code: ${error.streamErrorCode}.`; console.log(msg); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport) - {{domxref("WebSockets API", "WebSockets API", "", "nocode")}} - {{domxref("Streams API", "Streams API", "", "nocode")}} - [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
0
data/mdn-content/files/en-us/web/api/webtransporterror
data/mdn-content/files/en-us/web/api/webtransporterror/webtransporterror/index.md
--- title: "WebTransportError: WebTransportError() constructor" short-title: WebTransportError() slug: Web/API/WebTransportError/WebTransportError page-type: web-api-constructor browser-compat: api.WebTransportError.WebTransportError --- {{APIRef("WebTransport API")}}{{SecureContext_Header}} The **`WebTransportError()`** constructor creates a new {{domxref("WebTransportError")}} object instance. {{AvailableInWorkers}} ## Syntax ```js-nolint new WebTransportError(init) ``` ### Parameters - `init` {{optional_inline}} - : An object containing the following properties: - `message` - : A string describing the error that has occurred. - `streamErrorCode` - : A number in the range 0-255 indicating the application protocol error code for this error. ## Examples A developer would not use this constructor manually. A new `WebTransportError` object is constructed when an error related to WebTransport occurs, for example a server error or network connection problem. ```js const url = "notaurl"; async function initTransport(url) { try { // Initialize transport connection const transport = new WebTransport(url); // The connection can be used once ready fulfills await transport.ready; // ... } catch (error) { const msg = `Transport initialization failed. Reason: ${error.message}. Source: ${error.source}. Error code: ${error.streamErrorCode}.`; console.log(msg); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport) - {{domxref("WebSockets API", "WebSockets API", "", "nocode")}} - {{domxref("Streams API", "Streams API", "", "nocode")}} - [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
0
data/mdn-content/files/en-us/web/api/webtransporterror
data/mdn-content/files/en-us/web/api/webtransporterror/streamerrorcode/index.md
--- title: "WebTransportError: streamErrorCode property" short-title: streamErrorCode slug: Web/API/WebTransportError/streamErrorCode page-type: web-api-instance-property browser-compat: api.WebTransportError.streamErrorCode --- {{APIRef("WebTransport API")}}{{SecureContext_Header}} The **`streamErrorCode`** read-only property of the {{domxref("WebTransportError")}} interface returns a number in the range 0-255 indicating the application protocol error code for this error, or `null` if one is not available. {{AvailableInWorkers}} ## Value A number, or `null`. ## Examples ```js const url = "notaurl"; async function initTransport(url) { try { // Initialize transport connection const transport = new WebTransport(url); // The connection can be used once ready fulfills await transport.ready; // ... } catch (error) { const msg = `Transport initialization failed. Reason: ${error.message}. Source: ${error.source}. Error code: ${error.streamErrorCode}.`; console.log(msg); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using WebTransport](https://developer.chrome.com/docs/capabilities/web-apis/webtransport) - {{domxref("WebSockets API", "WebSockets API", "", "nocode")}} - {{domxref("Streams API", "Streams API", "", "nocode")}} - [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlmodelement/index.md
--- title: HTMLModElement slug: Web/API/HTMLModElement page-type: web-api-interface browser-compat: api.HTMLModElement --- {{ APIRef("HTML DOM") }} The **`HTMLModElement`** interface provides special properties (beyond the regular methods and properties available through the {{domxref("HTMLElement")}} interface they also have available to them by inheritance) for manipulating modification elements, that is {{HTMLElement("del")}} and {{HTMLElement("ins")}}. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLModElement.cite")}} - : A string reflecting the [`cite`](/en-US/docs/Web/HTML/Element/del#cite) HTML attribute, containing a URI of a resource explaining the change. - {{domxref("HTMLModElement.dateTime")}} - : A string reflecting the [`datetime`](/en-US/docs/Web/HTML/Element/del#datetime) HTML attribute, containing a date-and-time string representing a timestamp for the change. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML elements implementing this interface: {{HTMLElement("ins")}}, {{HTMLElement("del")}}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gestureevent/index.md
--- title: GestureEvent slug: Web/API/GestureEvent page-type: web-api-interface status: - non-standard browser-compat: api.GestureEvent --- {{APIRef("UI Events")}}{{Non-standard_header}} The **`GestureEvent`** is a proprietary interface specific to WebKit which gives information regarding multi-touch gestures. Events using this interface include {{domxref("Element/gesturestart_event", "gesturestart")}}, {{domxref("Element/gesturechange_event", "gesturechange")}}, and {{domxref("Element/gestureend_event", "gestureend")}}. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}._ - {{domxref("GestureEvent.rotation")}} {{ReadOnlyInline}} {{Non-standard_Inline}} - : Change in rotation (in degrees) since the event's beginning. Positive values indicate clockwise rotation; negative values indicate counterclockwise rotation. Initial value: `0.0`. - {{domxref("GestureEvent.scale")}} {{ReadOnlyInline}} {{Non-standard_Inline}} - : Distance between two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the gesture. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: `1.0`. ## Instance methods _This interface also inherits methods of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}._ - {{domxref("GestureEvent.initGestureEvent()")}} {{Non-standard_Inline}} - : Initializes the value of an `GestureEvent`. If the event has already been dispatched, this method does nothing. ## Gesture event types - {{domxref("Element/gesturestart_event", "gesturestart")}} - {{domxref("Element/gesturechange_event", "gesturechange")}} - {{domxref("Element/gestureend_event", "gestureend")}} ## Specifications _Not part of any specification._ Apple has [a description at the Safari Developer Library](https://developer.apple.com/documentation/webkitjs/gestureevent). ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/usbisochronousouttransferpacket/index.md
--- title: USBIsochronousOutTransferPacket slug: Web/API/USBIsochronousOutTransferPacket page-type: web-api-interface status: - experimental browser-compat: api.USBIsochronousOutTransferPacket --- {{securecontext_header}}{{APIRef("WebUSB API")}}{{SeeCompatTable}} The `USBIsochronousOutTransferPacket` interface of the [WebUSB API](/en-US/docs/Web/API/WebUSB_API) is part of the response from a call to the `isochronousTransferOut()` method of the `USBDevice` interface. It represents the status of an individual packet from a request to transfer data from the USB host to the USB device over an isochronous endpoint. ## Constructor - {{domxref("USBIsochronousOutTransferPacket.USBIsochronousOutTransferPacket", "USBIsochronousOutTransferPacket()")}} {{Experimental_Inline}} - : Creates a new `USBIsochronousOutTransferPacket` object with the provided `status` and `bytesWritten` fields. ## Instance properties - {{domxref("USBIsochronousOutTransferPacket.bytesWritten")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the number of bytes from the packet that were sent to the device. - {{domxref("USBIsochronousOutTransferPacket.status")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the status of the transfer request, one of: - `"ok"` - The transfer was successful. - `"stall"` - The device indicated an error by generating a stall condition on the endpoint. A stall on an isochronous endpoint does not need to be cleared. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/mutationevent/index.md
--- title: MutationEvent slug: Web/API/MutationEvent page-type: web-api-interface status: - deprecated browser-compat: api.MutationEvent --- {{APIRef("UI Events")}}{{Deprecated_Header}} The **`MutationEvent`** interface provides event properties that are specific to modifications to the Document Object Model (DOM) hierarchy and nodes. > **Note:** Using _mutation events_ is problematic: > > - Their design is [flawed](https://lists.w3.org/Archives/Public/public-webapps/2011JulSep/0779.html). > - Adding DOM mutation listeners to a document [profoundly degrades the performance](https://groups.google.com/d/topic/mozilla.dev.platform/L0Lx11u5Bvs?pli=1) of further DOM modifications to that document (making them 1.5 - 7 times slower!). Moreover, removing the listeners does not reverse the damage. > - They have poor cross-browser compatibility: Safari doesn't support `DOMAttrModified` (see [WebKit bug 8191](https://webkit.org/b/8191)) and Firefox doesn't support _mutation name events_ (like `DOMElementNameChanged` and `DOMAttributeNameChanged`). > > They have been deprecated in favor of [mutation observers](/en-US/docs/Web/API/MutationObserver). **Consider using these instead.** {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent {{domxref("UIEvent")}}, and indirectly from {{domxref("Event")}}._ - {{domxref("MutationEvent.attrChange")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Indicates what kind of change triggered the `DOMAttrModified` event. It can be `MODIFICATION` (`1`), `ADDITION` (`2`) or `REMOVAL` (`3`). It has no meaning for other events and is then set to `0`. - {{domxref("MutationEvent.attrName")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Indicates the name of the node affected by the `DOMAttrModified` event. It has no meaning for other events and is then set to the empty string (`""`). - {{domxref("MutationEvent.newValue")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : In `DOMAttrModified` events, contains the new value of the modified {{domxref("Attr")}} node. In `DOMCharacterDataModified` events, contains the new value of the modified {{domxref("CharacterData")}} node. In all other cases, returns the empty string (`""`). - {{domxref("MutationEvent.prevValue")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : In `DOMAttrModified` events, contains the previous value of the modified {{domxref("Attr")}} node. In `DOMCharacterDataModified` events, contains previous new value of the modified{{domxref("CharacterData")}} node. In all other cases, returns the empty string (`""`). - {{domxref("MutationEvent.relatedNode")}} {{ReadOnlyInline}} {{Deprecated_Inline}} - : Indicates the node related to the event, like the changed node inside the subtree for `DOMSubtreeModified`. ## Instance methods - {{domxref("MutationEvent.initMutationEvent()")}} {{Deprecated_Inline}} - : Constructor method that returns a new `MutationEvent` configured with the parameters given. ## Mutation events list The following is a list of all mutation events: - `DOMAttrModified` (Not supported by Safari) - `DOMAttributeNameChanged` (Not supported by Firefox) - `DOMCharacterDataModified` - `DOMElementNameChanged` (Not supported by Firefox) - `DOMNodeInserted` - `DOMNodeInsertedIntoDocument` - `DOMNodeRemoved` - `DOMNodeRemovedFromDocument` - `DOMSubtreeModified` ## Examples You can register a listener for mutation events using {{DOMxRef("EventTarget.addEventListener()")}} as follows: ```js element.addEventListener( "DOMNodeInserted", (event) => { // … }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("MutationObserver")}}
0
data/mdn-content/files/en-us/web/api/mutationevent
data/mdn-content/files/en-us/web/api/mutationevent/newvalue/index.md
--- title: "MutationEvent: newValue property" short-title: newValue slug: Web/API/MutationEvent/newValue page-type: web-api-instance-property status: - deprecated browser-compat: api.MutationEvent.newValue --- {{APIRef("UI Events")}}{{Deprecated_Header}} The **`newValue`** read-only property of the {{domxref("MutationEvent")}} interface returns a string. In `DOMAttrModified` events, it represents the new value of the {{domxref("Attr")}} node. In `DOMCharacterDataModified` events, it contains the new value of the {{domxref("CharacterData")}} node. In all other cases, returns the empty string (`""`). ## Value A string. ## Examples ```js element.addEventListener( "DOMAttrModified", (event) => { console.log(event.newValue); }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mutationevent
data/mdn-content/files/en-us/web/api/mutationevent/attrname/index.md
--- title: "MutationEvent: attrName property" short-title: attrName slug: Web/API/MutationEvent/attrName page-type: web-api-instance-property status: - deprecated browser-compat: api.MutationEvent.attrName --- {{APIRef("UI Events")}}{{Deprecated_Header}} The **`attrName`** read-only property of the {{domxref("MutationEvent")}} interface returns a string with the name of the node affected by the `DOMAttrModified` event. It has no meaning for other events and is then set to the empty string (`""`). ## Value A string. ## Examples ```js element.addEventListener( "DOMAttrModified", (event) => { console.log(event.attrName); }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mutationevent
data/mdn-content/files/en-us/web/api/mutationevent/relatednode/index.md
--- title: "MutationEvent: relatedNode property" short-title: relatedNode slug: Web/API/MutationEvent/relatedNode page-type: web-api-instance-property status: - deprecated browser-compat: api.MutationEvent.relatedNode --- {{APIRef("UI Events")}}{{Deprecated_Header}} The **`relatedNode`** read-only property of the {{domxref("MutationEvent")}} interface returns a string indicating the node related to the event, like the changed node inside the subtree for `DOMSubtreeModified`. ## Value A string. ## Examples ```js element.addEventListener( "DOMSubtreeModified", (event) => { console.log(event.relatedNode); }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mutationevent
data/mdn-content/files/en-us/web/api/mutationevent/prevvalue/index.md
--- title: "MutationEvent: prevValue property" short-title: prevValue slug: Web/API/MutationEvent/prevValue page-type: web-api-instance-property status: - deprecated browser-compat: api.MutationEvent.prevValue --- {{APIRef("UI Events")}}{{Deprecated_Header}} The **`prevValue`** read-only property of the {{domxref("MutationEvent")}} interface returns a string. In `DOMAttrModified` events, it represents the previous value of the {{domxref("Attr")}} node. In `DOMCharacterDataModified` events, it contains the previous value of the {{domxref("CharacterData")}} node. In all other cases, returns the empty string (`""`). ## Value A string. ## Examples ```js element.addEventListener( "DOMAttrModified", (event) => { console.log(event.previousValue); }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mutationevent
data/mdn-content/files/en-us/web/api/mutationevent/initmutationevent/index.md
--- title: "MutationEvent: initMutationEvent() method" short-title: initMutationEvent() slug: Web/API/MutationEvent/initMutationEvent page-type: web-api-instance-method status: - deprecated browser-compat: api.MutationEvent.initMutationEvent --- {{APIRef("UI Events")}}{{deprecated_header}} The **`initMutationEvent()`** method of the {{domxref("MutationEvent")}} interface initializes the value of a mutation event once it's been created (normally using the {{domxref("Document.createEvent()")}} method). This method must be called to set the event before it is dispatched, using {{ domxref("EventTarget.dispatchEvent()") }}. > **Note:** In general, you won't create these events yourself; they are created by the browser. ## Syntax ```js-nolint initMutationEvent(type, canBubble, cancelable, relatedNode, prevValue, newValue, attrName, attrChange) ``` ### Parameters - `type` - : A string to set the event's {{domxref("Event.type", "type")}} to. Browsers set the following values for {{domxref("MutationEvent")}}: `DOMAttrModified`, `DOMAttributeNameChanged`, `DOMCharacterDataModified`, `DOMElementNameChanged`, `DOMNodeInserted`, `DOMNodeInsertedIntoDocument`, `DOMNodeRemoved`, `DOMNodeRemovedFromDocument`,`DOMSubtreeModified`. - `canBubble` - : A boolean indicating whether or not the event can bubble. Sets the value of {{domxref("Event.bubbles")}}. - `cancelable` - : A boolean indicating whether or not the event's default action can be prevented. Sets the value of {{domxref("Event.cancelable")}}. - `relatedNode` - : A string representing the new value of the modified node, if any. Sets the value of {{domxref("MutationEvent.relatedNode")}}. - `prevValue` - : A string representing the previous value of the modified node, if any. Sets the value of {{domxref("MutationEvent.prevValue")}}. - `newValue` - : A string representing the new value of the modified node, if any. Sets the value of {{domxref("MutationEvent.newValue")}}. - `attrName` - : A string representing the name of the {{domxref("Attr")}} node changed, if any. Sets the value of {{domxref("MutationEvent.attrName")}}. - `attrChange` - : A integer representing the reason attribute node changed. Sets the value of {{domxref("MutationEvent.attrChange")}}. ### Return value None ({{jsxref("undefined")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mutationevent
data/mdn-content/files/en-us/web/api/mutationevent/attrchange/index.md
--- title: "MutationEvent: attrChange property" short-title: attrChange slug: Web/API/MutationEvent/attrChange page-type: web-api-instance-property status: - deprecated browser-compat: api.MutationEvent.attrChange --- {{APIRef("UI Events")}}{{Deprecated_Header}} The **`attrChange`** read-only property of the {{domxref("MutationEvent")}} interface returns a number indicating what kind of change triggered the `DOMAttrModified` event. The three possible values are `MODIFICATION` (`1`), `ADDITION` (`2`) or `REMOVAL` (`3`). It has no meaning for other events and is then set to `0`. ## Value An integer: `0`, `1` (`MODIFICATION`), `2` (`ADDITION`), or `3` (`REMOVAL`). ## Examples ```js element.addEventListener( "DOMAttrModified", (event) => { console.log(event.attrChange); }, false, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/imagetracklist/index.md
--- title: ImageTrackList slug: Web/API/ImageTrackList page-type: web-api-interface status: - experimental browser-compat: api.ImageTrackList --- {{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`ImageTrackList`** interface of the {{domxref('WebCodecs API','','','true')}} represents a list of image tracks. ## Instance properties - {{domxref("ImageTrackList.ready")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{jsxref("promise")}} that resolves once the `ImageTrackList` has been populated with {{domxref("ImageTrack","tracks")}}. - {{domxref("ImageTrackList.length")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns an integer indicating the length of the `ImageTrackList`. - {{domxref("ImageTrackList.selectedIndex")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns an integer indicating the index of the `selectedTrack`. - {{domxref("ImageTrackList.selectedTrack")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the selected {{domxref("ImageTrack")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/imagetracklist
data/mdn-content/files/en-us/web/api/imagetracklist/length/index.md
--- title: "ImageTrackList: length property" short-title: length slug: Web/API/ImageTrackList/length page-type: web-api-instance-property status: - experimental browser-compat: api.ImageTrackList.length --- {{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`length`** property of the {{domxref("ImageTrackList")}} interface returns the length of the `ImageTrackList`. ## Value An integer. ## Examples The following example prints the value of `length` to the console. ```js let tracks = imageDecoder.tracks; console.log(tracks.length); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/imagetracklist
data/mdn-content/files/en-us/web/api/imagetracklist/selectedindex/index.md
--- title: "ImageTrackList: selectedIndex property" short-title: selectedIndex slug: Web/API/ImageTrackList/selectedIndex page-type: web-api-instance-property status: - experimental browser-compat: api.ImageTrackList.selectedIndex --- {{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`selectedIndex`** property of the {{domxref("ImageTrackList")}} interface returns the `index` of the selected track. ## Value An integer. ## Examples The following example prints the value of `selectedIndex` to the console. ```js let tracks = imageDecoder.tracks; console.log(tracks.selectedIndex); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/imagetracklist
data/mdn-content/files/en-us/web/api/imagetracklist/selectedtrack/index.md
--- title: "ImageTrackList: selectedTrack property" short-title: selectedTrack slug: Web/API/ImageTrackList/selectedTrack page-type: web-api-instance-property status: - experimental browser-compat: api.ImageTrackList.selectedTrack --- {{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`selectedTrack`** property of the {{domxref("ImageTrackList")}} interface returns an {{domxref("ImageTrack")}} object representing the currently selected track. ## Value An {{domxref("ImageTrack")}} object. ## Examples The following example returns the `selectedTrack` then prints it to the console. ```js let track = imageDecoder.tracks.selectedTrack; console.log(track); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/imagetracklist
data/mdn-content/files/en-us/web/api/imagetracklist/ready/index.md
--- title: "ImageTrackList: ready property" short-title: ready slug: Web/API/ImageTrackList/ready page-type: web-api-instance-property status: - experimental browser-compat: api.ImageTrackList.ready --- {{APIRef("WebCodecs API")}}{{SeeCompatTable}} The **`ready`** property of the {{domxref("ImageTrackList")}} interface returns a {{jsxref("Promise")}} that resolves when the `ImageTrackList` is populated with {{domxref("ImageTrack","tracks")}}. ## Value A {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}}. ## Examples The following example prints the value of `ready` to the console, this will be `undefined` once the promise resolves. ```js let tracks = imageDecoder.tracks; let ready = await tracks.ready; console.log(ready); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlimageelement/index.md
--- title: HTMLImageElement slug: Web/API/HTMLImageElement page-type: web-api-interface browser-compat: api.HTMLImageElement --- {{APIRef("HTML DOM")}} The **`HTMLImageElement`** interface represents an HTML {{HTMLElement("img")}} element, providing the properties and methods used to manipulate image elements. {{InheritanceDiagram}} ## Constructor - {{domxref("HTMLImageElement.Image()", "Image()")}} - : The `Image()` constructor creates and returns a new `HTMLImageElement` object representing an HTML {{HTMLElement("img")}} element which is not attached to any DOM tree. It accepts optional width and height parameters. When called without parameters, `new Image()` is equivalent to calling {{DOMxRef("Document.createElement()", "document.createElement('img')")}}. ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLImageElement.alt")}} - : A string that reflects the [`alt`](/en-US/docs/Web/HTML/Element/img#alt) HTML attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded. - {{domxref("HTMLImageElement.complete")}} {{ReadOnlyInline}} - : Returns a boolean value that is `true` if the browser has finished fetching the image, whether successful or not. That means this value is also `true` if the image has no {{domxref("HTMLImageElement.src", "src")}} value indicating an image to load. - {{domxref("HTMLImageElement.crossOrigin")}} - : A string specifying the CORS setting for this image element. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for further details. This may be `null` if CORS is not used. - {{domxref("HTMLImageElement.currentSrc")}} {{ReadOnlyInline}} - : Returns a string representing the URL from which the currently displayed image was loaded. This may change as the image is adjusted due to changing conditions, as directed by any [media queries](/en-US/docs/Web/CSS/CSS_media_queries) which are in place. - {{domxref("HTMLImageElement.decoding")}} - : An optional string representing a hint given to the browser on how it should decode the image. If this value is provided, it must be one of the possible permitted values: `sync` to decode the image synchronously, `async` to decode it asynchronously, or `auto` to indicate no preference (which is the default). Read the {{domxref("HTMLImageElement.decoding", "decoding")}} page for details on the implications of this property's values. - {{domxref("HTMLImageElement.fetchPriority")}} - : An optional string representing a hint given to the browser on how it should prioritize fetching of the image relative to other images. If this value is provided, it must be one of the possible permitted values: `high` to fetch at a high priority, `low` to fetch at a low priority, or `auto` to indicate no preference (which is the default). - {{domxref("HTMLImageElement.height")}} - : An integer value that reflects the [`height`](/en-US/docs/Web/HTML/Element/img#height) HTML attribute, indicating the rendered height of the image in CSS pixels. - {{domxref("HTMLImageElement.isMap")}} - : A boolean value that reflects the [`ismap`](/en-US/docs/Web/HTML/Element/img#ismap) HTML attribute, indicating that the image is part of a server-side image map. This is different from a client-side image map, specified using an `<img>` element and a corresponding {{HTMLElement("map")}} which contains {{HTMLElement("area")}} elements indicating the clickable areas in the image. The image _must_ be contained within an {{HTMLElement("a")}} element; see the `ismap` page for details. - {{domxref("HTMLImageElement.loading")}} - : A string providing a hint to the browser used to optimize loading the document by determining whether to load the image immediately (`eager`) or on an as-needed basis (`lazy`). - {{domxref("HTMLImageElement.naturalHeight")}} {{ReadOnlyInline}} - : Returns an integer value representing the intrinsic height of the image in CSS pixels, if it is available; else, it shows `0`. This is the height the image would be if it were rendered at its natural full size. - {{domxref("HTMLImageElement.naturalWidth")}} {{ReadOnlyInline}} - : An integer value representing the intrinsic width of the image in CSS pixels, if it is available; otherwise, it will show `0`. This is the width the image would be if it were rendered at its natural full size. - {{domxref("HTMLImageElement.referrerPolicy")}} - : A string that reflects the [`referrerpolicy`](/en-US/docs/Web/HTML/Element/img#referrerpolicy) HTML attribute, which tells the {{Glossary("user agent")}} how to decide which referrer to use in order to fetch the image. Read this article for details on the possible values of this string. - {{domxref("HTMLImageElement.sizes")}} - : A string reflecting the [`sizes`](/en-US/docs/Web/HTML/Element/img#sizes) HTML attribute. This string specifies a list of comma-separated conditional sizes for the image; that is, for a given viewport size, a particular image size is to be used. Read the documentation on the {{domxref("HTMLImageElement.sizes", "sizes")}} page for details on the format of this string. - {{domxref("HTMLImageElement.src")}} - : A string that reflects the [`src`](/en-US/docs/Web/HTML/Element/img#src) HTML attribute, which contains the full URL of the image including base URI. You can load a different image into the element by changing the URL in the `src` attribute. - {{domxref("HTMLImageElement.srcset")}} - : A string reflecting the [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) HTML attribute. This specifies a list of candidate images, separated by commas (`',', U+002C COMMA`). Each candidate image is a URL followed by a space, followed by a specially-formatted string indicating the size of the image. The size may be specified either the width or a size multiple. Read the {{domxref("HTMLImageElement.srcset", "srcset")}} page for specifics on the format of the size substring. - {{domxref("HTMLImageElement.useMap")}} - : A string reflecting the [`usemap`](/en-US/docs/Web/HTML/Element/img#usemap) HTML attribute, containing the page-local URL of the {{HTMLElement("map")}} element describing the image map to use. The page-local URL is a pound (hash) symbol (`#`) followed by the ID of the `<map>` element, such as `#my-map-element`. The `<map>` in turn contains {{HTMLElement("area")}} elements indicating the clickable areas in the image. - {{domxref("HTMLImageElement.width")}} - : An integer value that reflects the [`width`](/en-US/docs/Web/HTML/Element/img#width) HTML attribute, indicating the rendered width of the image in CSS pixels. - {{domxref("HTMLImageElement.x")}} {{ReadOnlyInline}} - : An integer indicating the horizontal offset of the left border edge of the image's CSS layout box relative to the origin of the {{HTMLElement("html")}} element's containing block. - {{domxref("HTMLImageElement.y")}} {{ReadOnlyInline}} - : The integer vertical offset of the top border edge of the image's CSS layout box relative to the origin of the {{HTMLElement("html")}} element's containing block. ## Obsolete properties - {{domxref("HTMLImageElement.align")}} {{deprecated_inline}} - : A string indicating the alignment of the image with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`. This is obsolete; you should instead use CSS (such as {{cssxref("text-align")}}, which works with images despite its name) to specify the alignment. - {{domxref("HTMLImageElement.border")}} {{deprecated_inline}} - : A string which defines the width of the border surrounding the image. This is deprecated; use the CSS {{cssxref("border")}} property instead. - {{domxref("HTMLImageElement.hspace")}} {{deprecated_inline}} - : An integer value which specifies the amount of space (in pixels) to leave empty on the left and right sides of the image. - {{domxref("HTMLImageElement.longDesc")}} {{deprecated_inline}} - : A string specifying the URL at which a long description of the image's contents may be found. This is used to turn the image into a hyperlink automatically. Modern HTML should instead place an `<img>` inside an {{HTMLElement("a")}} element defining the hyperlink. - {{domxref("HTMLImageElement.name")}} {{deprecated_inline}} - : A string representing the name of the element. - {{domxref("HTMLImageElement.vspace")}} {{deprecated_inline}} - : An integer value specifying the amount of empty space, in pixels, to leave above and below the image. ## Instance methods _Inherits methods from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLImageElement.decode()")}} - : Returns a {{jsxref("Promise")}} that resolves when the image is decoded and it's safe to append the image to the DOM. This prevents rendering of the next frame from having to pause to decode the image, as would happen if an undecoded image were added to the DOM. ## Errors If an error occurs while trying to load or render the image, and an `onerror` event handler has been configured to handle the {{domxref("HTMLElement/error_event", "error")}} event, that event handler will get called. This can happen in a number of situations, including: - The [`src`](/en-US/docs/Web/HTML/Element/img#src) attribute is empty or `null`. - The specified `src` URL is the same as the URL of the page the user is currently on. - The specified image is corrupted in some way that prevents it from being loaded. - The specified image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the `<img>` element's attributes. - The specified image is in a format not supported by the {{Glossary("user agent")}}. ## Example ```js const img1 = new Image(); // Image constructor img1.src = "image1.png"; img1.alt = "alt"; document.body.appendChild(img1); const img2 = document.createElement("img"); // Use DOM HTMLImageElement img2.src = "image2.jpg"; img2.alt = "alt text"; document.body.appendChild(img2); // using first image in the document alert(document.images[0].src); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{HTMLElement("img")}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/srcset/index.md
--- title: "HTMLImageElement: srcset property" short-title: srcset slug: Web/API/HTMLImageElement/srcset page-type: web-api-instance-property browser-compat: api.HTMLImageElement.srcset --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} property **`srcset`** is a string which identifies one or more **image candidate strings**, separated using commas (`,`) each specifying image resources to use under given circumstances. Each image candidate string contains an image URL and an optional width or pixel density descriptor that indicates the conditions under which that candidate should be used instead of the image specified by the {{domxref("HTMLImageElement.src", "src")}} property. The `srcset` property, along with the {{domxref("HTMLImageElement.sizes", "sizes")}} property, are a crucial component in designing responsive websites, as they can be used together to make pages that use appropriate images for the rendering situation. > **Note:** If the [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) attribute uses width descriptors, the `sizes` attribute must also be present, or the `srcset` itself will be ignored. ## Value A string containing a comma-separated list of one or more image candidate strings to be used when determining which image resource to present inside the {{HTMLElement("img")}} element represented by the `HTMLImageElement`. Each image candidate string must begin with a valid URL referencing a non-interactive graphic resource. This is followed by whitespace and then a condition descriptor that indicates the circumstances in which the indicated image should be used. Space characters, other than the whitespace separating the URL and the corresponding condition descriptor, are ignored; this includes both leading and trailing space, as well as space before or after each comma. The condition descriptor may take one of two forms: - To indicate that the image resource specified by the image candidate string should be used when the image is being rendered with a particular width in pixels, provide a **width descriptor** comprised the number giving that width in pixels followed by the lower case letter "w". For example, to provide an image resource to be used when the renderer needs a 450 pixel wide image, use the width descriptor string `450w`. The specified width must be a positive, non-zero, integer, and _must_ match the intrinsic width of the referenced image. When a `srcset` contains "w" descriptors, the browser uses those descriptors together with the {{domxref("HTMLImageElement.sizes", "sizes")}} attribute to pick a resource. - Alternatively, you can use a **pixel density descriptor**, which specifies the condition in which the corresponding image resource should be used as the display's pixel density. This is written by stating the pixel density as a positive, non-zero floating-point value followed by the lower-case letter "x". As an example, to state that the corresponding image should be used when the pixel density is double the standard density, you can give the pixel density descriptor `2x` or `2.0x`. If the condition descriptor is not provided (in other words, the image candidate provides only a URL), the candidate is assigned a default descriptor of "1x". ```plain "images/team-photo.jpg, images/team-photo-retina.jpg 2x" ``` This string provides versions of an image to be used at the standard pixel density (undescribed, assigned a default of `1x`) as well as double that pixel density (`2x`). When an image element's `srcset` contains "x" descriptors, browsers also consider the URL in the {{domxref("HTMLImageElement.src", "src")}} attribute (if present) as a candidate, and assign it a default descriptor of `1x`. ```plain "header640.png 640w, header960.png 960w, header1024.png 1024w" ``` This string provides versions of a header image to use when the {{Glossary("user agent", "user agent's")}} renderer needs an image of width 640px, 960px, or 1024px. Note that if any resource in a `srcset` is described with a "w" descriptor, all resources within that `srcset` must also be described with "w" descriptors, and the image element's {{domxref("HTMLImageElement.src", "src")}} is not considered a candidate. ## Examples ### HTML The HTML below indicates that the default image resource, contained within the {{domxref("HTMLImageElement.src", "src")}} attribute should be used for 1x displays, and that a 400-pixel version (contained within the `srcset`, and assigned a `2x` descriptor) should be used for 2x displays. ```html <div class="box"> <img src="/en-US/docs/Web/HTML/Element/img/clock-demo-200px.png" alt="Clock" srcset="/en-US/docs/Web/HTML/Element/img/clock-demo-400px.png 2x" /> </div> ``` ### CSS The CSS specifies that the image and its surrounding box should be 200 pixels square and should have a simple border around it. Also provided is the {{cssxref("word-break")}} attribute, using the `break-all` value to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur. ```css .box { width: 200px; border: 2px solid rgb(150 150 150); padding: 0.5em; word-break: break-all; } .box img { width: 200px; } ``` ### JavaScript The following code is run within a handler for the {{domxref("Window", "window")}}'s {{domxref("Window.load_event", "load")}} event. It uses the image's {{domxref("HTMLImageElement.currentSrc", "currentSrc")}} property to fetch and display the URL selected by the browser from the `srcset`. ```js window.addEventListener("load", () => { let box = document.querySelector(".box"); let image = box.querySelector("img"); let newElem = document.createElement("p"); newElem.innerHTML = `Image: <code>${image.currentSrc}</code>`; box.appendChild(newElem); }); ``` ### Result In the displayed output below, the selected URL will correspond with whether your display results in selecting the 1x or the 2x version of the image. If you happen to have both standard and high density displays, try moving this window between them and reloading the page to see the results change. {{EmbedLiveSample("Examples", 640, 320)}} For additional examples, see our guide to [responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Images in HTML](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML) - [Responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) - [Image file type and format guide](/en-US/docs/Web/Media/Formats/Image_types)
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/name/index.md
--- title: "HTMLImageElement: name property" short-title: name slug: Web/API/HTMLImageElement/name page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLImageElement.name --- {{APIRef("HTML DOM")}}{{deprecated_header}} The {{domxref("HTMLImageElement")}} interface's _deprecated_ **`name`** property specifies a name for the element. This has been replaced by the {{domxref("Element.id", "id")}} property available on all elements. ## Value A string providing a name by which the image can be referenced. > **Warning:** This property is deprecated and is only in the > specification still for backward compatibility purposes. Since it functions > identically to [`id`](/en-US/docs/Web/HTML/Global_attributes#id), you can and should use it instead. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/fetchpriority/index.md
--- title: "HTMLImageElement: fetchPriority property" short-title: fetchPriority slug: Web/API/HTMLImageElement/fetchPriority page-type: web-api-instance-property browser-compat: api.HTMLImageElement.fetchPriority --- {{APIRef}} The **`fetchPriority`** property of the {{domxref("HTMLImageElement")}} interface represents a hint given to the browser on how it should prioritize the fetch of the image relative to other images. ## Value A string representing the priority hint. Possible values are: - `high` - : Fetch the image at a high priority relative to other images. - `low` - : Fetch the image at a low priority relative to other images. - `auto` - : Default mode, which indicates no preference for the fetch priority. The browser decides what is best for the user. The `fetchPriority` property allows you to signal high or low priority image fetches. This can be useful when applied to {{HTMLElement("img")}} elements to signal images that are "important" to the user experience early in the loading process. The effects of the hint on resource loading is browser-specific so make sure to test on multiple browser engines. Use it sparingly for exceptional cases where the browser may not be able to infer the best way to load the image automatically. Over use can result in degrading performance. ## Examples ```js const img = new Image(); img.fetchPriority = "high"; img.src = "img/logo.png"; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/sizes/index.md
--- title: "HTMLImageElement: sizes property" short-title: sizes slug: Web/API/HTMLImageElement/sizes page-type: web-api-instance-property browser-compat: api.HTMLImageElement.sizes --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} property **`sizes`** allows you to specify the layout width of the [image](/en-US/docs/Web/HTML/Element/img) for each of a list of media conditions. This provides the ability to automatically select among different images—even images of different orientations or aspect ratios—as the document state changes to match different media conditions. Each condition is specified using the same conditional format used by [media queries](/en-US/docs/Web/CSS/CSS_media_queries). ## Value A string containing a comma-separated list of source size descriptors followed by an optional fallback size. Each **source size descriptor** is comprised of a media condition, then at least one whitespace character, then the **source size value** to use for the image when the media condition evaluates to `true`. ### Media conditions Each source size descriptor consists of a media condition as defined by the media queries standard. Because a source size descriptor is used to specify the width to use for the image during layout of the page, the media condition is typically (but not necessarily) based entirely on [width](/en-US/docs/Web/CSS/@media/width) information. See [Using media queries, Syntax](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#syntax) for details on how to construct a media condition. ### Source size values The source size value is a CSS {{cssxref("length")}}. It may be specified using font-relative units (such as `em` or `ex`), absolute units (such as `px` or `cm`), or the `vw` unit, which lets you specify the width as a percentage of the viewport width (`1vw` being 1% of the viewport width). > **Note:** The source size value must _not_ be specified as a > percentage of the container size; that is, lengths such as `50%` or > `100%` are not allowed, as there would be uncertainty as to what the > specified value is a percentage of. ## Examples ### Selecting an image to fit window width In this example, a blog-like layout is created, displaying some text and an image for which three size points are specified, depending on the width of the window. Three versions of the image are also available, with their widths specified. The browser takes all of this information and selects an image and width that best meets the specified values. How exactly the images are used may depend upon the browser and the pixel density of the user's display. Buttons at the bottom of the example let you actually modify the `sizes` property slightly, switching the largest of the three widths for the image between 40em and 50em. #### HTML ```html <article> <h1>An amazing headline</h1> <div class="test"></div> <p> This is even more amazing content text. It's really spectacular. And fascinating. Oh, it's also clever and witty. Award-winning stuff, I'm sure. </p> <img src="new-york-skyline-wide.jpg" srcset=" new-york-skyline-wide.jpg 3724w, new-york-skyline-4by3.jpg 1961w, new-york-skyline-tall.jpg 1060w " sizes="((min-width: 50em) and (max-width: 60em)) 50em, ((min-width: 30em) and (max-width: 50em)) 30em, (max-width: 30em) 20em" alt="The New York City skyline on a beautiful day, with the One World Trade Center building in the middle." /> <p> Then there's even more amazing stuff to say down here. Can you believe it? I sure can't. </p> <button id="break40">Last Width: 40em</button> <button id="break50">Last Width: 50em</button> </article> ``` #### CSS ```css article { margin: 1em; max-width: 60em; min-width: 20em; border: 4em solid #880e4f; border-radius: 7em; padding: 1.5em; font: 16px "Open Sans", Verdana, Arial, Helvetica, sans-serif; } article img { display: block; max-width: 100%; border: 1px solid #888; box-shadow: 0 0.5em 0.3em #888; margin-bottom: 1.25em; } ``` #### JavaScript The JavaScript code handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the {{domxref("Element.click_event", "click")}} event, using the JavaScript string object {{jsxref("String.replace", "replace()")}} method to replace the relevant portion of the `sizes` string. ```js const image = document.querySelector("article img"); const break40 = document.getElementById("break40"); const break50 = document.getElementById("break50"); break40.addEventListener( "click", () => (image.sizes = image.sizes.replace(/50em,/, "40em,")), ); break50.addEventListener( "click", () => (image.sizes = image.sizes.replace(/40em,/, "50em,")), ); ``` #### Result {{EmbedLiveSample("Selecting an image to fit window width", "", 1050)}} The page is best {{LiveSampleLink('Selecting an image to fit window width', 'viewed in its own window')}}, so you can adjust the sizes fully. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries) - [Using media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [Images in HTML](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML) - [Responsive images](/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images) - [Using the `srcset` and `sizes` attributes](/en-US/docs/Web/HTML/Element/img#using_the_srcset_and_sizes_attributes)
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/hspace/index.md
--- title: "HTMLImageElement: hspace property" short-title: hspace slug: Web/API/HTMLImageElement/hspace page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLImageElement.hspace --- {{APIRef("HTML DOM")}}{{deprecated_header}} The _obsolete_ **`hspace`** property of the {{domxref("HTMLImageElement")}} interface specifies the number of pixels of empty space to leave empty on the left and right sides of the {{HTMLElement("img")}} element when laying out the page. This property reflects the {{Glossary("HTML")}} [`hspace`](/en-US/docs/Web/HTML/Element/img#hspace) attribute. ## Value An integer value specifying the width, in pixels, of the horizontal margin to apply to the left and right sides of the image. ## Usage notes The value specified for `hspace` is mapped to the {{cssxref("margin-left")}} and {{cssxref("margin-right")}} properties to specify the width of those margins in pixels. > **Warning:** This property is obsolete. You should instead use the CSS > {{cssxref("margin")}} property and its longhand forms to establish margins around > an `<img>`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/naturalwidth/index.md
--- title: "HTMLImageElement: naturalWidth property" short-title: naturalWidth slug: Web/API/HTMLImageElement/naturalWidth page-type: web-api-instance-property browser-compat: api.HTMLImageElement.naturalWidth --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} interface's read-only **`naturalWidth`** property returns the intrinsic (natural), density-corrected width of the image in {{Glossary("CSS pixel", "CSS pixels")}}. This is the width the image is if drawn with nothing constraining its width; if you neither specify a width for the image nor place the image inside a container that limits or expressly specifies the image width, this is the number of CSS pixels wide the image will be. The corresponding {{domxref("HTMLImageElement.naturalHeight", "naturalHeight")}} method returns the natural height of the image. > **Note:** Most of the time the natural width is the actual width of the image sent by the server. > Nevertheless, browsers can modify an image before pushing it to the renderer. For example, Chrome > [degrades the resolution of images on low-end devices](https://crbug.com/1187043#c7). In such cases, `naturalWidth` will consider the width of the image modified > by such browser interventions as the natural width, and returns this value. ## Value An integer value indicating the intrinsic width of the image, in CSS pixels. This is the width at which the image is naturally drawn when no constraint or specific value is established for the image. This natural width is corrected for the pixel density of the device on which it's being presented, unlike the value of {{domxref("HTMLImageElement.width", "width")}}. If the intrinsic width is not available—either because the image does not specify an intrinsic width or because the image data is not available in order to obtain this information, `naturalWidth` returns 0. ## Examples See [`HTMLImageElement.naturalHeight`](/en-US/docs/Web/API/HTMLImageElement/naturalHeight#examples) for example code that displays an image in both its natural "density-adjusted" size, and in its rendered size as altered by the page's CSS and other factors. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/crossorigin/index.md
--- title: "HTMLImageElement: crossOrigin property" short-title: crossOrigin slug: Web/API/HTMLImageElement/crossOrigin page-type: web-api-instance-property browser-compat: api.HTMLImageElement.crossOrigin --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} interface's **`crossOrigin`** attribute is a string which specifies the Cross-Origin Resource Sharing ({{Glossary("CORS")}}) setting to use when retrieving the image. ## Value A string of a keyword specifying the CORS mode to use when fetching the image resource. If you don't specify `crossOrigin`, the image is fetched without CORS (the fetch `no-cors` mode). Permitted values are: - `anonymous` - : Requests by the {{HTMLElement("img")}} element have their {{domxref("Request.mode", "mode")}} set to `cors` and their {{domxref("Request.credentials", "credentials")}} mode set to `same-origin`. This means that CORS is enabled and credentials are sent _if_ the image is fetched from the same origin from which the document was loaded. - `use-credentials` - : Requests by the {{domxref("HTMLImageElement")}} will use the `cors` mode and the `include` credentials mode; all image requests by the element will use CORS, regardless of what domain the fetch is from. If `crossOrigin` is an empty string (`""`), the `anonymous` mode is selected. ## Examples In this example, a new {{HTMLElement("img")}} element is created and added to the document, loading the image with the Anonymous state; the image will be loaded using CORS and credentials will be used for all cross-origin loads. ### JavaScript The code below demonstrates setting the `crossOrigin` property on an `<img>` element to configure CORS access for the fetch of a newly-created image. ```js const imageUrl = "clock-demo-400px.png"; const container = document.querySelector(".container"); function loadImage(url) { const image = new Image(200, 200); image.addEventListener("load", () => container.prepend(image)); image.addEventListener("error", () => { const errMsg = document.createElement("output"); errMsg.value = `Error loading image at ${url}`; container.append(errMsg); }); image.crossOrigin = "anonymous"; image.alt = ""; image.src = url; } loadImage(imageUrl); ``` ### HTML ```html <div class="container"> <p> Here's a paragraph. It's a very interesting paragraph. You are captivated by this paragraph. Keep reading this paragraph. Okay, now you can stop reading this paragraph. Thanks for reading me. </p> </div> ``` ### CSS ```css body { font: 1.125rem/1.5, Helvetica, sans-serif; } .container { display: flow-root; width: 37.5em; border: 1px solid #d2d2d2; } img { float: left; padding-right: 1.5em; } output { background: rgb(100 100 100 / 100%); font-family: Courier, monospace; width: 95%; } ``` ### Result {{EmbedLiveSample("Examples", 600, 260)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLLinkElement.crossOrigin")}} - {{domxref("HTMLMediaElement.crossOrigin")}} - {{domxref("HTMLScriptElement.crossOrigin")}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/y/index.md
--- title: "HTMLImageElement: y property" short-title: "y" slug: Web/API/HTMLImageElement/y page-type: web-api-instance-property browser-compat: api.HTMLImageElement.y --- {{APIRef("HTML DOM")}} The read-only {{domxref("HTMLImageElement")}} property **`y`** indicates the y-coordinate of the {{HTMLElement("img")}} element's top border edge relative to the root element's origin. The {{domxref("HTMLImageElement.x", "x")}} and `y` properties are only valid for an image if its {{cssxref("display")}} property has the computed value `table-column` or `table-column-group`. In other words: it has either of those values set explicitly on it, or it has inherited it from a containing element, or by being located within a column described by either {{HTMLElement("col")}} or {{HTMLElement("colgroup")}}. ## Value An integer value indicating the distance in pixels from the top edge of the element's nearest root element to the top edge of the {{HTMLElement("img")}} element's border box. The nearest root element is the outermost {{HTMLElement("html")}} element that contains the image. If the image is in an {{HTMLElement("iframe")}}, its `y` is relative to that frame. In the diagram below, the top border edge is the top edge of the blue padding area. So the value returned by `y` would be the distance from that point to the top edge of the content area. ![Diagram showing the relationships between the various boxes associated with an element](boxmodel-3.png) > **Note:** The `y` property is only valid if the computed > value of the image's {{cssxref("display")}} property is either > `table-column` or `table-column-group`; in other words, > either of those are set directly on the {{HTMLElement("img")}} or they're > inherited from a containing element or by being located within a column described > by either {{HTMLElement("col")}} or {{HTMLElement("colgroup")}}. ## Example See [`HTMLImageElement.x`](/en-US/docs/Web/API/HTMLImageElement/x#example) for example code that demonstrates the use of the `HTMLImageElement.y` (and `HTMLImageElement.x`). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/usemap/index.md
--- title: "HTMLImageElement: useMap property" short-title: useMap slug: Web/API/HTMLImageElement/useMap page-type: web-api-instance-property browser-compat: api.HTMLImageElement.useMap --- {{APIRef("HTML DOM")}} The **`useMap`** property on the {{domxref("HTMLImageElement")}} interface reflects the value of the {{Glossary("HTML")}} [`usemap`](/en-US/docs/Web/HTML/Element/img#usemap) attribute, which is a string providing the name of the client-side image map to apply to the image. ## Value A string providing the page-local URL (that is, a URL that begins with the hash or pound symbol, "`#`") of the {{HTMLElement("map")}} element which defines the image map to apply to the image. You can learn more about client-side image maps in our learning article [Add a hitmap on top of an image](/en-US/docs/Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image). ## Usage notes The string value of `useMap` must be a valid anchor for a {{HTMLElement("map")}} element. In other words, this string should be the value of the appropriate `<map>`'s [`name`](/en-US/docs/Web/HTML/Element/map#name) attribute with a pound or hash symbol prepended to it. Consider a `<map>` that looks like this: ```html <map name="mainmenu-map"> <area shape="circle" coords="25, 25, 75" href="/index.html" alt="Return to home page" /> <area shape="rect" coords="25, 25, 100, 150" href="/index.html" alt="Shop" /> </map> ``` Given the image map named `mainmenu-map`, the image which uses it should look something like the following: ```html <img src="menubox.png" usemap="#mainmenu-map" /> ``` For additional examples (including interactive ones), see the articles about the {{HTMLElement("map")}} and {{HTMLElement("area")}} elements, as well as the [guide to using image maps](/en-US/docs/Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image). ## Examples {{EmbedInteractiveExample("pages/tabbed/area.html", "tabbed-taller")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/border/index.md
--- title: "HTMLImageElement: border property" short-title: border slug: Web/API/HTMLImageElement/border page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLImageElement.border --- {{APIRef("HTML DOM")}}{{deprecated_header}} The obsolete {{domxref("HTMLImageElement")}} property **`border`** specifies the number of pixels thick the border surrounding the image should be. A value of 0, the default, indicates that no border should be drawn. You should _not_ use this property! Instead, you should use CSS to style the border. The {{cssxref("border")}} property or its longhand properties to not only set the thickness of the border but to potentially apply a wide variety of other styling options to it. The width, specifically, is controlled using the writing-mode aware {{cssxref("border-block-start-width")}}, {{cssxref("border-block-end-width")}}, {{cssxref("border-inline-start-width")}}, and {{cssxref("border-inline-end-width")}} properties. For compatibility (or perhaps other) reasons, you can use the older properties instead (or in addition): {{cssxref("border-top-width")}}, {{cssxref("border-right-width")}}, {{cssxref("border-bottom-width")}}, and {{cssxref("border-left-width")}}. ## Value A string containing an integer value specifying the thickness of the border that should surround the image, in CSS pixels. A value of `0`, or an empty string, indicates that there should be no border drawn. The default value of `border` is `0` ## Usage notes Do not use `border`. It is obsolete. Instead, use the CSS {{cssxref("border")}} property and its longhand properties to establish borders around images. For example, if you have the following HTML: ```html <img src="image.png" border="2" /> ``` The following will provide the same appearance using CSS instead of this obsolete property: ```html <img src="image.png" style="border: 2px;" /> ``` You can further provide additional information to change the color and other features of the border: ```html <img src="image.png" style="border: dashed 2px #333388;" /> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/decoding/index.md
--- title: "HTMLImageElement: decoding property" short-title: decoding slug: Web/API/HTMLImageElement/decoding page-type: web-api-instance-property browser-compat: api.HTMLImageElement.decoding --- {{APIRef}} The **`decoding`** property of the {{domxref("HTMLImageElement")}} interface provides a hint to the browser as to how it should decode the image. More specifically, whether it should wait for the image to be decoded before presenting other content updates or not. ## Value A string representing the decoding hint. Possible values are: - `"sync"` - : Decode the image synchronously for atomic presentation with other content. - `"async"` - : Decode the image asynchronously and allow other content to be rendered before this completes. - `"auto"` - : No preference for the decoding mode; the browser decides what is best for the user. This is the default value, but different browsers have different defaults: - Chromium defaults to `"sync"`. - Firefox defaults to `"async"`. - Safari defaults to `"sync"` except in a small number of circumstances. ## Usage notes The `decoding` property provides a hint to the browser as to whether it should perform image decoding along with other tasks in a single step (`"sync"`), or allow other content to be rendered before this completes (`"async"`). In reality, the differences between the two values are often difficult to perceive and, where there are differences, there is often a better way. For images that are inserted into the DOM inside the viewport, `"async"` can result in flashes of unstyled content, while `"sync"` can result in small amounts of [jank](/en-US/docs/Glossary/Jank). Using the {{domxref("HTMLImageElement.decode()")}} method is usually a better way to achieve atomic presentation without holding up other content. For images inserted into the DOM outside of the viewport, modern browsers will usually decode them before they are scrolled into view and there will be no noticeable difference using either value. ## Examples In the below example, you'll likely get an empty image shown on the page as the image is downloaded. Setting `decoding` won't prevent that. ```js const img = new Image(); img.decoding = "sync"; img.src = "img/logo.png"; document.body.appendChild(img); ``` Inserting an image after download can make the `decoding` property more relevant: ```js async function loadImage(url, elem) { return new Promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } const img = new Image(); await loadImage("img/logo.png", img); // Using `sync` can ensure other content is only updated with the image img.decoding = "sync"; document.body.appendChild(img); const p = document.createElement("p"); p.textContent = "Image is fully loaded!"; document.body.appendChild(p); ``` A better solution, however, is to use the {{domxref("HTMLImageElement.decode()")}} method to solve this problem. It provides a way to asynchronously decode an image, delaying inserting it into the DOM until it is fully downloaded and decoded, thereby avoiding the empty image problem mentioned above. This is particularly useful if you're dynamically swapping an existing image for a new one, and also prevents unrelated paints outside of this code from being held up while the image is decoding. Using `img.decoding = "async"` may avoid holding up other content from displaying if the decoding time is long: ```js const img = new Image(); img.decoding = "async"; img.src = "img/logo.png"; document.body.appendChild(img); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("HTMLImageElement.decode()")}} method - The {{htmlelement("img")}} element `decoding` attribute - [What does the image decoding attribute actually do?](https://www.tunetheweb.com/blog/what-does-the-image-decoding-attribute-actually-do/) on tunetheweb.com (2023)
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/x/index.md
--- title: "HTMLImageElement: x property" short-title: x slug: Web/API/HTMLImageElement/x page-type: web-api-instance-property browser-compat: api.HTMLImageElement.x --- {{APIRef("HTML DOM")}} The read-only {{domxref("HTMLImageElement")}} property **`x`** indicates the x-coordinate of the {{HTMLElement("img")}} element's left border edge relative to the root element's origin. The `x` and {{domxref("HTMLImageElement.y", "y")}} properties are only valid for an image if its {{cssxref("display")}} property has the computed value `table-column` or `table-column-group`. In other words: it has either of those values set explicitly on it, or it has inherited it from a containing element, or by being located within a column described by either {{HTMLElement("col")}} or {{HTMLElement("colgroup")}}. ## Value An integer value indicating the distance in pixels from the left edge of the element's nearest root element and the left edge of the {{HTMLElement("img")}} element's border box. The nearest root element is the outermost {{HTMLElement("html")}} element that contains the image. If the image is in an {{HTMLElement("iframe")}}, its `x` is relative to that frame. In the diagram below, the left border edge is the left edge of the blue padding area. So the value returned by `x` would be the distance from that point to the left edge of the content area. ![Diagram showing the relationships between the various boxes associated with an element](boxmodel-3.png) > **Note:** The `x` property is only valid if the computed > value of the image's {{cssxref("display")}} property is either > `table-column` or `table-column-group`; in other words, either > of those are set directly on the {{HTMLElement("img")}} or they're inherited from a > containing element or by being located within a column described by either > {{HTMLElement("col")}} or {{HTMLElement("colgroup")}}. ## Example The example below demonstrates the use of the `HTMLImageElement` properties {{domxref("HTMLImageElement.x", "x")}} and {{domxref("HTMLImageElement.y", "y")}}. ### HTML In this example, we see a table showing information about users of a website, including their user ID, their full name, and their avatar image. ```html <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>UserID</th> <th>Name</th> <th>Avatar</th> </tr> <tr> <td>12345678</td> <td>Johnny Rocket</td> <td><img src="https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg"></td> </th> </table> <pre id="log"> </pre> ``` ### JavaScript The JavaScript code that fetches the image from the table and looks up its `x` and `y` values is below. ```js let logBox = document.querySelector("pre"); let tbl = document.getElementById("userinfo"); let log = (msg) => { logBox.innerHTML += `${msg}<br>`; }; let cell = tbl.rows[1].cells[2]; let image = cell.querySelector("img"); log(`Image's global X: ${image.x}`); log(`Image's global Y: ${image.y}`); ``` This uses the {{HTMLElement("table")}}'s {{domxref("HTMLTableElement.rows", "rows")}} property to get a list of the rows in the table, from which it looks up row 1 (which, being a zero-based index, means the second row from the top). Then it looks at that {{HTMLElement("tr")}} (table row) element's {{domxref("HTMLTableRowElement.cells", "cells")}} property to get a list of the cells in that row. The third cell is taken from that row (once again, specifying 2 as the zero-based offset). From there, we can get the `<img>` element itself from the cell by calling {{domxref("Element.querySelector", "querySelector()")}} on the {{domxref("HTMLTableCellElement")}} representing that cell. Finally, we can look up and display the values of the `HTMLImageElement`'s `x` and `y` properties. ### CSS The CSS defining the appearance of the table: ```css .group1 { background-color: #d7d9f2; } table { border-collapse: collapse; border: 2px solid rgb(100 100 100); font-family: sans-serif; } td, th { border: 1px solid rgb(100 100 100); padding: 10px 14px; } td > img { max-width: 4em; } ``` ### Result The resulting table looks like this: {{EmbedLiveSample("Example", 600, 200)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/alt/index.md
--- title: "HTMLImageElement: alt property" short-title: alt slug: Web/API/HTMLImageElement/alt page-type: web-api-instance-property browser-compat: api.HTMLImageElement.alt --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} property **`alt`** provides fallback (alternate) text to display when the image specified by the {{HTMLElement("img")}} element is not loaded. This may be the case because of an error, because the user has disabled the loading of images, or because the image hasn't finished loading yet. Perhaps the most important reason to use the `alt` property is to support [accessibility](/en-US/docs/Web/Accessibility), as the `alt` text may be used by screen readers and other assistive technologies to help people with a disability make full use of your content. It will be read aloud or sent to a braille output device, for example, to support blind or visually impaired users. > **Think of it like this:** When choosing `alt` strings for your images, imagine what you would say when reading the page to someone over the phone without mentioning that there's an image on the page. The alternate text is displayed in the space the image would occupy and should be able to take the place of the image _without altering the meaning of the page_. ## Value A string which contains the alternate text to display when the image is not loaded or for use by assistive devices. The `alt` attribute is officially mandatory; it's meant to always be specified. If the image doesn't require a fallback (such as for an image which is decorative or an advisory icon of minimal importance), you may specify an empty string (`""`). For compatibility reasons, browsers generally will accept an image without an `alt` attribute, but you should try to get into the habit of using it. ## Usage notes The fundamental guideline for the `alt` attribute is that every image's alternate text should be able to replace the image _without altering the meaning of the page_. You should never use `alt` for text that could be construed as a caption or title. There are separate attributes and elements designed for those purposes. ## Examples Beyond that, there are additional guidelines for using `alt` appropriately which vary depending on what the image is being used for. These are shown in the examples below. ### Decorative images Images with no semantic meaning—such as those which are solely decorative—or of limited informational value, should have their `alt` attributes set to the empty string (`""`). This is shown in the example below. #### HTML In the HTML for this example, shown below, the {{HTMLElement("img")}} element includes the `alt` property, which will prevent the image from having any alternate text, since it's a decorative detail. ```html <div class="container"> <div class="left-margin"> <img src="/files/16861/margin-flourish.svg" alt="" /> </div> <div class="contents"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque quis orci ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ac neque libero. Vivamus consectetur rhoncus elit eget porta. Etiam pulvinar ex id sapien laoreet, quis aliquet odio lobortis. Nam ac mauris at risus laoreet cursus vitae et sapien. Etiam molestie auctor eros, ac porta risus scelerisque sit amet. Ut nunc neque, porta eu auctor at, tempor et arcu. </p> </div> </div> ``` #### CSS The CSS for this example sets up the styles for the layout as shown in the result below. ```css body { margin: 0; padding: 0; } p { margin-block-start: 0; margin-block-end: 1em; margin-top: 0; margin-bottom: 1em; } .container { width: 100vh; height: 95vh; font: 16px Arial, Helvetica, sans-serif; } .left-margin { background-color: rgb(241 240 237); width: 9em; height: 100%; float: left; margin-right: 5px; padding-right: 1em; display: flex; align-items: center; justify-content: center; } .left-margin img { width: 6em; } .contents { background-color: rgb(241 240 235); height: 100%; margin-left: 2em; padding-top: 1em; padding-left: 2em; padding-right: 1em; } ``` #### Result {{EmbedLiveSample("Decorative_images", 600, 500)}} ### Images used as buttons When using an image as a button (by using it as the only visible child of an {{HTMLElement("a")}} element representing a hyperlink), the `alt` attribute must be used to convey the purpose of the button. In other words, it should be the same text you would use in a textual button to serve the same purpose. For example, in the snippet of HTML below, a toolbar which uses icon images as link labels provides `alt` attributes for each giving a textual label to use instead of the icon when the icons cannot be or are intentionally not used. ```html <li class="toolbar" aria-role="toolbar"> <a href="songs.html" aria-role="button"> <img src="songicon.svg" alt="Songs" /> </a> <a href="albums.html" aria-role="button"> <img src="albumicon.svg" alt="Albums" /></a> <a href="artists.html" aria-role="button"> <img src="artisticon.svg" alt="Artists" /> </a> <a href="playlists.html" aria-role="button"> <img src="playlisticon.svg" alt="Playlists" /> </a> </li> ``` ### Images containing diagrams or maps When an image contains information presented as a diagram, chart, graph, or map, the `alt` text should provide the same information, at least in summary form. This is true whether the /me image is in a bitmapped format such as [PNG](/en-US/docs/Web/Media/Formats/Image_types#png_portable_network_graphics) or [JPEG](/en-US/docs/Web/Media/Formats/Image_types#jpeg_joint_photographic_experts_group_image) or in a vector format like [SVG](/en-US/docs/Web/Media/Formats/Image_types#svg_scalable_vector_graphics). - For a map, the `alt` text could be directions to the place indicated by the map, similarly to how you would explain it verbally. - For a chart, the text could describe the items in the chart and their values. - For a diagram, the text could be an explanation of the concept presented by the diagram. Keep in mind that any text included in diagrams and charts presented in {{Glossary("SVG")}} format may be read by screen readers. This may impact the decisions you make when writing the `alt` text for the diagram. ### Icons or logos Logos (such as corporate or brand logos) and informational icons should use the corresponding text in their `alt` strings. That is, if an image is a corporate logo, the `alt` text should be the name of the company. If the image is an icon representing a status or other information, the text should be the name of that state. For example, if an image is a badge that's shown on a page to indicate that the content of the page is new and has been updated recently, the corresponding `alt` text might be "`Updated Recently"` or even "`Updated on 27 August 2019"`. In this example, a starburst image with the word "New!" is used to indicate that an article is about something new (and probably supposedly also exciting). The `alt` attribute is set to `New Page!` to allow that text to be displayed in place of the image if the image isn't available. It is also available to be read by screen readers. #### HTML The HTML below creates a snippet of content from a site using the described icon. Note the use of the `alt` attribute on the {{HTMLElement("img")}}, providing a good substitution string to use in case the image doesn't load. ```html <div class="container"> <img src="https://www.bitstampede.com/mdn-test/new-page.svg" alt="New Page!" class="pageinfo-badge" /> <p class="contents"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque quis orci ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ac neque libero. Vivamus consectetur rhoncus elit eget porta. Etiam pulvinar ex id sapien laoreet, quis aliquet odio lobortis. Nam ac mauris at risus laoreet cursus vitae et sapien. Etiam molestie auctor eros, ac porta risus scelerisque sit amet. Ut nunc neque, porta eu auctor at, tempor et arcu. </p> </div> ``` #### CSS The main feature of the CSS here is the use of {{cssxref("clip-path")}} and {{cssxref("shape-outside")}} to wrap the text around the icon in an appealing way. ```css .container { max-width: 500px; } .pageinfo-badge { width: 9em; padding-right: 1em; float: left; clip-path: polygon( 100% 0, 100% 50%, 90% 70%, 80% 80%, 70% 90%, 50% 100%, 0 100%, 0 0 ); shape-outside: polygon( 100% 0, 100% 50%, 90% 70%, 80% 80%, 70% 90%, 50% 100%, 0 100%, 0 0 ); } .contents { margin-top: 1em; font: 16px Arial, Helvetica, Verdana, sans-serif; } ``` #### Result {{EmbedLiveSample("Icons_or_logos", 640,400)}} ### Other images Images showing objects or scenes should have `alt` text describing what's seen in the image. A photo of a yellow teapot might literally have its `alt` attribute set to "`A yellow teapot"`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/naturalheight/index.md
--- title: "HTMLImageElement: naturalHeight property" short-title: naturalHeight slug: Web/API/HTMLImageElement/naturalHeight page-type: web-api-instance-property browser-compat: api.HTMLImageElement.naturalHeight --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} interface's **`naturalHeight`** property is a read-only value which returns the intrinsic (natural), density-corrected height of the image in {{Glossary("CSS pixel", "CSS pixels")}}. This is the height the image is if drawn with nothing constraining its height; if you don't specify a height for the image, or place the image inside a container that either limits or expressly specifies the image height, it will be rendered this tall. > **Note:** Most of the time the natural height is the actual height of the image sent by the server. > Nevertheless, browsers can modify an image before pushing it to the renderer. For example, Chrome > [degrades the resolution of images on low-end devices](https://crbug.com/1187043#c7). In such cases, `naturalHeight` will consider the height of the image modified > by such browser interventions as the natural height, and returns this value. ## Value An integer value indicating the intrinsic height, in CSS pixels, of the image. This is the height at which the image is naturally drawn when no constraint or specific value is established for the image. This natural height is corrected for the pixel density of the device on which it's being presented, unlike {{domxref("HTMLImageElement.height", "height")}}. If the intrinsic height is not available—either because the image does not specify an intrinsic height or because the image data is not available in order to obtain this information, `naturalHeight` returns 0. ## Examples This example displays both the natural, density-adjusted size of an image as well as its rendered size as altered by the page's CSS and other factors. ### HTML ```html <div class="box"> <img src="/en-US/docs/Web/HTML/Element/img/clock-demo-400px.png" class="image" alt="A round wall clock with a white dial and black numbers" /> </div> <pre></pre> ``` The HTML features a 400x398 pixel image which is placed inside a {{HTMLElement("div")}}. ### CSS ```css .box { width: 200px; height: 200px; } .image { width: 100%; } ``` The main thing of note in the CSS above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). ### JavaScript ```js const output = document.querySelector("pre"); const image = document.querySelector("img"); image.addEventListener("load", (event) => { const { naturalWidth, naturalHeight, width, height } = image; output.textContent = ` Natural size: ${naturalWidth} x ${naturalHeight} pixels Displayed size: ${width} x ${height} pixels `; }); ``` The JavaScript code dumps the natural and as-displayed sizes into the {{HTMLElement("pre")}}. This is done in response to the images's {{domxref("HTMLElement.load_event", "load")}} event handler, in order to ensure that the image is available before attempting to examine its width and height. ### Result {{EmbedLiveSample("Examples", 600, 280)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/loading/index.md
--- title: "HTMLImageElement: loading property" short-title: loading slug: Web/API/HTMLImageElement/loading page-type: web-api-instance-property browser-compat: api.HTMLImageElement.loading --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} property **`loading`** is a string whose value provides a hint to the {{Glossary("user agent")}} on how to handle the loading of the image which is currently outside the window's {{Glossary("visual viewport")}}. This helps to optimize the loading of the document's contents by postponing loading the image until it's expected to be needed, rather than immediately during the initial page load. ## Value A string providing a hint to the user agent as to how to best schedule the loading of the image to optimize page performance. The possible values are: - `eager` - : The default behavior, `eager` tells the browser to load the image as soon as the `<img>` element is processed. - `lazy` - : Tells the user agent to hold off on loading the image until the browser estimates that it will be needed imminently. For instance, if the user is scrolling through the document, a value of `lazy` will cause the image to only be loaded shortly before it will appear in the window's {{Glossary("visual viewport")}}. ## Usage notes > **Note:** In Firefox, the `loading` attribute must be defined before the `src` attribute, otherwise it has no effect ([Firefox bug 1647077](https://bugzil.la/1647077)). ### JavaScript must be enabled Loading is only deferred when JavaScript is enabled. This is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing images in a page's markup such that a server can track how many images are requested and when. ### Timing of the load event The {{domxref("Window.load_event", "load")}} event is fired when the document has been fully processed. When images are loaded eagerly (which is the default), every image in the document must be fetched before the `load` event can fire. By specifying the value `lazy` for `loading`, you prevent the image from delaying the `load` attribute by the amount of time it takes to request, fetch, and process the image. Images whose `loading` attribute is set to `lazy` but are located within the visual viewport immediately upon initial page load are loaded as soon as the layout is known, but their loads do not delay the firing of the `load` event. In other words, these images aren't loaded immediately when processing the `<img>` element, but are still loaded as part of the initial page load. They just don't affect the timing of the `load` event. That means that when `load` fires, it's possible that any lazy-loaded images located in the visual viewport may not yet be visible. ### Preventing element shift during image lazy loads When an image whose loading has been delayed by the `loading` attribute being set to `lazy` is finally loaded, the browser will determine the final size of the {{HTMLElement("img")}} element based on the style and intrinsic size of the image, then reflow the document as needed to update the positions of elements based on any size change made to the element to fit the image. To prevent this reflow from occurring, you should explicitly specify the size of the image's presentation using the image element's [`width`](/en-US/docs/Web/HTML/Element/img#width) and [`height`](/en-US/docs/Web/HTML/Element/img#height) attributes. By establishing the intrinsic aspect ratio in this manner, you prevent elements from shifting around while the document loads, which can be disconcerting or off-putting at best and can cause users to click the wrong thing at worst, depending on the exact timing of the deferred loads and reflows. ## Examples The `addImageToList()` function shown below adds a photo thumbnail to a list of items, using lazy-loading to avoid loading the image from the network until it's actually needed. ```js function addImageToList(url) { const list = document.querySelector("div.photo-list"); let newItem = document.createElement("div"); newItem.className = "photo-item"; let newImg = document.createElement("img"); newImg.loading = "lazy"; newImg.width = 320; newImg.height = 240; newImg.src = url; newItem.appendChild(newImg); list.appendChild(newItem); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("img")}} element - [Web performance](/en-US/docs/Learn/Performance) in the MDN Learning Area - [Lazy loading](/en-US/docs/Web/Performance/Lazy_loading) in the MDN web performance guide
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/vspace/index.md
--- title: "HTMLImageElement: vspace property" short-title: vspace slug: Web/API/HTMLImageElement/vspace page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLImageElement.vspace --- {{APIRef("HTML DOM")}}{{deprecated_header}} The _obsolete_ **`vspace`** property of the {{domxref("HTMLImageElement")}} interface specifies the number of pixels of empty space to leave empty on the top and bottom of the {{HTMLElement("img")}} element when laying out the page. ## Value An integer value specifying the height, in pixels, of the vertical margin to apply to the top and bottom sides of the image. ## Usage notes The value specified for `vspace` is mapped to the {{cssxref("margin-top")}} and {{cssxref("margin-bottom")}} properties to specify the height of those margins in pixels. > **Warning:** This property is obsolete. You should instead use the CSS > {{cssxref("margin")}} property and its longhand forms to establish margins around > an `<img>`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/ismap/index.md
--- title: "HTMLImageElement: isMap property" short-title: isMap slug: Web/API/HTMLImageElement/isMap page-type: web-api-instance-property browser-compat: api.HTMLImageElement.isMap --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} property **`isMap`** is a Boolean value which indicates that the image is to be used by a server-side image map. This may only be used on images located within an {{HTMLElement("a")}} element. > **Note:** For accessibility reasons, you should generally avoid using > server-side image maps, as they require the use of a mouse. Use a [client-side image map](/en-US/docs/Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image) instead. ## Value A Boolean value which is `true` if the image is being used for a server-side image map; otherwise, the value is `false`. ## Usage notes When an image marked as being part of a server-side image map is clicked, the browser constructs the string "?x,y", where x and y indicate the coordinates at which the mouse was clicked as offsets from the top-left corner of the image, specified in CSS pixels. The browser then fetches that URL from the server and displays or downloads it depending on the value of the [`download`](/en-US/docs/Web/HTML/Element/a#download) attribute. Unlike server-side image maps, client-side image maps don't cause the {{HTMLElement("img")}} element to adopt interactive content mode. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/image/index.md
--- title: "HTMLImageElement: Image() constructor" short-title: Image() slug: Web/API/HTMLImageElement/Image page-type: web-api-constructor browser-compat: api.HTMLImageElement.Image --- {{APIRef("HTML DOM")}} The **`Image()`** constructor creates a new {{DOMxRef("HTMLImageElement")}} instance. It is functionally equivalent to {{DOMxRef("Document.createElement()", "document.createElement('img')")}}. > **Note:** This function should not be confused with the CSS [`image()`](/en-US/docs/Web/CSS/image/image) function. ## Syntax ```js-nolint new Image() new Image(width) new Image(width, height) ``` ### Parameters - `width` {{optional_inline}} - : The width of the image (i.e., the value for the [`width`](/en-US/docs/Web/HTML/Element/img#width) attribute). - `height` {{optional_inline}} - : The height of the image (i.e., the value for the [`height`](/en-US/docs/Web/HTML/Element/img#height) attribute). ## Usage note The entire bitmap is loaded regardless of the sizes specified in the constructor. The size specified in the constructor is reflected through the properties {{DOMxRef("HTMLImageElement.width")}} and {{DOMxRef("HTMLImageElement.height")}} of the resulting instance. The intrinsic width and height of the image in CSS pixels are reflected through the properties {{DOMxRef("HTMLImageElement.naturalWidth")}} and {{DOMxRef("HTMLImageElement.naturalHeight")}}. If no size is specified in the constructor both pairs of properties have the same values. ## Examples ```js const myImage = new Image(100, 200); myImage.src = "picture.jpg"; document.body.appendChild(myImage); ``` This would be the equivalent of defining the following HTML tag inside the {{HTMLElement("body")}}: ```html <img width="100" height="200" src="picture.jpg" /> ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/decode/index.md
--- title: "HTMLImageElement: decode() method" short-title: decode() slug: Web/API/HTMLImageElement/decode page-type: web-api-instance-method browser-compat: api.HTMLImageElement.decode --- {{APIRef("HTML DOM")}} The **`decode()`** method of the {{domxref("HTMLImageElement")}} interface returns a {{jsxref("Promise")}} that resolves once the image is decoded and it is safe to append it to the DOM. This can be used to initiate loading of the image prior to attaching it to an element in the DOM (or adding it to the DOM as a new element), so that the image can be rendered immediately upon being added to the DOM. This, in turn, prevents the rendering of the next frame after adding the image to the DOM from causing a delay while the image loads. ## Syntax ```js-nolint decode() ``` ### Parameters None. ### Return value A {{jsxref('Promise')}} that fulfills with `undefined` once the image data is ready to be used. ### Exceptions - `EncodingError` - : A {{domxref('DOMException')}} indicating that an error occurred while decoding the image. ## Usage notes One potential use case for `decode()`: when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new {{domxref("HTMLImageElement")}}, setting its source to the full-resolution image's URL, then using `decode()` to get a promise which is resolved once the full-resolution image is ready for use. At that time, you can then replace the low-resolution image with the full-resolution one that's now available. ## Examples ### Basic usage The following example shows how to use the `decode()` method to control when an image is appended to the DOM. ```js const img = new Image(); img.src = "nebula.jpg"; img .decode() .then(() => { document.body.appendChild(img); }) .catch((encodingError) => { // Do something with the error. }); ``` > **Note:** Without a {{jsxref('Promise')}}-returning method, you > would add the image to the DOM in a {{domxref("Window/load_event", "load")}} event handler, > and handle the error in the {{domxref("HTMLElement/error_event", "error")}} event's handler. ### Avoiding empty images In the below example, you'll likely get an empty image shown on the page as the image is downloaded: ```js const img = new Image(); img.src = "img/logo.png"; document.body.appendChild(img); ``` Using `decode()` will delay inserting the image into the DOM until it is fully downloaded and decoded, thereby avoiding the empty image problem: ```js async function getImage() { const img = new Image(); img.src = "img/logo.png"; await img.decode(); document.body.appendChild(img); const p = document.createElement("p"); p.textContent = "Image is fully loaded!"; document.body.appendChild(p); } ``` This is particularly useful if you're dynamically swapping an existing image for a new one, and also prevents unrelated paints outside of this code from being held up while the image is decoding. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [What does the image decoding attribute actually do?](https://www.tunetheweb.com/blog/what-does-the-image-decoding-attribute-actually-do/) on tunetheweb.com (2023) - The {{domxref("HTMLImageElement.decoding")}} property
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/src/index.md
--- title: "HTMLImageElement: src property" short-title: src slug: Web/API/HTMLImageElement/src page-type: web-api-instance-property browser-compat: api.HTMLImageElement.src --- {{APIRef("HTML DOM")}} The {{domxref("HTMLImageElement")}} property **`src`**, which reflects the HTML [`src`](/en-US/docs/Web/HTML/Element/img#src) attribute, specifies the image to display in the {{HTMLElement("img")}} element. ## Value When providing only a single image, rather than a set of images from which the browser selects the best match for the viewport size and display pixel density, the `src` attribute is a string specifying the URL of the desired image. This can be set either within the HTML itself using the [`src`](/en-US/docs/Web/HTML/Element/img#src) content attribute, or programmatically by setting the element's `src` property. If you use the [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) content attribute to provide multiple image options for different display pixel densities, the URL specified by the `src` attribute is used in one of two ways: - as a fallback for browsers that don't support `srcset`. - as an equivalent for specifying an image in `srcset` with the size multiplier `1x`; that is, the image specified by `src` is used on low-density screens (such as typical 72 DPI or 96 DPI displays). Additionally, if you use `src` along with _both_ {{domxref("HTMLImageElement.sizes", "sizes")}} (or the corresponding [`sizes`](/en-US/docs/Web/HTML/Element/img#sizes) content attribute) _and_ `srcset` in order to choose an image based on the viewport size, the `src` attribute is only used as a fallback for browsers that don't support `sizes` and `srcset`; otherwise, it's not used at all. ## Examples ### Specifying a single image #### HTML ```html <img src="grapefruit-slice-332-332.jpg" width="160" alt="Slices of grapefruit, looking yummy." /> ``` #### Result {{EmbedLiveSample("Specifying_a_single_image", 640,200)}} ### Using src with an image set When using a set of images with the {{domxref("HTMLImageElement.srcset", "srcset")}} property, the `src` serves as either a fallback for older browsers, or as the `1x` size of the image. #### HTML #### Result ### Specifying a fallback for viewport-based selection When using viewport-bases selection of an image from a `srcset` by also specifying the {{domxref("HTMLImageElement.sizes", "sizes")}} property, the `src` property serves as the fallback to be used on browsers that don't support viewport-based selection. Browsers that _do_ support viewport-based selection will ignore `src` in this situation. #### HTML #### Result ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/width/index.md
--- title: "HTMLImageElement: width property" short-title: width slug: Web/API/HTMLImageElement/width page-type: web-api-instance-property browser-compat: api.HTMLImageElement.width --- {{APIRef("HTML DOM")}} The **`width`** property of the {{domxref("HTMLImageElement")}} interface indicates the width at which an image is drawn in {{Glossary("CSS pixel", "CSS pixels")}} if it's being drawn or rendered to any visual medium such as a screen or printer. Otherwise, it's the natural, pixel density-corrected width of the image. ## Value An integer value indicating the width of the image. The way the width is defined depends on whether or not the image is being rendered to a visual medium, such as a screen or printer: - If the image is being rendered to a visual medium, the width is expressed in {{Glossary("CSS pixel", "CSS pixels")}}. - If the image is not being rendered to a visual medium, its width is represented using the image's natural (intrinsic) width, adjusted for the display density as indicated by {{domxref("HTMLImageElement.naturalWidth", "naturalWidth")}}. ## Examples In this example, two different sizes are provided for an image of a clock using the [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) attribute. One is 200px wide and the other is 400px wide. The [`sizes`](/en-US/docs/Web/HTML/Element/img#sizes) attribute is used to specify the width at which the image should be drawn given the viewport's width. ### HTML For viewports up to 400px wide, the image is drawn at a width of 200px. Otherwise, it's drawn at 400px. ```html <p>Image width: <span class="size">?</span>px (resize to update)</p> <img src="/en-US/docs/Web/HTML/Element/img/clock-demo-200px.png" alt="Clock" srcset=" /en-US/docs/Web/HTML/Element/img/clock-demo-200px.png 200w, /en-US/docs/Web/HTML/Element/img/clock-demo-400px.png 400w " sizes="(max-width: 400px) 200px, 400px" /> ``` ### JavaScript JavaScript looks at the `width` property to determine the width of the image at the moment. This is performed in the window's {{domxref("Window.load_event", "load")}} and {{domxref("Window.resize_event", "resize")}} event handlers so the most current width information is always available. ```js const clockImage = document.querySelector("img"); let output = document.querySelector(".size"); const updateWidth = (event) => { output.innerText = clockImage.width; }; window.addEventListener("load", updateWidth); window.addEventListener("resize", updateWidth); ``` ### Result {{EmbedLiveSample("Examples", 640, 450)}} This example may be easier to try out {{LiveSampleLink('Examples', 'in its own window')}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.width")}} - {{domxref("HTMLEmbedElement.width")}} - {{domxref("HTMLIFrameElement.width")}} - {{domxref("HTMLObjectElement.width")}} - {{domxref("HTMLSourceElement.width")}} - {{domxref("HTMLVideoElement.width")}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/complete/index.md
--- title: "HTMLImageElement: complete property" short-title: complete slug: Web/API/HTMLImageElement/complete page-type: web-api-instance-property browser-compat: api.HTMLImageElement.complete --- {{APIRef("HTML DOM")}} The read-only {{domxref("HTMLImageElement")}} interface's **`complete`** attribute is a Boolean value which indicates whether or not the image has completely loaded. ## Value A Boolean value which is `true` if the image has completely loaded; otherwise, the value is `false`. The image is considered completely loaded if any of the following are true: - Neither the [`src`](/en-US/docs/Web/HTML/Element/img#src) nor the [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) attribute is specified. - The `srcset` attribute is absent and the `src` attribute, while specified, is the empty string (`""`). - The image resource has been fully fetched and has been queued for rendering/compositing. - The image element has previously determined that the image is fully available and ready for use. - The image is "broken;" that is, the image failed to load due to an error or because image loading is disabled. It's worth noting that due to the image potentially being received asynchronously, the value of `complete` may change while your script is running. ## Examples Consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. These photos may be very large, so you don't want to wait for them to load, so your code uses `async`/`await` to load the images in the background. But imagine that you have other code that needs to only run when the image has completed loading, such as a command that performs red-eye removal on the image in the lightbox. While ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. So the `fixRedEyeCommand()` function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's `complete` property before attempting to do its work. This is demonstrated in the code below. ```js let lightboxElem = document.querySelector("#lightbox"); let lightboxImgElem = lightboxElem.querySelector("img"); let lightboxControlsElem = lightboxElem.querySelector(".toolbar"); async function loadImage(url, elem) { return new Promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightBox(url) { lightboxElem.style.display = "block"; await loadImage("https://somesite.net/huge-image.jpg", lightboxImgElem); lightboxControlsElem.disabled = false; } // … function fixRedEyeCommand() { if (lightboxElem.style.display === "block" && lightboxImgElem.complete) { fixRedEye(lightboxImgElem); } else { /* can't start doing this until the image is fully loaded */ } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/height/index.md
--- title: "HTMLImageElement: height property" short-title: height slug: Web/API/HTMLImageElement/height page-type: web-api-instance-property browser-compat: api.HTMLImageElement.height --- {{APIRef("HTML DOM")}} The **`height`** property of the {{domxref("HTMLImageElement")}} interface indicates the height at which the image is drawn, in {{Glossary("CSS pixels")}} if the image is being drawn or rendered to any visual medium such as the screen or a printer; otherwise, it's the natural, pixel density corrected height of the image. ## Value An integer value indicating the height of the image. The terms in which the height is defined depends on whether the image is being rendered to a visual medium or not. - If the image is being rendered to a visual medium such as a screen or printer, the height is expressed in {{Glossary("CSS pixels")}}. - Otherwise, the image's height is represented using its natural (intrinsic) height, adjusted for the display density as indicated by {{domxref("HTMLImageElement.naturalHeight", "naturalHeight")}}. ## Examples In this example, two different sizes are provided for an image of a clock using the [`srcset`](/en-US/docs/Web/HTML/Element/img#srcset) attribute. One is 200px wide and the other is 400px wide. Further, the [`sizes`](/en-US/docs/Web/HTML/Element/img#sizes) attribute is provided to specify the width at which the image should be drawn given the viewport's width. ### HTML Specifically, for viewports up to 400px wide, the image is drawn at a width of 200px; otherwise, it's drawn at 300px. ```html <p>Image height: <span class="size">?</span>px (resize to update)</p> <img src="/en-US/docs/Web/HTML/Element/img/clock-demo-200px.png" alt="Clock" srcset=" /en-US/docs/Web/HTML/Element/img/clock-demo-200px.png 200w, /en-US/docs/Web/HTML/Element/img/clock-demo-400px.png 400w " sizes="(max-width: 400px) 200px, 300px" /> ``` ### JavaScript The JavaScript code looks at the `height` to determine the height of the image given the width at which it's currently drawn. ```js const clockImage = document.querySelector("img"); let output = document.querySelector(".size"); const updateHeight = (event) => { output.innerText = clockImage.height; }; window.addEventListener("load", updateHeight); window.addEventListener("resize", updateHeight); ``` ### Result {{EmbedLiveSample("Examples", 640, 450)}} This example may be easier to try out {{LiveSampleLink('Examples', 'in its own window')}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.height")}} - {{domxref("HTMLEmbedElement.height")}} - {{domxref("HTMLIFrameElement.height")}} - {{domxref("HTMLObjectElement.height")}} - {{domxref("HTMLSourceElement.height")}} - {{domxref("HTMLVideoElement.height")}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/longdesc/index.md
--- title: "HTMLImageElement: longDesc property" short-title: longDesc slug: Web/API/HTMLImageElement/longDesc page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLImageElement.longDesc --- {{APIRef("HTML DOM")}}{{deprecated_header}} The _deprecated_ property **`longDesc`** on the {{domxref("HTMLImageElement")}} interface specifies the URL of a text or HTML file which contains a long-form description of the image. This can be used to provide optional added details beyond the short description provided in the [`title`](/en-US/docs/Web/HTML/Global_attributes#title) attribute. ## Value A string which may be either an empty string (indicating that no long description is available) or the URL of a file containing a long form description of the image's contents. For example, if the image is a [PNG](/en-US/docs/Web/Media/Formats/Image_types#png_portable_network_graphics) of a flowchart. The `longDesc` property could be used to provide an explanation of the flow of control represented by the chart, using only text. This can be used by readers both as an explanation, but also as a substitute for visually-impaired users. ## Usage notes This property is _deprecated_ and should no longer be used. Instead of using `longDesc` to provide a link to a detailed description of an image, encapsulate the image within a link using the {{HTMLElement("a")}} element. Consider the following older HTML: ```html <img src="taco-tuesday.jpg" alt="Taco Tuesday" longdesc="image-descriptions/taco-tuesday.html" /> ``` Here, the `longDesc` is used to indicate that the user should be able to access a detailed description of the image `taco-tuesday.jpg` in the HTML file `image-descriptions/taco-tuesday.html`. This can be easily converted into modern HTML: ```html <a href="image-descriptions/taco-tuesday.html"> <img src="taco-tuesday.jpg" alt="Taco Tuesday" /> </a> ``` With that, the image is a link to the HTML file describing the image in more detail. ## Specifications This feature is not part of any current specification. It is no longer on track to become a standard. ## Browser compatibility {{Compat}} ## See also - [`aria-details`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-details)
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/referrerpolicy/index.md
--- title: "HTMLImageElement: referrerPolicy property" short-title: referrerPolicy slug: Web/API/HTMLImageElement/referrerPolicy page-type: web-api-instance-property browser-compat: api.HTMLImageElement.referrerPolicy --- {{APIRef("HTML DOM")}} The **`HTMLImageElement.referrerPolicy`** property reflects the HTML [`referrerpolicy`](/en-US/docs/Web/HTML/Element/img#referrerpolicy) attribute of the {{HTMLElement("img")}} element defining which referrer is sent when fetching the resource. ## Value A string; one of the following: - `no-referrer` - : The {{HTTPHeader("Referer")}} header will be omitted entirely. No referrer information is sent along with requests. - `no-referrer-when-downgrade` - : The URL is sent as a referrer when the protocol security level stays the same (e.g.HTTP→HTTP, HTTPS→HTTPS), but isn't sent to a less secure destination (e.g. HTTPS→HTTP). - `origin` - : Only send the origin of the document as the referrer in all cases. The document `https://example.com/page.html` will send the referrer `https://example.com/`. - `origin-when-cross-origin` - : Send a full URL when performing a same-origin request, but only send the origin of the document for other cases. - `same-origin` - : A referrer will be sent for [same-site origins](/en-US/docs/Web/Security/Same-origin_policy), but cross-origin requests will contain no referrer information. - `strict-origin` - : Only send the origin of the document as the referrer when the protocol security level stays the same (e.g. HTTPS→HTTPS), but don't send it to a less secure destination (e.g. HTTPS→HTTP). - `strict-origin-when-cross-origin` (default) - : This is the user agent's default behavior if no policy is specified. Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (e.g. HTTPS→HTTPS), and send no header to a less secure destination (e.g. HTTPS→HTTP). - `unsafe-url` - : Send a full URL when performing a same-origin or cross-origin request. This policy will leak origins and paths from TLS-protected resources to insecure origins. Carefully consider the impact of this setting. ## Examples ```js const img = new Image(); img.src = "img/logo.png"; img.referrerPolicy = "origin"; const div = document.getElementById("divAround"); div.appendChild(img); // Fetch the image using the origin as the referrer ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLAnchorElement.referrerPolicy")}}, {{domxref("HTMLAreaElement.referrerPolicy")}}, and {{domxref("HTMLIFrameElement.referrerPolicy")}}.
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/align/index.md
--- title: "HTMLImageElement: align property" short-title: align slug: Web/API/HTMLImageElement/align page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLImageElement.align --- {{APIRef("HTML DOM")}}{{deprecated_header}} The _obsolete_ **`align`** property of the {{domxref("HTMLImageElement")}} interface is a string which indicates how to position the image relative to its container. You should instead use the CSS property {{cssxref("vertical-align")}}, which does in fact also work on images despite its name. You can also use the {{cssxref("float")}} property to float the image to the left or right margin. The `align` property reflects the HTML [`align`](/en-US/docs/Web/HTML/Element/img#align) content attribute. ## Value A string specifying one of the following strings which set the alignment mode for the image. ### Baseline alignment These three values specify the alignment of the element relative to the text baseline. These should be replaced by using the CSS {{cssxref("vertical-align")}} property. - `bottom` - : The bottom edge of the image is to be aligned vertically with the current text baseline. **Default value.** - `middle` - : The center of the object should be aligned vertically with the current baseline. - `top` - : The top edge of the object should be aligned vertically with the current baseline. It may be worth noting that {{cssxref("vertical-align")}} offers several additional options for its value; you may wish to consider these when changing your code to use it. ### Floating images horizontally The `left` and `right` properties don't affect the baseline-relative alignment. Instead, they cause the image to "float" to the left or right margin, allowing the following text to flow around the image. You should instead use the CSS {{cssxref("float")}} property, specifying as the value either `left` or `right`. - `left` - : Floats the image over to place the left edge flush against the current margin. Any text that follows will flow against the image's right edge. - `right` - : Floats the image to place its right edge flush against the right margin. Subsequent text will flow along the image's left edge. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlimageelement
data/mdn-content/files/en-us/web/api/htmlimageelement/currentsrc/index.md
--- title: "HTMLImageElement: currentSrc property" short-title: currentSrc slug: Web/API/HTMLImageElement/currentSrc page-type: web-api-instance-property browser-compat: api.HTMLImageElement.currentSrc --- {{APIRef("HTML DOM")}} The read-only {{domxref("HTMLImageElement")}} property **`currentSrc`** indicates the URL of the image which is currently presented in the {{HTMLElement("img")}} element it represents. ## Value A string indicating the full URL of the image currently visible in the {{HTMLElement("img")}} element represented by the `HTMLImageElement`. This is useful when you provide multiple image options using the {{domxref("HTMLImageElement.sizes", "sizes")}} and/or {{domxref("HTMLImageElement.srcset")}} properties. `currentSrc` lets you determine which image from the set of provided images was selected by the browser. ## Examples In this example, two different sizes are provided for an image of a clock. One is 200px wide and the other is 400px wide. The [`sizes`](/en-US/docs/Web/HTML/Element/img#sizes) attribute is provided to indicate that the image should be drawn at 50% of the document width if the viewport is under 400px wide; otherwise, the image is drawn at 90% width of the document. ### HTML ```html <img src="/files/16797/clock-demo-400px.png" alt="Clock" srcset=" /en-US/docs/Web/HTML/Element/img/clock-demo-200px.png 200w, /en-US/docs/Web/HTML/Element/img/clock-demo-400px.png 400w " sizes="(max-width: 400px) 50%, 90%" /> ``` ### JavaScript ```js const clockImage = document.querySelector("img"); const p = document.createElement("p"); p.textContent = clockImage.currentSrc.endsWith("200px.png") ? "Using the 400px image!" : "Using the 200px image."; document.body.appendChild(p); ``` ### Result {{EmbedLiveSample("Examples", 640, 370)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/domexception/index.md
--- title: DOMException slug: Web/API/DOMException page-type: web-api-interface browser-compat: api.DOMException --- {{ APIRef("DOM") }} The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. This is how error conditions are described in web APIs. Each exception has a **name**, which is a short "PascalCase"-style string identifying the error or abnormal condition. `DOMException` is a {{Glossary("Serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker.postMessage()", "postMessage()")}}. ## Constructor - {{domxref("DOMException.DOMException()", "DOMException()")}} - : Returns a `DOMException` object with a specified message and name. ## Instance properties - {{domxref("DOMException.code")}} {{deprecated_inline}} {{ReadOnlyInline}} - : Returns one of the legacy error code constants, or `0` if none match. - {{domxref("DOMException.message")}} {{ReadOnlyInline}} - : Returns a string representing a message or description associated with the given [error name](#error_names). - {{domxref("DOMException.name")}} {{ReadOnlyInline}} - : Returns a string that contains one of the strings associated with an [error name](#error_names). ## Error names Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list. Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name: - Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR` - Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR` - Legacy code value: `16`, legacy constant name: `VALIDATION_ERR` > **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past. - `IndexSizeError` - : The index is not in the allowed range. For example, this can be thrown by the {{ domxref("Range") }} object. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`) - `HierarchyRequestError` - : The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`) - `WrongDocumentError` - : The object is in the wrong {{ domxref("Document") }}. (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`) - `InvalidCharacterError` - : The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`) - `NoModificationAllowedError` - : The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`) - `NotFoundError` - : The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`) - `NotSupportedError` - : The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`) - `InvalidStateError` - : The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`) - `InUseAttributeError` - : The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`) - `SyntaxError` - : The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`) - `InvalidModificationError` - : The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`) - `NamespaceError` - : The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`) - `InvalidAccessError` - : The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`) - `TypeMismatchError` {{deprecated_inline}} - : The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript {{jsxref("TypeError")}} exception is now raised instead of a `DOMException` with this value. - `SecurityError` - : The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`) - `NetworkError` {{experimental_inline}} - : A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`) - `AbortError` {{experimental_inline}} - : The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`) - `URLMismatchError` {{experimental_inline}} - : The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`) - `QuotaExceededError` {{experimental_inline}} - : The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`) - `TimeoutError` - : The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`) - `InvalidNodeTypeError` {{experimental_inline}} - : The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`) - `DataCloneError` {{experimental_inline}} - : The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`) - `EncodingError` {{experimental_inline}} - : The encoding or decoding operation failed (No legacy code value and constant name). - `NotReadableError` {{experimental_inline}} - : The input/output read operation failed (No legacy code value and constant name). - `UnknownError` {{experimental_inline}} - : The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name). - `ConstraintError` {{experimental_inline}} - : A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name). - `DataError` {{experimental_inline}} - : Provided data is inadequate (No legacy code value and constant name). - `TransactionInactiveError` {{experimental_inline}} - : A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name). - `ReadOnlyError` {{experimental_inline}} - : The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name). - `VersionError` {{experimental_inline}} - : An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name). - `OperationError` {{experimental_inline}} - : The operation failed for an operation-specific reason (No legacy code value and constant name). - `NotAllowedError` - : The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [A polyfill of `DOMException`](https://github.com/zloirock/core-js#domexception) is available in [`core-js`](https://github.com/zloirock/core-js) - {{ domxref("DOMError") }}
0
data/mdn-content/files/en-us/web/api/domexception
data/mdn-content/files/en-us/web/api/domexception/name/index.md
--- title: "DOMException: name property" short-title: name slug: Web/API/DOMException/name page-type: web-api-instance-property browser-compat: api.DOMException.name --- {{ APIRef("DOM") }} The **`name`** read-only property of the {{domxref("DOMException")}} interface returns a string that contains one of the strings associated with an [error name](/en-US/docs/Web/API/DOMException#error_names). ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/domexception
data/mdn-content/files/en-us/web/api/domexception/domexception/index.md
--- title: "DOMException: DOMException() constructor" short-title: DOMException() slug: Web/API/DOMException/DOMException page-type: web-api-constructor browser-compat: api.DOMException.DOMException --- {{ APIRef("DOM") }} The **`DOMException()`** constructor returns a {{domxref("DOMException")}} object with a specified message and name. ## Syntax ```js-nolint new DOMException() new DOMException(message) new DOMException(message, name) ``` ### Parameters - `message` {{optional_inline}} - : A description of the exception. If not present, the empty string `''` is used. - `name` {{optional_inline}} - : A string. If the specified name is a [standard error name](/en-US/docs/Web/API/DOMException#error_names), then getting the [`code`](/en-US/docs/Web/API/DOMException/code) property of the `DOMException` object will return the code number corresponding to the specified name. ### Return value A newly created {{domxref("DOMException")}} object. ## Examples In this example, pressing the button causes a custom `DOMException` to be thrown, which is then caught and the custom error message shown in an alert. ### HTML ```html <button>Trigger DOM Exception</button> <p id="output"></p> ``` ### JavaScript ```js const button = document.querySelector("button"); button.onclick = () => { try { throw new DOMException("Custom DOM Exception Triggered."); } catch (error) { document.querySelector("#output").textContent = `Error: ${error.message}`; } }; ``` ### Result {{ EmbedLiveSample('Examples', '100%', 100) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [A polyfill of `DOMException` constructor](https://github.com/zloirock/core-js#domexception) is available in [`core-js`](https://github.com/zloirock/core-js)
0
data/mdn-content/files/en-us/web/api/domexception
data/mdn-content/files/en-us/web/api/domexception/message/index.md
--- title: "DOMException: message property" short-title: message slug: Web/API/DOMException/message page-type: web-api-instance-property browser-compat: api.DOMException.message --- {{ APIRef("DOM") }} The **`message`** read-only property of the {{domxref("DOMException")}} interface returns a string representing a message or description associated with the given [error name](/en-US/docs/Web/API/DOMException#error_names). ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/domexception
data/mdn-content/files/en-us/web/api/domexception/code/index.md
--- title: "DOMException: code property" short-title: code slug: Web/API/DOMException/code page-type: web-api-instance-property status: - deprecated browser-compat: api.DOMException.code --- {{ APIRef("DOM") }} {{deprecated_header}} The **`code`** read-only property of the {{domxref("DOMException")}} interface returns one of the legacy [error code constants](/en-US/docs/Web/API/DOMException#error_names), or `0` if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the {{domxref("DOMException.name")}} attribute. ## Value One of the [error code constants](/en-US/docs/Web/API/DOMException#error_names), or `0` if none match. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmliframeelement/index.md
--- title: HTMLIFrameElement slug: Web/API/HTMLIFrameElement page-type: web-api-interface browser-compat: api.HTMLIFrameElement --- {{APIRef("HTML DOM")}} The **`HTMLIFrameElement`** interface provides special properties and methods (beyond those of the {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating the layout and presentation of inline frame elements. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}_. - {{domxref("HTMLIFrameElement.align")}} {{Deprecated_Inline}} - : A string that specifies the alignment of the frame with respect to the surrounding context. - {{domxref("HTMLIFrameElement.allow")}} - : A list of origins the frame is allowed to display content from. This attribute also accepts the values `self` and `src` which represent the origin in the iframe's src attribute. The default value is `src`. - {{domxref("HTMLIFrameElement.allowFullscreen")}} - : A boolean value indicating whether the inline frame is willing to be placed into full screen mode. See [Using fullscreen mode](/en-US/docs/Web/API/Fullscreen_API) for details. - {{domxref("HTMLIFrameElement.allowPaymentRequest")}} {{Deprecated_Inline}} {{Non-standard_Inline}} - : A boolean value indicating whether the [Payment Request API](/en-US/docs/Web/API/Payment_Request_API) may be invoked inside a cross-origin iframe. - {{domxref("HTMLIFrameElement.contentDocument")}} {{ReadOnlyInline}} - : Returns a {{domxref("Document")}}, the active document in the inline frame's nested browsing context. - {{domxref("HTMLIFrameElement.contentWindow")}} {{ReadOnlyInline}} - : Returns a {{glossary("WindowProxy")}}, the window proxy for the nested browsing context. - {{domxref("HTMLIFrameElement.credentialless")}} {{Experimental_Inline}} - : A boolean value indicating whether the `<iframe>` is credentialless, meaning that its content is loaded in a new, ephemeral context. This context does not have access to the parent context's shared storage and credentials. In return, the {{httpheader("Cross-Origin-Embedder-Policy")}} (COEP) embedding rules can be lifted, so documents with COEP set can embed third-party documents that do not. See [IFrame credentialless](/en-US/docs/Web/Security/IFrame_credentialless) for a deeper explanation. - {{domxref("HTMLIFrameElement.csp")}} {{Experimental_Inline}} - : Specifies the Content Security Policy that an embedded document must agree to enforce upon itself. - {{domxref("HTMLIFrameElement.featurePolicy")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the {{domxref("FeaturePolicy")}} interface which provides a simple API for introspecting the [Permissions Policies](/en-US/docs/Web/HTTP/Permissions_Policy) applied to a specific document. - {{domxref("HTMLIFrameElement.frameBorder")}} {{Deprecated_Inline}} - : A string that indicates whether to create borders between frames. - {{domxref("HTMLIFrameElement.height")}} - : A string that reflects the [`height`](/en-US/docs/Web/HTML/Element/iframe#height) HTML attribute, indicating the height of the frame. - {{domxref("HTMLIFrameElement.loading")}} - : A string providing a hint to the browser that the iframe should be loaded immediately (`eager`) or on an as-needed basis (`lazy`). This reflects the [`loading`](/en-US/docs/Web/HTML/Element/iframe#loading) HTML attribute. - {{domxref("HTMLIFrameElement.longDesc")}} {{Deprecated_Inline}} - : A string that contains the URI of a long description of the frame. - {{domxref("HTMLIFrameElement.marginHeight")}} {{Deprecated_Inline}} - : A string being the height of the frame margin. - {{domxref("HTMLIFrameElement.marginWidth")}} {{Deprecated_Inline}} - : A string being the width of the frame margin. - {{domxref("HTMLIFrameElement.name")}} - : A string that reflects the [`name`](/en-US/docs/Web/HTML/Element/iframe#name) HTML attribute, containing a name by which to refer to the frame. - {{domxref("HTMLIFrameElement.referrerPolicy")}} - : A string that reflects the [`referrerPolicy`](/en-US/docs/Web/HTML/Element/iframe#referrerpolicy) HTML attribute indicating which referrer to use when fetching the linked resource. - {{domxref("HTMLIFrameElement.sandbox")}} - : A {{domxref("DOMTokenList")}} that reflects the [`sandbox`](/en-US/docs/Web/HTML/Element/iframe#sandbox) HTML attribute, indicating extra restrictions on the behavior of the nested content. - {{domxref("HTMLIFrameElement.scrolling")}} {{Deprecated_Inline}} - : A string that indicates whether the browser should provide scrollbars for the frame. - {{domxref("HTMLIFrameElement.src")}} - : A string that reflects the [`src`](/en-US/docs/Web/HTML/Element/iframe#src) HTML attribute, containing the address of the content to be embedded. Note that programmatically removing an `<iframe>`'s src attribute (e.g. via {{domxref("Element.removeAttribute()")}}) causes `about:blank` to be loaded in the frame in Firefox (from version 65), Chromium-based browsers, and Safari/iOS. - {{domxref("HTMLIFrameElement.srcdoc")}} - : A string that represents the content to display in the frame. - {{domxref("HTMLIFrameElement.width")}} - : A string that reflects the [`width`](/en-US/docs/Web/HTML/Element/iframe#width) HTML attribute, indicating the width of the frame. ## Instance methods _Inherits methods from its parent, {{domxref("HTMLElement")}}_. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{HTMLElement("iframe")}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/name/index.md
--- title: "HTMLIFrameElement: name property" short-title: name slug: Web/API/HTMLIFrameElement/name page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.name --- {{APIRef("HTML DOM")}} The **`name`** property of the {{domxref("HTMLIFrameElement")}} interface is a string value that reflects the `name` attribute of the {{HTMLElement("iframe")}} element, indicating the specific name of the `<iframe>` element. ## Value A string. ## Examples ```html <iframe id="el" name="example"></iframe> ``` ```js const el = document.getElementById("el"); console.log(el.name); // Output: "example" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/credentialless/index.md
--- title: "HTMLIFrameElement: credentialless property" short-title: credentialless slug: Web/API/HTMLIFrameElement/credentialless page-type: web-api-instance-property status: - experimental browser-compat: api.HTMLIFrameElement.credentialless --- {{APIRef("HTML DOM")}}{{SeeCompatTable}} The **`credentialless`** property of the {{domxref("HTMLIFrameElement")}} interface indicates whether the {{htmlelement("iframe")}} is credentialless, meaning that documents inside will be loaded using new, ephemeral contexts. Those contexts do not have access to their network, cookies and storage data associated with their origin. Instead, they use new ones, local to the top-level document lifetime. It means any data stored won't be accessible anymore after the user navigates away from the page or reloads it. In return, the {{httpheader("Cross-Origin-Embedder-Policy")}} (COEP) embedding rules can be lifted, so documents with COEP set can embed third-party documents that do not. See [IFrame credentialless](/en-US/docs/Web/Security/IFrame_credentialless) for a deeper explanation. ## Value A boolean. The default value is `false`; set it to `true` to make the `<iframe>` credentialless. ## Examples ### Get Specify a credentialless `<iframe>` like so: ```html <iframe src="https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)" title="Spectre vulnerability Wikipedia page" width="960" height="600" credentialless></iframe> ``` Return the `credentialless` property value: ```js const iframeElem = document.querySelector("iframe"); console.log(iframeElem.credentialless); // will return true in supporting browsers ``` ### Set Alternatively, specify the minimum of details in the HTML: ```html <iframe width="960" height="600"> </iframe> ``` And set `credentialless` to `true` then load the `<iframe>` contents via script: ```js const iframeElem = document.querySelector("iframe"); iframeElem.credentialless = true; iframeElem.title = "Spectre vulnerability Wikipedia page"; iframeElem.src = "https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)"; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [IFrame credentialless](/en-US/docs/Web/Security/IFrame_credentialless) - {{htmlelement("iframe")}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/contentdocument/index.md
--- title: "HTMLIFrameElement: contentDocument property" short-title: contentDocument slug: Web/API/HTMLIFrameElement/contentDocument page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.contentDocument --- {{APIRef("HTML DOM")}} If the iframe and the iframe's parent document are [Same Origin](/en-US/docs/Web/Security/Same-origin_policy), returns a [`Document`](/en-US/docs/Web/API/Document) (that is, the active document in the inline frame's nested browsing context), else returns `null`. ## Example of contentDocument ```js const iframeDocument = document.querySelector("iframe").contentDocument; iframeDocument.body.style.backgroundColor = "blue"; // This would turn the iframe blue. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/allowfullscreen/index.md
--- title: "HTMLIFrameElement: allowFullscreen property" short-title: allowFullscreen slug: Web/API/HTMLIFrameElement/allowFullscreen page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.allowFullscreen --- {{APIRef("HTML DOM")}} The **`allowFullscreen`** property of the {{domxref("HTMLIFrameElement")}} interface is a boolean value that reflects the `allowfullscreen` attribute of the {{HTMLElement("iframe")}} element, indicating whether to allow the iframe's contents to use {{domxref("Element.requestFullscreen", "requestFullscreen()")}}. > **Note:** This property is considered a legacy property. Use `allow="fullscreen"` and {{domxref("HTMLIFrameElement.allow")}} instead. ## Value A boolean value. ## Examples ```html <iframe id="el" allowfullscreen></iframe> ``` ```js const el = document.getElementById("el"); console.log(el.allowFullscreen); // Output: true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Fullscreen API](/en-US/docs/Web/API/Fullscreen_API) - {{domxref("Element.requestFullscreen()")}} - [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) - {{httpheader("Permissions-Policy/fullscreen", "fullscreen")}} Permissions Policy directive
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/featurepolicy/index.md
--- title: "HTMLIFrameElement: featurePolicy property" short-title: featurePolicy slug: Web/API/HTMLIFrameElement/featurePolicy page-type: web-api-instance-property status: - experimental browser-compat: api.HTMLIFrameElement.featurePolicy --- {{APIRef("Feature Policy API")}}{{SeeCompatTable}} The **`featurePolicy`** read-only property of the {{DOMxRef("HTMLIFrameElement")}} interface returns the {{DOMxRef("FeaturePolicy")}} interface which provides a simple API for introspecting the [Permissions Policies](/en-US/docs/Web/HTTP/Permissions_Policy) applied to a specific frame. ## Value A [`FeaturePolicy`](/en-US/docs/Web/API/FeaturePolicy) object that can be used to inspect the Permissions Policy settings applied to the frame. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/loading/index.md
--- title: "HTMLIFrameElement: loading property" short-title: loading slug: Web/API/HTMLIFrameElement/loading page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.loading --- {{APIRef("HTML DOM")}} The **`loading`** property of the {{domxref("HTMLIFrameElement")}} interface is a string that provides a hint to the {{Glossary("user agent")}} indicating whether the [iframe](/en-US/docs/Web/HTML/Element/iframe) should be loaded immediately on page load, or only when it is needed. This can be used to optimize the loading of the document's contents. Iframes that are visible when the page loads can be downloaded immediately (eagerly), while iframes that are likely to be offscreen on initial page load can be downloaded lazily — just before they will appear in the window's {{Glossary("visual viewport")}}. ## Value A string providing a hint to the user agent as to how to best schedule the loading of the iframe. The possible values are: - `eager` - : Load the iframe as soon as the element is processed. This is the default. - `lazy` - : Load the iframe when the browser believes that it is likely to be need in the near future. ## Usage notes ### JavaScript must be enabled Loading is only deferred when JavaScript is enabled, irrespective of the value of this property. This is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing iframes in a page's markup such that a server can track how many are requested and when. ### Timing of the load event The {{domxref("Window.load_event", "load")}} event is fired when the document has been fully processed. Lazily loaded iframes do not affect the timing of the `load` event even if the iframe is in the visual viewport and is therefore fetched on page load. All eagerly loaded iframes in the document must be fetched before the `load` event can fire. ## Examples The example below shows how you might define a lazy-loaded iframe and then append it to a `<div>` in the document. The frame would then only be loaded when the frame about to become visible. ```js // Define iframe with lazy loading const iframe = document.createElement("iframe"); iframe.src = "https://example.com"; iframe.width = 320; iframe.height = 240; iframe.loading = "lazy"; // Add to div element with class named frameDiv const frameDiv = document.querySelector("div.frameDiv"); frameDiv.appendChild(iframe); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("iframe")}} element - [Web performance](/en-US/docs/Learn/Performance) in the MDN Learning Area - [Lazy loading](/en-US/docs/Web/Performance/Lazy_loading) in the MDN web performance guide - [It's time to lazy-load offscreen iframes!](https://web.dev/articles/iframe-lazy-loading) on web.dev
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/allowpaymentrequest/index.md
--- title: "HTMLIFrameElement: allowPaymentRequest property" short-title: allowPaymentRequest slug: Web/API/HTMLIFrameElement/allowPaymentRequest page-type: web-api-instance-property status: - deprecated - non-standard browser-compat: api.HTMLIFrameElement.allowPaymentRequest --- {{APIRef("HTML DOM")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`allowPaymentRequest`** property of the {{domxref("HTMLIFrameElement")}} interface returns a boolean value indicating whether the [Payment Request API](/en-US/docs/Web/API/Payment_Request_API) may be invoked on a cross-origin iframe. ## Value A boolean value. ## Browser compatibility {{Compat}} ## See also - [Payment Request API](/en-US/docs/Web/API/Payment_Request_API)
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/csp/index.md
--- title: "HTMLIFrameElement: csp property" short-title: csp slug: Web/API/HTMLIFrameElement/csp page-type: web-api-instance-property status: - experimental browser-compat: api.HTMLIFrameElement.csp --- {{APIRef("HTML DOM")}}{{SeeCompatTable}} The **`csp`** property of the {{domxref("HTMLIFrameElement")}} interface specifies the [Content Security Policy](/en-US/docs/Web/HTTP/CSP) that an embedded document must agree to enforce upon itself. ## Value A content security policy. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/src/index.md
--- title: "HTMLIFrameElement: src property" short-title: src slug: Web/API/HTMLIFrameElement/src page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.src --- {{APIRef}} The **`HTMLIFrameElement.src`** A string that reflects the [`src`](/en-US/docs/Web/HTML/Element/iframe#src) HTML attribute, containing the address of the content to be embedded. Note that programmatically removing an `<iframe>`'s src attribute (e.g. via {{domxref("Element.removeAttribute()")}}) causes `about:blank` to be loaded in the frame. ## Syntax ```js-nolint src = iframeElt.src iframeElt.src= src ``` ## Example ```js const iframe = document.createElement("iframe"); iframe.src = "/"; const body = document.querySelector("body"); body.appendChild(iframe); // Fetch the image using the complete URL as the referrer ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("HTMLAnchorElement.src")}} - {{DOMxRef("HTMLAreaElement.src")}} - {{DOMxRef("HTMLAreaElement.src")}}.
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/width/index.md
--- title: "HTMLIFrameElement: width property" short-title: width slug: Web/API/HTMLIFrameElement/width page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.width --- {{APIRef("HTML DOM")}} The **`width`** property of the {{domxref("HTMLIFrameElement")}} interface returns a string that reflects the `width` attribute of the {{HTMLElement("iframe")}} element, indicating the width of the frame in CSS pixels. ## Value A string indicating the width of the frame in CSS pixels. ## Examples ```html <iframe id="el" width="800" height="600"></iframe> ``` ```js const el = document.getElementById("el"); console.log(el.width); // Output: '800' ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.width")}} - {{domxref("HTMLEmbedElement.width")}} - {{domxref("HTMLImageElement.width")}} - {{domxref("HTMLObjectElement.width")}} - {{domxref("HTMLSourceElement.width")}} - {{domxref("HTMLVideoElement.width")}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/contentwindow/index.md
--- title: "HTMLIFrameElement: contentWindow property" short-title: contentWindow slug: Web/API/HTMLIFrameElement/contentWindow page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.contentWindow --- {{APIRef("HTML DOM")}} The **`contentWindow`** property returns the [Window](/en-US/docs/Web/API/Window) object of an [HTMLIFrameElement](/en-US/docs/Web/API/HTMLIFrameElement). This attribute is read-only. ## Value A [Window](/en-US/docs/Web/API/Window) object. ## Description Access to the {{domxref("Window")}} returned by `contentWindow` is subject to the rules defined by the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy), meaning that if the iframe is same-origin with the parent, then the parent can access the iframe's document and its internal DOM, and if they are cross-origin, it gets very limited access to the window's attributes. See ["Cross-origin script API access"](/en-US/docs/Web/Security/Same-origin_policy#cross-origin_script_api_access) for details. Pages can also use this property to find out which iframe sent a message using {{domxref("Window.postMessage()")}}, by comparing it with the message event's {{domxref("MessageEvent.source", "source")}} property. ## Examples ### Accessing an iframe's document This example modifies the `style` attribute of the document body. Note that this only works if the iframe's window is same-origin with its parent: otherwise attempting to access `contentWindow.document` will throw an exception. ```js const iframe = document.querySelector("iframe").contentWindow; iframe.document.querySelector("body").style.backgroundColor = "blue"; // this would turn the 1st iframe in document blue. ``` ### Mapping message sources to iframes This example could run in a page that hosts several iframes, any of which can send it messages using {{domxref("Window.postMessage()")}}. When the page receives a message, it wants to know which iframe contains the window that sent the message. To do this, when it receives a message, the page first checks that the message was from the expected origin, and then finds the iframe that was the source of the message by comparing the message event's {{domxref("MessageEvent.source", "source")}} property with the iframe's `contentWindow` property. ```js const expectedOrigin = "https://example.org"; const iframes = Array.from(document.querySelectorAll("iframe")); window.addEventListener("message", (e) => { if (e.origin !== expectedOrigin) return; const sourceIframe = iframes.find( (iframe) => iframe.contentWindow === e.source, ); console.log(sourceIframe); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/height/index.md
--- title: "HTMLIFrameElement: height property" short-title: height slug: Web/API/HTMLIFrameElement/height page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.height --- {{APIRef("HTML DOM")}} The **`height`** property of the {{domxref("HTMLIFrameElement")}} interface returns a string that reflects the `height` attribute of the {{HTMLElement("iframe")}} element, indicating the height of the frame in CSS pixels. ## Value A string indicating the height of the frame in CSS pixels. ## Examples ```html <iframe id="el" width="800" height="600"></iframe> ``` ```js const el = document.getElementById("el"); console.log(el.height); // Output: '600' ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.height")}} - {{domxref("HTMLEmbedElement.height")}} - {{domxref("HTMLImageElement.height")}} - {{domxref("HTMLObjectElement.height")}} - {{domxref("HTMLSourceElement.height")}} - {{domxref("HTMLVideoElement.height")}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/srcdoc/index.md
--- title: "HTMLIFrameElement: srcdoc property" short-title: srcdoc slug: Web/API/HTMLIFrameElement/srcdoc page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.srcdoc --- {{APIRef('HTMLIFrameElement')}} The **`srcdoc`** property of the {{domxref("HTMLIFrameElement")}} specifies the content of the page. ## Examples ```js const iframe = document.createElement("iframe"); iframe.srcdoc = `<!DOCTYPE html><p>Hello World!</p>`; document.body.appendChild(iframe); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmliframeelement
data/mdn-content/files/en-us/web/api/htmliframeelement/referrerpolicy/index.md
--- title: "HTMLIFrameElement: referrerPolicy property" short-title: referrerPolicy slug: Web/API/HTMLIFrameElement/referrerPolicy page-type: web-api-instance-property browser-compat: api.HTMLIFrameElement.referrerPolicy --- {{APIRef}} The **`HTMLIFrameElement.referrerPolicy`** property reflects the HTML [`referrerpolicy`](/en-US/docs/Web/HTML/Element/iframe#referrerpolicy) attribute of the {{HTMLElement("iframe")}} element defining which referrer is sent when fetching the resource. ## Value - `no-referrer` - : The {{HTTPHeader("Referer")}} header will be omitted entirely. No referrer information is sent along with requests. - `no-referrer-when-downgrade` - : The URL is sent as a referrer when the protocol security level stays the same (HTTP→HTTP, HTTPS→HTTPS), but isn't sent to a less secure destination (HTTPS→HTTP). - `origin` - : Only send the origin of the document as the referrer in all cases. The document `https://example.com/page.html` will send the referrer `https://example.com/`. - `origin-when-cross-origin` - : Send a full URL when performing a same-origin request, but only send the origin of the document for other cases. - `same-origin` - : A referrer will be sent for [same-site origins](/en-US/docs/Web/Security/Same-origin_policy), but cross-origin requests will contain no referrer information. - `strict-origin` - : Only send the origin of the document as the referrer when the protocol security level stays the same (HTTPS→HTTPS), but don't send it to a less secure destination (HTTPS→HTTP). - `strict-origin-when-cross-origin` (default) - : This is the user agent's default behavior if no policy is specified. Send a full URL when performing a same-origin request, only send the origin when the protocol security level stays the same (HTTPS→HTTPS), and send no header to a less secure destination (HTTPS→HTTP). - `unsafe-url` - : Send a full URL when performing a same-origin or cross-origin request. > **Note:** This policy will leak origins and paths from TLS-protected resources > to insecure origins. Carefully consider the impact of this setting. ## Examples ```js const iframe = document.createElement("iframe"); iframe.src = "/"; iframe.referrerPolicy = "unsafe-url"; const body = document.querySelector("body"); body.appendChild(iframe); // Fetch the image using the complete URL as the referrer ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLAnchorElement.referrerPolicy")}}, {{domxref("HTMLAreaElement.referrerPolicy")}}, and {{domxref("HTMLAreaElement.referrerPolicy")}}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/web_locks_api/index.md
--- title: Web Locks API slug: Web/API/Web_Locks_API page-type: web-api-overview browser-compat: - api.LockManager - api.Lock spec-urls: https://w3c.github.io/web-locks/ --- {{DefaultAPISidebar("Web Locks API")}}{{securecontext_header}} The **Web Locks API** allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, then release it. While held, no other script executing in the same origin can acquire the same lock, which allows a web app running in multiple tabs or workers to coordinate work and the use of resources. {{AvailableInWorkers}} ## Concepts and Usage A lock is an abstract concept representing some potentially shared resource, identified by a name chosen by the web app. For example, if a web app running in multiple tabs wants to ensure that only one tab is syncing data between the network and Indexed DB, each tab could try to acquire a "my_net_db_sync" lock, but only one tab will succeed (the [leader election pattern](https://en.wikipedia.org/wiki/Leader_election).) The API is used as follows: 1. The lock is requested. 2. Work is done while holding the lock in an asynchronous task. 3. The lock is automatically released when the task completes. ```js navigator.locks.request("my_resource", async (lock) => { // The lock has been acquired. await do_something(); await do_something_else(); // Now the lock will be released. }); ``` While a lock is held, requests for the same lock from this execution context, or from other tabs/workers, will be queued. The first queued request will be granted only when the lock is released. The API provides optional functionality that may be used as needed, including: - returning values from the asynchronous task - shared and exclusive lock modes - conditional acquisition - diagnostics to query the state of locks in an origin - an escape hatch to protect against deadlocks Locks are scoped to origins; the locks acquired by a tab from `https://example.com` have no effect on the locks acquired by a tab from `https://example.org:8080` as they are separate origins. The main entry point is {{domxref("LockManager.request", "navigator.locks.request()")}} which requests a lock. It takes a lock name, an optional set of options, and a callback. The callback is invoked when the lock is granted. The lock is automatically released when the callback returns, so usually the callback is an _async function_, which causes the lock to be released only when the async function has completely finished. The `request()` method itself returns a promise which resolves once the lock has been released; within an async function, a script can `await` the call to make the asynchronous code flow linearly. For example: ```js await do_something_without_lock(); // Request the lock. await navigator.locks.request("my_resource", async (lock) => { // The lock has been acquired. await do_something_with_lock(); await do_something_else_with_lock(); // Now the lock will be released. }); // The lock has been released. await do_something_else_without_lock(); ``` ### Options Several options can be passed when requesting a lock: - `mode`: The default mode is "exclusive", but "shared" can be specified. There can be only one "exclusive" holder of a lock, but multiple "shared" requests can be granted at the same time. This can be used to implement the [readers-writer pattern](https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock). - `ifAvailable`: If specified, the lock request will fail if the lock cannot be granted immediately without waiting. The callback is invoked with `null`. - `steal`: If specified, then any held locks with the same name will be released, and the request will be granted, preempting any queued requests for it. - `signal`: An {{domxref("AbortSignal")}} can be passed in, allowing a lock request to be aborted. This can be used to implement a timeout on requests. ### Monitoring The {{domxref("LockManager.query", "navigator.locks.query()")}} method can be used by scripts to introspect the state of the lock manager for the origin. This can be useful when debugging, for example, identifying why a lock could not be acquired. The results are a snapshot of the lock manager state, which identifies held and requested locks and some additional data (e.g. mode) about each, at the time the snapshot was taken. ### Advanced use For more complicated cases, such as holding the lock for an arbitrary amount of time, the callback can return a promise explicitly resolved by the script: ```js // Capture promise control functions: let resolve, reject; const p = new Promise((res, rej) => { resolve = res; reject = rej; }); // Request the lock: navigator.locks.request( "my_resource", // Lock is acquired. (lock) => p, // Now lock will be held until either resolve() or reject() is called. ); ``` ### Deadlocks A deadlock occurs when a process can no longer make progress because each part is waiting on a request that cannot be satisfied. This can occur with this API in complex use-cases, for example, if multiple locks are requested out-of-order. If tab 1 holds lock A and tab 2 holds lock B, then tab 1 attempts to also acquire lock B and tab 2 attempts to also acquire lock A, neither request can be granted. Web applications can avoid this through several strategies, such as ensuring lock requests are not nested, or are always well ordered, or have timeouts. Note that such deadlocks only affect the locks themselves and code depending on them; the browser, other tabs, and other script in the page is not affected. ## Interfaces - {{domxref("Lock")}} - : Provides the name and mode of a previously requested lock, which is received in the callback to {{domxref("LockManager.request()")}}. - {{domxref("LockManager")}} - : Provides methods for requesting a new {{domxref("Lock")}} object and querying for an existing {{domxref('Lock')}} object. To get an instance of {{domxref("LockManager")}}, call {{domxref("navigator.locks")}}. ### Extensions to other interfaces - {{domxref("Navigator.locks")}} {{ReadOnlyInline}} - : Returns a {{domxref("LockManager")}} object that provides methods for requesting a new {{domxref('Lock')}} object and querying for an existing {{domxref('Lock')}} object. - {{domxref("WorkerNavigator.locks")}} {{ReadOnlyInline}} - : Returns a {{DOMxRef("LockManager")}} object which provides methods for requesting a new {{DOMxRef('Lock')}} object and querying for an existing {{domxref('Lock')}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0