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/element
data/mdn-content/files/en-us/web/api/element/attachshadow/index.md
--- title: "Element: attachShadow() method" short-title: attachShadow() slug: Web/API/Element/attachShadow page-type: web-api-instance-method browser-compat: api.Element.attachShadow --- {{APIRef('Shadow DOM')}} The **`Element.attachShadow()`** method attaches a shadow DOM tree to the specified element and returns a reference to its {{domxref("ShadowRoot")}}. ## Elements you can attach a shadow to Note that you can't attach a shadow root to every type of element. There are some that can't have a shadow DOM for security reasons (for example {{htmlelement("a")}}). The following is a list of elements you _can_ attach a shadow root to: - Any autonomous custom element with a [valid name](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name) - {{htmlelement("article")}} - {{htmlelement("aside")}} - {{htmlelement("blockquote")}} - {{htmlelement("body")}} - {{htmlelement("div")}} - {{htmlelement("footer")}} - {{htmlelement("Heading_Elements", "h1")}} - {{htmlelement("Heading_Elements", "h2")}} - {{htmlelement("Heading_Elements", "h3")}} - {{htmlelement("Heading_Elements", "h4")}} - {{htmlelement("Heading_Elements", "h5")}} - {{htmlelement("Heading_Elements", "h6")}} - {{htmlelement("header")}} - {{htmlelement("main")}} - {{htmlelement("nav")}} - {{htmlelement("p")}} - {{htmlelement("section")}} - {{htmlelement("span")}} ## Syntax ```js-nolint attachShadow(options) ``` ### Parameters - `options` - : An object which contains the following fields: - `mode` - : A string specifying the _encapsulation mode_ for the shadow DOM tree. This can be one of: - `open` - : Elements of the shadow root are accessible from JavaScript outside the root, for example using {{domxref("Element.shadowRoot")}}: ```js element.attachShadow({ mode: "open" }); element.shadowRoot; // Returns a ShadowRoot obj ``` - `closed` - : Denies access to the node(s) of a closed shadow root from JavaScript outside it: ```js element.attachShadow({ mode: "closed" }); element.shadowRoot; // Returns null ``` - `clonable` {{Optional_Inline}} - : A boolean that specifies whether the shadow root is clonable: when set to `true`, the shadow host cloned with {{domxref("Node.cloneNode()")}} or {{domxref("Document.importNode()")}} will include shadow root in the copy. Its default value is `false`, unless the shadow root is created via declarative shadow DOM. - `delegatesFocus` {{Optional_Inline}} - : A boolean that, when set to `true`, specifies behavior that mitigates custom element issues around focusability. When a non-focusable part of the shadow DOM is clicked, the first focusable part is given focus, and the shadow host is given any available `:focus` styling. Its default value is `false`. - `slotAssignment` {{Optional_inline}} - : A string specifying the _slot assignment mode_ for the shadow DOM tree. This can be one of: - `named` - : Elements are automatically assigned to {{HTMLElement("slot")}} elements within this shadow root. Any descendants of the host with a `slot` attribute which matches the `name` attribute of a `<slot>` within this shadow root will be assigned to that slot. Any top-level children of the host with no `slot` attribute will be assigned to a `<slot>` with no `name` attribute (the "default slot") if one is present. - `manual` - : Elements are not automatically assigned to {{HTMLElement("slot")}} elements. Instead, they must be manually assigned with {{domxref("HTMLSlotElement.assign()")}}. Its default value is `named`. ### Return value Returns a {{domxref("ShadowRoot")}} object. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : The element you are trying to attach to is already a shadow host. - `NotSupportedError` {{domxref("DOMException")}} - : You are trying to attach a shadow root to an element outside the HTML namespace, the element cannot have a shadow attached to it, or the static property `disabledFeatures` has been given a value of `"shadow"` in the element definition. ## Examples ### Word count custom element The following example is taken from our [word-count-web-component](https://github.com/mdn/web-components-examples/tree/main/word-count-web-component) demo ([see it live also](https://mdn.github.io/web-components-examples/word-count-web-component/)). You can see that we use `attachShadow()` in the middle of the code to create a shadow root, which we then attach our custom element's contents to. ```js // Create a class for the element class WordCount extends HTMLParagraphElement { constructor() { // Always call super first in constructor super(); // count words in element's parent element const wcParent = this.parentNode; function countWords(node) { const text = node.innerText || node.textContent; return text .trim() .split(/\s+/g) .filter((a) => a.trim().length > 0).length; } const count = `Words: ${countWords(wcParent)}`; // Create a shadow root const shadow = this.attachShadow({ mode: "open" }); // Create text node and add word count to it const text = document.createElement("span"); text.textContent = count; // Append it to the shadow root shadow.appendChild(text); // Update count when element content changes setInterval(() => { const count = `Words: ${countWords(wcParent)}`; text.textContent = count; }, 200); } } // Define the new element customElements.define("word-count", WordCount, { extends: "p" }); ``` ### Disabling shadow DOM If the element has a static property named `disabledFeatures`, which is an array containing the string `"shadow"`, then the `attachShadow()` call will throw an exception. For example: ```js class MyCustomElement extends HTMLElement { // Disable shadow DOM for this element. static disabledFeatures = ["shadow"]; constructor() { super(); } connectedCallback() { // Create a shadow root. // This will throw an exception. const shadow = this.attachShadow({ mode: "open" }); } } // Define the new element customElements.define("my-custom-element", MyCustomElement); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ShadowRoot.mode")}} - {{domxref("ShadowRoot.delegatesFocus")}} - {{domxref("ShadowRoot.slotAssignment")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/queryselector/index.md
--- title: "Element: querySelector() method" short-title: querySelector() slug: Web/API/Element/querySelector page-type: web-api-instance-method browser-compat: api.Element.querySelector --- {{APIRef("DOM")}} The **`querySelector()`** method of the {{domxref("Element")}} interface returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors. ## Syntax ```js-nolint querySelector(selectors) ``` ### Parameters - `selectors` - : A group of [selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors) to match the descendant elements of the {{domxref("Element")}} `baseElement` against; this must be valid CSS syntax, or a `SyntaxError` exception will occur. The first element found which matches this group of selectors is returned. ### Return value The first descendant element of `baseElement` which matches the specified group of `selectors`. The entire hierarchy of elements is considered when matching, including those outside the set of elements including `baseElement` and its descendants; in other words, `selectors` is first applied to the whole document, not the `baseElement`, to generate an initial list of potential elements. The resulting elements are then examined to see if they are descendants of `baseElement`. The first match of those remaining elements is returned by the `querySelector()` method. If no matches are found, the returned value is `null`. ### Exceptions - `SyntaxError` {{domxref("DOMException")}} - : Thrown if the specified `selectors` are invalid. ## Examples Let's consider a few examples. ### Find a specific element with specific values of an attribute In this first example, the first {{HTMLElement("style")}} element which either has no type or has type "text/css" in the HTML document body is returned: ```js const el = document.body.querySelector( "style[type='text/css'], style:not([type])", ); ``` ### Get direct descendants using the :scope pseudo-class This example uses the {{cssxref(":scope")}} pseudo-class to retrieve direct children of the `parentElement` element. #### HTML ```html <div> <h6>Page Title</h6> <div id="parent"> <span>Love is Kind.</span> <span> <span>Love is Patient.</span> </span> <span> <span>Love is Selfless.</span> </span> </div> </div> ``` #### CSS ```css span { display: block; margin-bottom: 5px; } .red span { background-color: red; padding: 5px; } ``` #### JavaScript ```js const parentElement = document.querySelector("#parent"); let allChildren = parentElement.querySelectorAll(":scope > span"); allChildren.forEach((item) => item.classList.add("red")); ``` #### Result {{ EmbedLiveSample('Get_direct_descendants_using_the_scope_pseudo-class', 600, 160) }} ### The entire hierarchy counts This example demonstrates that the hierarchy of the entire document is considered when applying `selectors`, so that levels outside the specified `baseElement` are still considered when locating matches. #### HTML ```html <div> <h5>Original content</h5> <p> inside paragraph <span>inside span</span> inside paragraph </p> </div> <div> <h5>Output</h5> <div id="output"></div> </div> ``` #### JavaScript ```js const baseElement = document.querySelector("p"); document.getElementById("output").innerHTML = baseElement.querySelector("div span").innerHTML; ``` #### Result The result looks like this: {{ EmbedLiveSample('The_entire_hierarchy_counts', 600, 160) }} Notice how the `"div span"` selector still successfully matches the {{HTMLElement("span")}} element, even though the `baseElement`'s child nodes do not include the {{HTMLElement("div")}} element (it is still part of the specified selector). ### More examples See {{domxref("Document.querySelector()")}} for additional examples of the proper format for the `selectors`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Locating DOM elements using selectors](/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors) - [Attribute selectors](/en-US/docs/Web/CSS/Attribute_selectors) in the CSS Guide - [Attribute selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors) in the MDN Learning Area - {{domxref("Element.querySelectorAll()")}} - {{domxref("Document.querySelector()")}} and {{domxref("Document.querySelectorAll()")}} - {{domxref("DocumentFragment.querySelector()")}} and {{domxref("DocumentFragment.querySelectorAll()")}} - Other methods that take selectors: {{domxref("element.closest()")}} and {{domxref("element.matches()")}}.
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/beforematch_event/index.md
--- title: "Element: beforematch event" short-title: beforematch slug: Web/API/Element/beforematch_event page-type: web-api-event status: - experimental browser-compat: api.Element.beforematch_event --- {{APIRef}}{{SeeCompatTable}} An element receives a **`beforematch`** event when it is in the _hidden until found_ state and the browser is about to reveal its content because the user has found the content through the "find in page" feature or through fragment navigation. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("beforematch", (event) => {}); onbeforematch = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Usage notes The HTML [`hidden`](/en-US/docs/Web/HTML/Global_attributes/hidden) attribute accepts a value `until-found`: when this value is specified, the element is hidden but its content will be accessible to the browser's "find in page" feature or to fragment navigation. When these features cause a scroll to an element in a "hidden until found" subtree, the browser will: - fire a `beforematch` event on the hidden element - remove the `hidden` attribute from the element - scroll to the element ## Examples ### Using beforematch In this example we have: - Two {{HTMLElement("div")}} elements. The first is not hidden, while the second has `hidden="until-found"`and `id="until-found-box"` attributes. - A link whose target is the `"until-found-box"` fragment. We also have some JavaScript that listens for the `beforematch` event firing on the hidden until found element. The event handler changes the text content of the box. #### HTML ```html <a href="#until-found-box">Go to hidden content</a> <div>I'm not hidden</div> <div id="until-found-box" hidden="until-found">Hidden until found</div> ``` ```html hidden <button id="reset">Reset</button> ``` #### CSS ```css div { height: 40px; width: 300px; border: 5px dashed black; margin: 1rem 0; padding: 1rem; font-size: 2rem; } ``` ```css hidden #until-found-box { scroll-margin-top: 200px; } ``` #### JavaScript ```js const untilFound = document.querySelector("#until-found-box"); untilFound.addEventListener( "beforematch", () => (untilFound.textContent = "I've been revealed!"), ); ``` ```js hidden document.querySelector("#reset").addEventListener("click", () => { document.location.hash = ""; document.location.reload(); }); ``` #### Result Clicking the "Go to hidden content" button navigates to the hidden-until-found element. The `beforematch` event fires, the text content is updated, and then the element's content is displayed. To run the example again, click "Reload". {{EmbedLiveSample("Using beforematch", "", 300)}} If your browser does not support the `"until-found"` enumerated value of the `hidden` attribute, the second `<div>` will be hidden (as `hidden` was boolean prior to the addition of the `until-found` value). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML [`hidden`](/en-US/docs/Web/HTML/Global_attributes/hidden) attribute
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/animate/index.md
--- title: "Element: animate() method" short-title: animate() slug: Web/API/Element/animate page-type: web-api-instance-method browser-compat: api.Element.animate --- {{APIRef('Web Animations')}} The {{domxref("Element")}} interface's **`animate()`** method is a shortcut method which creates a new {{domxref("Animation")}}, applies it to the element, then plays the animation. It returns the created {{domxref("Animation")}} object instance. > **Note:** Elements can have multiple animations applied to them. You can get a list of the > animations that affect an element by calling {{domxref("Element.getAnimations()")}}. ## Syntax ```js-nolint animate(keyframes, options) ``` ### Parameters - `keyframes` - : Either an array of keyframe objects, **or** a keyframe object whose properties are arrays of values to iterate over. See [Keyframe Formats](/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats) for more details. - `options` - : Either an **integer representing the animation's duration** (in milliseconds), **or** an Object containing one or more timing properties described in the [`KeyframeEffect()` options parameter](/en-US/docs/Web/API/KeyframeEffect/KeyframeEffect#parameters) and/or the following options: - `id` {{optional_inline}} - : A property unique to `animate()`: A string with which to reference the animation. - `rangeEnd` {{optional_inline}} - : Specifies the end of an animation's attachment range along its timeline, i.e. where along the timeline an animation will end. The JavaScript equivalent of the CSS {{cssxref("animation-range-end")}} property. `rangeEnd` can take several different value types, as follows: - A string that can be `normal` (meaning no change to the animation's attachment range), a CSS {{cssxref("length-percentage")}} representing an offset, a `<timeline-range-name>`, or a `<timeline-range-name>` with a `<length-percentage>` following it. For example: ```plain "normal" "entry" "cover 100%" ``` See [`animation-range`](/en-US/docs/Web/CSS/animation-range) for a detailed description of the available values. Also check out the [View Timeline Ranges Visualizer](https://scroll-driven-animations.style/tools/view-timeline/ranges/), which shows exactly what the different values mean in an easy visual format. - An object containing `rangeName` (a string) and `offset` (a {{domxref("CSSNumericValue")}}) properties representing a `<timeline-range-name>` and `<length-percentage>`, as described in the previous bullet. For example: ```js { rangeName: 'entry', offset: CSS.percent('100'), } ``` - A {{domxref("CSSNumericValue")}} representing an offset, for example: ```js CSS.percent("100"); ``` - `rangeStart` {{optional_inline}} - : Specifies the start of an animation's attachment range along its timeline, i.e. where along the timeline an animation will start. The JavaScript equivalent of the CSS {{cssxref("animation-range-start")}} property. `rangeStart` can take the same value types as `rangeEnd`. - `timeline` {{optional_inline}} - : A property unique to `animate()`: The {{domxref("AnimationTimeline")}} to associate with the animation. Defaults to {{domxref("Document.timeline")}}. The JavaScript equivalent of the CSS {{cssxref("animation-timeline")}} property. ### Return value Returns an {{domxref("Animation")}}. ## Examples ### Rotating and scaling In this example we use the `animate()` method to rotate and scale an element. #### HTML ```html <div class="newspaper">Spinning newspaper<br />causes dizziness</div> ``` #### CSS ```css html, body { height: 100%; } body { display: flex; justify-content: center; align-items: center; background-color: black; } .newspaper { padding: 0.5rem; text-transform: uppercase; text-align: center; background-color: white; cursor: pointer; } ``` #### JavaScript ```js const newspaperSpinning = [ { transform: "rotate(0) scale(1)" }, { transform: "rotate(360deg) scale(0)" }, ]; const newspaperTiming = { duration: 2000, iterations: 1, }; const newspaper = document.querySelector(".newspaper"); newspaper.addEventListener("click", () => { newspaper.animate(newspaperSpinning, newspaperTiming); }); ``` #### Result {{EmbedLiveSample("Rotating and scaling")}} ### Down the Rabbit Hole demo In the demo [Down the Rabbit Hole (with the Web Animation API)](https://codepen.io/rachelnabors/pen/rxpmJL/?editors=0010), we use the convenient `animate()` method to immediately create and play an animation on the `#tunnel` element to make it flow upwards, infinitely. Notice the array of objects passed as keyframes and also the timing options block. ```js document.getElementById("tunnel").animate( [ // keyframes { transform: "translateY(0px)" }, { transform: "translateY(-300px)" }, ], { // timing options duration: 1000, iterations: Infinity, }, ); ``` ### Implicit to/from keyframes In newer browser versions, you are able to set a beginning or end state for an animation only (i.e. a single keyframe), and the browser will infer the other end of the animation if it is able to. For example, consider [this simple animation](https://mdn.github.io/dom-examples/web-animations-api/implicit-keyframes.html) — the Keyframe object looks like so: ```js let rotate360 = [{ transform: "rotate(360deg)" }]; ``` We have only specified the end state of the animation, and the beginning state is implied. ### timeline, rangeStart, and rangeEnd Typical usage of the `timeline`, `rangeStart`, and `rangeEnd` properties might look like this: ```js const img = document.querySelector("img"); const timeline = new ViewTimeline({ subject: img, axis: "block", }); img.animate( { opacity: [0, 1], transform: ["scaleX(0)", "scaleX(1)"], }, { fill: "both", duration: 1, timeline, rangeStart: "cover 0%", rangeEnd: "cover 100%", }, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Animation")}} - {{domxref("Element.getAnimations()")}} - {{cssxref("animation-range-end")}}, {{cssxref("animation-range-start")}}, {{cssxref("animation-timeline")}} - [CSS scroll-driven animations](/en-US/docs/Web/CSS/CSS_scroll-driven_animations) - [Web Animations API](/en-US/docs/Web/API/Web_Animations_API)
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/webkitmouseforcewillbegin_event/index.md
--- title: "Element: webkitmouseforcewillbegin event" short-title: webkitmouseforcewillbegin slug: Web/API/Element/webkitmouseforcewillbegin_event page-type: web-api-event status: - non-standard browser-compat: api.Element.webkitmouseforcewillbegin_event --- {{APIRef("Force Touch Events")}}{{Non-standard_header}} Safari for macOS fires the non-standard **`webkitmouseforcewillbegin`** event at an {{domxref("Element")}} before firing the initial {{domxref("Element/mousedown_event", "mousedown")}} event. This offers the opportunity to tell the system not to trigger any default Force Touch actions if and when the click turns into a {{domxref("Force Touch Events")}}. To instruct macOS not to engage any default Force Touch actions if the user apply enough pressure to activate a Force Touch event, call {{domxref("Event.preventDefault", "preventDefault()")}} on the `webkitmouseforcewillbegin` event object. **`webkitmouseforcewillbegin`** is a proprietary, WebKit-specific event. It is part of the {{domxref("Force Touch Events")}} feature. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("webkitmouseforceup", (event) => {}); onwebkitmouseforceup = (event) => {}; ``` ## Event type A {{domxref("MouseEvent")}}. Inherits from {{domxref("UIEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("MouseEvent")}} ## Event properties _This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}._ - {{domxref("MouseEvent.altKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>alt</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.button")}} {{ReadOnlyInline}} - : The button number that was pressed (if applicable) when the mouse event was fired. - {{domxref("MouseEvent.buttons")}} {{ReadOnlyInline}} - : The buttons being pressed (if any) when the mouse event was fired. - {{domxref("MouseEvent.clientX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.clientY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.ctrlKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>control</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.layerX")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the horizontal coordinate of the event relative to the current layer. - {{domxref("MouseEvent.layerY")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the vertical coordinate of the event relative to the current layer. - {{domxref("MouseEvent.metaKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>meta</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.movementX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.movementY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.offsetX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.offsetY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.pageX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.pageY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.relatedTarget")}} {{ReadOnlyInline}} - : The secondary target for the event, if there is one. - {{domxref("MouseEvent.screenX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.screenY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.shiftKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>shift</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The type of device that generated the event (one of the `MOZ_SOURCE_*` constants). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). - {{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The amount of pressure applied when clicking. - {{domxref("MouseEvent.x")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientX")}}. - {{domxref("MouseEvent.y")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientY")}}. ## Specifications _Not part of any specification._ Apple has [a description at the Mac Developer Library](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/SafariJSProgTopics/RespondingtoForceTouchEventsfromJavaScript.html). ## Browser compatibility {{Compat}} ## See also - [Introduction to events](/en-US/docs/Learn/JavaScript/Building_blocks/Events) - {{domxref("Element/webkitmouseforcedown_event", "webkitmouseforcedown")}} - {{domxref("Element/webkitmouseforceup_event", "webkitmouseforceup")}} - {{domxref("Element/webkitmouseforcechanged_event", "webkitmouseforcechanged")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/ariarowspan/index.md
--- title: "Element: ariaRowSpan property" short-title: ariaRowSpan slug: Web/API/Element/ariaRowSpan page-type: web-api-instance-property browser-compat: api.Element.ariaRowSpan --- {{DefaultAPISidebar("DOM")}} The **`ariaRowSpan`** property of the {{domxref("Element")}} interface reflects the value of the [`aria-rowspan`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowspan) attribute, which defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. ## Value A string which contains an integer. ## Examples In this example the `aria-rowspan` attribute on the element with an ID of `spanning-heading` is set to "3". Using `ariaRowSpan` we update the value to "2". ```html <table> <tr> <th id="spanning-heading" rowspan="3" aria-rowspan="3">Spanning heading</th> <th>Heading</th> </tr> <tr> <td>One</td> </tr> <tr> <td>Two</td> </tr> </table> ``` ```js let el = document.getElementById("spanning-heading"); console.log(el.ariaRowSpan); el.ariaRowSpan = "2"; console.log(el.ariaRowSpan); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ARIA: table role](/en-US/docs/Web/Accessibility/ARIA/Roles/table_role)
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/getattributenodens/index.md
--- title: "Element: getAttributeNodeNS() method" short-title: getAttributeNodeNS() slug: Web/API/Element/getAttributeNodeNS page-type: web-api-instance-method browser-compat: api.Element.getAttributeNodeNS --- {{ APIRef("DOM") }} The **`getAttributeNodeNS()`** method of the {{domxref("Element")}} interface returns the namespaced {{domxref("Attr")}} node of an element. This method is useful if you need the namespaced attribute's [instance properties](/en-US/docs/Web/API/Attr#instance_properties). If you only need the namespaced attribute's value, you can use the {{domxref("Element.getAttributeNS()", "getAttributeNS()")}} method instead. If you need the {{domxref("Attr")}} node of an element in HTML documents and the attribute is not namespaced, use the {{domxref("Element.getAttributeNode()", "getAttributeNode()")}} method instead. ## Syntax ```js-nolint getAttributeNodeNS(namespace, nodeName) ``` ### Parameters - `namespace` is a string specifying the namespace of the attribute. - `nodeName` is a string specifying the name of the attribute. ### Return value The node for specified attribute. ## Notes `getAttributeNodeNS` is more specific than [getAttributeNode](getAttributeNode) in that it allows you to specify attributes that are part of a particular namespace. The corresponding setter method is [setAttributeNodeNS](/en-US/docs/Web/API/Element/setAttributeNodeNS). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Document.createAttribute()")}} - {{domxref("Document.createAttributeNS()")}} - {{domxref("Element.setAttributeNodeNS()")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/ariaautocomplete/index.md
--- title: "Element: ariaAutoComplete property" short-title: ariaAutoComplete slug: Web/API/Element/ariaAutoComplete page-type: web-api-instance-property browser-compat: api.Element.ariaAutoComplete --- {{DefaultAPISidebar("DOM")}} The **`ariaAutoComplete`** property of the {{domxref("Element")}} interface reflects the value of the [`aria-autocomplete`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-autocomplete) attribute, which indicates whether inputting text could trigger display of one or more predictions of the user's intended value for a combobox, searchbox, or textbox and specifies how predictions would be presented if they were made. ## Value A string with one of the following values: - `"inline"` - : When a user is providing input, text suggesting one way to complete the provided input may be dynamically inserted after the caret. - `"list"` - : When a user is providing input, an element containing a collection of values that could complete the provided input may be displayed. - `"both"` - : When a user is providing input, an element containing a collection of values that could complete the provided input may be displayed. If displayed, one value in the collection is automatically selected, and the text needed to complete the automatically selected value appears after the caret in the input. - `"none"` - : When a user is providing input, there is no display of an automatic suggestion that attempts to predict how the user intends to complete the input. ## Examples In this example, the `aria-autocomplete` attribute on the element with an ID of `animal` is set to "`inline`". Using `ariaAutoComplete` we update the value to "`list`", which is the expected value for a combobox that invokes a `listbox` popup. ```html <div class="animals-combobox"> <label for="animal">Animal</label> <input id="animal" type="text" role="combobox" aria-autocomplete="inline" aria-controls="animals-listbox" aria-expanded="false" aria-haspopup="listbox" /> <ul id="animals-listbox" role="listbox" aria-label="Animals"> <li id="animal-cat" role="option">Cat</li> <li id="animal-dog" role="option">Dog</li> </ul> </div> ``` ```js let el = document.getElementById("animal"); console.log(el.ariaAutoComplete); // inline el.ariaAutoComplete = "list"; console.log(el.ariaAutoComplete); // list ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/scroll_event/index.md
--- title: "Element: scroll event" short-title: scroll slug: Web/API/Element/scroll_event page-type: web-api-event browser-compat: api.Element.scroll_event --- {{APIRef}} The **`scroll`** event fires when an element has been scrolled. To detect when scrolling has completed, see the {{domxref("Element/scrollend_event", "Element: scrollend event")}}. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("scroll", (event) => {}); onscroll = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples The following examples show how to use the `scroll` event with an event listener and with the `onscroll` event handler property. The {{DOMxRef("setTimeout()")}} method is used to throttle the event handler because `scroll` events can fire at a high rate. For additional examples that use {{DOMxRef("Window.requestAnimationFrame()", "requestAnimationFrame()")}}, see the {{domxref("Document/scroll_event", "Document: scroll event")}} page. ### Using `scroll` with an event listener The following example shows how to use the `scroll` event to detect when the user is scrolling inside an element: ```html <div id="scroll-box" style="overflow: scroll; height: 100px; width: 100px; float: left;"> <p style="height: 200px; width: 200px;">Scroll me!</p> </div> <p style="text-align: center;" id="output">Waiting on scroll events...</p> ``` ```js const element = document.querySelector("div#scroll-box"); const output = document.querySelector("p#output"); element.addEventListener("scroll", (event) => { output.innerHTML = "Scroll event fired!"; setTimeout(() => { output.innerHTML = "Waiting on scroll events..."; }, 1000); }); ``` {{EmbedLiveSample("Using_scroll_with_an_event_listener", "100%", 120)}} ### Using `onscroll` event handler property The following example shows how to use the `onscroll` event handler property to detect when the user is scrolling: ```html <div id="scroll-box" style="overflow: scroll; height: 100px; width: 100px; float: left;"> <p style="height: 200px; width: 200px;">Scroll me!</p> </div> <p id="output" style="text-align: center;">Waiting on scroll events...</p> ``` ```js const element = document.querySelector("div#scroll-box"); const output = document.querySelector("p#output"); element.onscroll = (event) => { output.innerHTML = "Element scroll event fired!"; setTimeout(() => { output.innerHTML = "Waiting on scroll events..."; }, 1000); }; ``` {{EmbedLiveSample("Using_onscroll_event_handler_property", "100%", 120)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Element `scrollend` event](/en-US/docs/Web/API/Element/scrollend_event) - [Document `scroll` event](/en-US/docs/Web/API/Document/scroll_event) - [Document `scrollend` event](/en-US/docs/Web/API/Document/scrollend_event)
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/ariahidden/index.md
--- title: "Element: ariaHidden property" short-title: ariaHidden slug: Web/API/Element/ariaHidden page-type: web-api-instance-property browser-compat: api.Element.ariaHidden --- {{DefaultAPISidebar("DOM")}} The **`ariaHidden`** property of the {{domxref("Element")}} interface reflects the value of the [`aria-hidden`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden)) attribute, which indicates whether the element is exposed to an accessibility API. ## Value A string with one of the following values: - `"true"` - : The element is hidden from the accessibility API. - `"false"` - : The element is exposed to the accessibility API as if it were rendered. - `undefined` - : The element's hidden state is determined by the user agent based on whether it is rendered. ## Examples In this example the [`aria-hidden`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden) attribute on the element with an ID of `hidden` is set to "true". Using `ariaHidden` we update the value to "false". ```html <div id="hidden" aria-hidden="true">Some things are better left unsaid.</div> ``` ```js let el = document.getElementById("hidden"); console.log(el.ariaHidden); // true el.ariaHidden = "false"; console.log(el.ariaHidden); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/beforescriptexecute_event/index.md
--- title: "Element: beforescriptexecute event" short-title: beforescriptexecute slug: Web/API/Element/beforescriptexecute_event page-type: web-api-event status: - non-standard browser-compat: api.Element.beforescriptexecute_event --- {{APIRef}}{{Non-standard_header}} > **Warning:** This event was a proposal in an early version of the specification. Do not rely on it. The **`beforescriptexecute`** event is fired when a script is about to be executed. Cancelling the event prevents the script from executing. It is a proprietary event specific to Gecko (Firefox). ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("NameOfTheEvent", (event) => {}); onNameOfTheEvent = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Specifications Not part of any specification. ## Browser compatibility {{Compat}} ## See also - [`afterscriptexecute`](/en-US/docs/Web/API/Element/afterscriptexecute_event) event
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/ariapressed/index.md
--- title: "Element: ariaPressed property" short-title: ariaPressed slug: Web/API/Element/ariaPressed page-type: web-api-instance-property browser-compat: api.Element.ariaPressed --- {{DefaultAPISidebar("DOM")}} The **`ariaPressed`** property of the {{domxref("Element")}} interface reflects the value of the [`aria-pressed`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed) attribute, which indicates the current "pressed" state of toggle buttons. > **Note:** Where possible use an HTML {{htmlelement("input")}} element with `type="button"` or the {{htmlelement("button")}} element as these have built in semantics and do not require ARIA attributes. ## Value A string with one of the following values: - `"true"` - : The element is pressed. - `"false"` - : The element supports being pressed but is not currently pressed. - `"mixed"` - : Indicates a mixed mode value for a tri-state toggle button. - `"undefined"` - : The element does not support being pressed. ## Examples In this example the `aria-pressed` attribute on the element with an ID of `saveChanges` is set to "false" indicating that this input is currently not pressed. Using `ariaPressed` we update the value to "true". ```html <div id="saveChanges" tabindex="0" role="button" aria-pressed="false">Save</div> ``` ```js let el = document.getElementById("saveChanges"); console.log(el.ariaPressed); // "false" el.ariaPressed = "true"; console.log(el.ariaPressed); // "true" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [ARIA: button role](/en-US/docs/Web/Accessibility/ARIA/Roles/button_role)
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/outerhtml/index.md
--- title: "Element: outerHTML property" short-title: outerHTML slug: Web/API/Element/outerHTML page-type: web-api-instance-property browser-compat: api.Element.outerHTML --- {{APIRef("DOM")}} The **`outerHTML`** attribute of the {{ domxref("Element") }} DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string. To only obtain the HTML representation of the contents of an element, or to replace the contents of an element, use the {{domxref("Element.innerHTML", "innerHTML")}} property instead. ## Value Reading the value of `outerHTML` returns a string containing an HTML serialization of the `element` and its descendants. Setting the value of `outerHTML` replaces the element and all of its descendants with a new DOM tree constructed by parsing the specified `htmlString`. ### Exceptions - `SyntaxError` {{domxref("DOMException")}} - : Thrown if an attempt was made to set `outerHTML` using an HTML string which is not valid. - `NoModificationAllowedError` {{domxref("DOMException")}} - : Thrown if an attempt was made to set `outerHTML` on an element which is a direct child of a {{domxref("Document")}}, such as {{domxref("Document.documentElement")}}. ## Examples ### Getting the value of an element's outerHTML property #### HTML ```html <div id="d"> <p>Content</p> <p>Further Elaborated</p> </div> ``` #### JavaScript ```js const d = document.getElementById("d"); console.log(d.outerHTML); // The string '<div id="d"><p>Content</p><p>Further Elaborated</p></div>' // is written to the console window ``` ### Replacing a node by setting the outerHTML property #### HTML ```html <div id="container"> <div id="d">This is a div.</div> </div> ``` #### JavaScript ```js const container = document.getElementById("container"); const d = document.getElementById("d"); console.log(container.firstElementChild.nodeName); // logs "DIV" d.outerHTML = "<p>This paragraph replaced the original div.</p>"; console.log(container.firstElementChild.nodeName); // logs "P" // The #d div is no longer part of the document tree, // the new paragraph replaced it. ``` ## Notes If the element has no parent node, setting its `outerHTML` property will not change it or its descendants. For example: ```js const div = document.createElement("div"); div.outerHTML = '<div class="test">test</div>'; console.log(div.outerHTML); // output: "<div></div>" ``` Also, while the element will be replaced in the document, the variable whose `outerHTML` property was set will still hold a reference to the original element: ```js const p = document.querySelector("p"); console.log(p.nodeName); // shows: "P" p.outerHTML = "<div>This div replaced a paragraph.</div>"; console.log(p.nodeName); // still "P"; ``` The returned value will contain HTML escaped attributes: ```js const anc = document.createElement("a"); anc.href = "https://developer.mozilla.org?a=b&c=d"; console.log(anc.outerHTML); // output: "<a href='https://developer.mozilla.org?a=b&amp;c=d'></a>" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Serializing DOM trees into XML strings: {{domxref("XMLSerializer")}} - Parsing XML or HTML into DOM trees: {{domxref("DOMParser")}} - {{domxref("HTMLElement.outerText")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/webkitmouseforceup_event/index.md
--- title: "Element: webkitmouseforceup event" short-title: webkitmouseforceup slug: Web/API/Element/webkitmouseforceup_event page-type: web-api-event status: - non-standard browser-compat: api.Element.webkitmouseforceup_event --- {{APIRef("Force Touch Events")}}{{Non-standard_header}} The non-standard **`webkitmouseforceup`** event is fired by Safari at an {{domxref("Element")}} some time after the {{domxref("Element/webkitmouseforcedown_event", "webkitmouseforcedown")}} event, when pressure on the button has been reduced sufficiently to end the "force click". **`webkitmouseforceup`** is a proprietary, WebKit-specific event. It is part of the {{domxref("Force Touch Events")}} feature. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("webkitmouseforceup", (event) => {}); onwebkitmouseforceup = (event) => {}; ``` ## Event type A {{domxref("MouseEvent")}}. Inherits from {{domxref("UIEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("MouseEvent")}} ## Event properties _This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}._ - {{domxref("MouseEvent.altKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>alt</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.button")}} {{ReadOnlyInline}} - : The button number that was pressed (if applicable) when the mouse event was fired. - {{domxref("MouseEvent.buttons")}} {{ReadOnlyInline}} - : The buttons being pressed (if any) when the mouse event was fired. - {{domxref("MouseEvent.clientX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.clientY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.ctrlKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>control</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.layerX")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the horizontal coordinate of the event relative to the current layer. - {{domxref("MouseEvent.layerY")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the vertical coordinate of the event relative to the current layer. - {{domxref("MouseEvent.metaKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>meta</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.movementX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.movementY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.offsetX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.offsetY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.pageX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.pageY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.relatedTarget")}} {{ReadOnlyInline}} - : The secondary target for the event, if there is one. - {{domxref("MouseEvent.screenX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.screenY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.shiftKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>shift</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The type of device that generated the event (one of the `MOZ_SOURCE_*` constants). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). - {{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The amount of pressure applied when clicking. - {{domxref("MouseEvent.x")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientX")}}. - {{domxref("MouseEvent.y")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientY")}}. ## Specifications _Not part of any specification._ Apple has [a description at the Mac Developer Library](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/SafariJSProgTopics/RespondingtoForceTouchEventsfromJavaScript.html). ## Browser compatibility {{Compat}} ## See also - [Introduction to events](/en-US/docs/Learn/JavaScript/Building_blocks/Events) - {{domxref("Element/webkitmouseforcewillbegin_event", "webkitmouseforcewillbegin")}} - {{domxref("Element/webkitmouseforcedown_event", "webkitmouseforcedown")}} - {{domxref("Element/webkitmouseforcechanged_event", "webkitmouseforcechanged")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/mouseenter_event/index.md
--- title: "Element: mouseenter event" short-title: mouseenter slug: Web/API/Element/mouseenter_event page-type: web-api-event browser-compat: api.Element.mouseenter_event --- {{APIRef}} The **`mouseenter`** event is fired at an {{domxref("Element")}} when a pointing device (usually a mouse) is initially moved so that its hotspot is within the element at which the event was fired. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("mouseenter", (event) => {}); onmouseenter = (event) => {}; ``` ## Event type A {{domxref("MouseEvent")}}. Inherits from {{domxref("UIEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("MouseEvent")}} ## Event properties _This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}._ - {{domxref("MouseEvent.altKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>alt</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.button")}} {{ReadOnlyInline}} - : The button number that was pressed (if applicable) when the mouse event was fired. - {{domxref("MouseEvent.buttons")}} {{ReadOnlyInline}} - : The buttons being pressed (if any) when the mouse event was fired. - {{domxref("MouseEvent.clientX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.clientY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.ctrlKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>control</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.layerX")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the horizontal coordinate of the event relative to the current layer. - {{domxref("MouseEvent.layerY")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the vertical coordinate of the event relative to the current layer. - {{domxref("MouseEvent.metaKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>meta</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.movementX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.movementY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.offsetX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.offsetY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.pageX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.pageY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.relatedTarget")}} {{ReadOnlyInline}} - : The secondary target for the event, if there is one. - {{domxref("MouseEvent.screenX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.screenY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.shiftKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>shift</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The type of device that generated the event (one of the `MOZ_SOURCE_*` constants). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). - {{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The amount of pressure applied when clicking. - {{domxref("MouseEvent.x")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientX")}}. - {{domxref("MouseEvent.y")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientY")}}. ## Usage notes Though similar to {{domxref("Element/mouseover_event", "mouseover")}}, `mouseenter` differs in that it doesn't [bubble](/en-US/docs/Web/API/Event/bubbles) and it isn't sent to any descendants when the pointer is moved from one of its descendants' physical space to its own physical space. ### Behavior of `mouseenter` events ![Mouseenter behavior diagram](mouseenter.png) One `mouseenter` event is sent to each element of the hierarchy when entering them. Here 4 events are sent to the four elements of the hierarchy when the pointer reaches the text. ### Behavior of `mouseover` events ![Mouseover behavior diagram](mouseover.png) A single `mouseover` event is sent to the deepest element of the DOM tree, then it bubbles up the hierarchy until it is canceled by a handler or reaches the root. With deep hierarchies, the number of `mouseover` events sent can be quite huge and cause significant performance problems. In such cases, it is better to listen for `mouseenter` events. Combined with the corresponding `mouseleave` (which is fired at the element when the mouse exits its content area), the `mouseenter` event acts in a very similar way to the CSS {{cssxref(':hover')}} pseudo-class. ## Examples The [`mouseover`](/en-US/docs/Web/API/Element/mouseover_event#examples) documentation has an example illustrating the difference between `mouseover` and `mouseenter`. ### mouseenter The following trivial example uses the `mouseenter` event to change the border on the `div` when the mouse enters the space allotted to it. It then adds an item to the list with the number of the `mouseenter` or `mouseleave` event. #### HTML ```html <div id="mouseTarget"> <ul id="unorderedList"> <li>No events yet!</li> </ul> </div> ``` #### CSS Styling the `div` to make it more visible. ```css #mouseTarget { box-sizing: border-box; width: 15rem; border: 1px solid #333; } ``` #### JavaScript ```js let enterEventCount = 0; let leaveEventCount = 0; const mouseTarget = document.getElementById("mouseTarget"); const unorderedList = document.getElementById("unorderedList"); mouseTarget.addEventListener("mouseenter", (e) => { mouseTarget.style.border = "5px dotted orange"; enterEventCount++; addListItem(`This is mouseenter event ${enterEventCount}.`); }); mouseTarget.addEventListener("mouseleave", (e) => { mouseTarget.style.border = "1px solid #333"; leaveEventCount++; addListItem(`This is mouseleave event ${leaveEventCount}.`); }); function addListItem(text) { // Create a new text node using the supplied text const newTextNode = document.createTextNode(text); // Create a new li element const newListItem = document.createElement("li"); // Add the text node to the li element newListItem.appendChild(newTextNode); // Add the newly created list item to list unorderedList.appendChild(newListItem); } ``` ### Result {{EmbedLiveSample('mouseenter')}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Introduction to events](/en-US/docs/Learn/JavaScript/Building_blocks/Events) - {{domxref("Element/mousedown_event", "mousedown")}} - {{domxref("Element/mouseup_event", "mouseup")}} - {{domxref("Element/mousemove_event", "mousemove")}} - {{domxref("Element/click_event", "click")}} - {{domxref("Element/dblclick_event", "dblclick")}} - {{domxref("Element/mouseover_event", "mouseover")}} - {{domxref("Element/mouseout_event", "mouseout")}} - {{domxref("Element/mouseenter_event", "mouseenter")}} - {{domxref("Element/mouseleave_event", "mouseleave")}} - {{domxref("Element/contextmenu_event", "contextmenu")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/webkitmouseforcedown_event/index.md
--- title: "Element: webkitmouseforcedown event" short-title: webkitmouseforcedown slug: Web/API/Element/webkitmouseforcedown_event page-type: web-api-event status: - non-standard browser-compat: api.Element.webkitmouseforcedown_event --- {{APIRef("Force Touch Events")}}{{Non-standard_header}} After a {{domxref("Element.mousedown_event", "mousedown")}} event has been fired at the element, if and when sufficient pressure has been applied to the mouse or trackpad button to qualify as a "force click," Safari begins sending **`webkitmouseforcedown`** events to the element. **`webkitmouseforcedown`** is a proprietary, WebKit-specific event. It is part of the {{domxref("Force Touch Events")}} feature. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("webkitmouseforcedown", (event) => {}); onwebkitmouseforcedown = (event) => {}; ``` ## Event type A {{domxref("MouseEvent")}}. Inherits from {{domxref("UIEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("MouseEvent")}} ## Event properties _This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}._ - {{domxref("MouseEvent.altKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>alt</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.button")}} {{ReadOnlyInline}} - : The button number that was pressed (if applicable) when the mouse event was fired. - {{domxref("MouseEvent.buttons")}} {{ReadOnlyInline}} - : The buttons being pressed (if any) when the mouse event was fired. - {{domxref("MouseEvent.clientX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.clientY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.ctrlKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>control</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.layerX")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the horizontal coordinate of the event relative to the current layer. - {{domxref("MouseEvent.layerY")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the vertical coordinate of the event relative to the current layer. - {{domxref("MouseEvent.metaKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>meta</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.movementX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.movementY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.offsetX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.offsetY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.pageX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.pageY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.relatedTarget")}} {{ReadOnlyInline}} - : The secondary target for the event, if there is one. - {{domxref("MouseEvent.screenX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.screenY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.shiftKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>shift</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The type of device that generated the event (one of the `MOZ_SOURCE_*` constants). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). - {{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The amount of pressure applied when clicking. - {{domxref("MouseEvent.x")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientX")}}. - {{domxref("MouseEvent.y")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientY")}}. ## Specifications _Not part of any specification._ Apple has [a description at the Mac Developer Library](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/SafariJSProgTopics/RespondingtoForceTouchEventsfromJavaScript.html). ## Browser compatibility {{Compat}} ## See also - [Introduction to events](/en-US/docs/Learn/JavaScript/Building_blocks/Events) - {{domxref("Element/webkitmouseforcewillbegin_event", "webkitmouseforcewillbegin")}} - {{domxref("Element/webkitmouseforceup_event", "webkitmouseforceup")}} - {{domxref("Element/webkitmouseforcechanged_event", "webkitmouseforcechanged")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/transitioncancel_event/index.md
--- title: "Element: transitioncancel event" short-title: transitioncancel slug: Web/API/Element/transitioncancel_event page-type: web-api-event browser-compat: api.Element.transitioncancel_event --- {{APIRef}} The **`transitioncancel`** event is fired when a [CSS transition](/en-US/docs/Web/CSS/CSS_transitions/Using_CSS_transitions) is canceled. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("transitioncancel", (event) => {}); ontransitioncancel = (event) => {}; ``` ## Event type A {{domxref("TransitionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("TransitionEvent")}} ## Event properties _Also inherits properties from its parent {{domxref("Event")}}_. - {{domxref("TransitionEvent.propertyName")}} {{ReadOnlyInline}} - : A string containing the name CSS property associated with the transition. - {{domxref("TransitionEvent.elapsedTime")}} {{ReadOnlyInline}} - : A `float` giving the amount of time the transition has been running, in seconds, when this event fired. This value is not affected by the {{cssxref("transition-delay")}} property. - {{domxref("TransitionEvent.pseudoElement")}} {{ReadOnlyInline}} - : A string, starting with `::`, containing the name of the [pseudo-element](/en-US/docs/Web/CSS/Pseudo-elements) the animation runs on. If the transition doesn't run on a pseudo-element but on the element, an empty string: `''`. ## Examples This code gets an element that has a transition defined and adds a listener to the `transitioncancel` event: ```js const transition = document.querySelector(".transition"); transition.addEventListener("transitioncancel", () => { console.log("Transition canceled"); }); ``` The same, but using the `ontransitioncancel` property instead of `addEventListener()`: ```js const transition = document.querySelector(".transition"); transition.ontransitioncancel = () => { console.log("Transition canceled"); }; ``` ### Live example In the following example, we have a simple {{htmlelement("div")}} element, styled with a transition that includes a delay: ```html <div class="transition"></div> <div class="message"></div> ``` ```css .transition { width: 100px; height: 100px; background: rgb(255 0 0 / 100%); transition-property: transform, background; transition-duration: 2s; transition-delay: 2s; } .transition:hover { transform: rotate(90deg); background: rgb(255 0 0 / 0%); } ``` To this, we'll add some JavaScript to indicate that the [`transitionstart`](/en-US/docs/Web/API/Element/transitionstart_event), [`transitionrun`](/en-US/docs/Web/API/Element/transitionrun_event), `transitioncancel`, and [`transitionend`](/en-US/docs/Web/API/Element/transitionend_event) events fire. In this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. For the transition end event to fire, stay hovered over the transition until the transition ends. ```js const message = document.querySelector(".message"); const el = document.querySelector(".transition"); el.addEventListener("transitionrun", () => { message.textContent = "transitionrun fired"; }); el.addEventListener("transitionstart", () => { message.textContent = "transitionstart fired"; }); el.addEventListener("transitioncancel", () => { message.textContent = "transitioncancel fired"; }); el.addEventListener("transitionend", () => { message.textContent = "transitionend fired"; }); ``` {{ EmbedLiveSample('Live_example', '100%', '150px') }} The `transitioncancel` event is fired if the transition is cancelled in either direction after the `transitionrun` event occurs and before the `transitionend` is fired. If there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. If the `transitioncancel` event is fired, the `transitionend` event will not fire. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("TransitionEvent")}} interface - CSS properties: {{cssxref("transition")}}, {{cssxref("transition-delay")}}, {{cssxref("transition-duration")}}, {{cssxref("transition-property")}}, {{cssxref("transition-timing-function")}} - Related events: {{domxref("Element/transitionrun_event", "transitionrun")}}, {{domxref("Element/transitionstart_event", "transitionstart")}}, {{domxref("Element/transitionend_event", "transitionend")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/animationiteration_event/index.md
--- title: "Element: animationiteration event" short-title: animationiteration slug: Web/API/Element/animationiteration_event page-type: web-api-event browser-compat: api.Element.animationiteration_event --- {{APIRef}} The **`animationiteration`** event is fired when an iteration of a [CSS Animation](/en-US/docs/Web/CSS/CSS_animations) ends, and another one begins. This event does not occur at the same time as the {{domxref("Element/animationend_event", "animationend")}} event, and therefore does not occur for animations with an `animation-iteration-count` of one. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("animationiteration", (event) => {}); onanimationiteration = (event) => {}; ``` ## Event type An {{domxref("AnimationEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("AnimationEvent")}} ## Event properties _Also inherits properties from its parent {{domxref("Event")}}_. - {{domxref("AnimationEvent.animationName")}} {{ReadOnlyInline}} - : A string containing the value of the {{cssxref("animation-name")}} that generated the animation. - {{domxref("AnimationEvent.elapsedTime")}} {{ReadOnlyInline}} - : A `float` giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an `animationstart` event, `elapsedTime` is `0.0` unless there was a negative value for {{cssxref("animation-delay")}}, in which case the event will be fired with `elapsedTime` containing `(-1 * delay)`. - {{domxref("AnimationEvent.pseudoElement")}} {{ReadOnlyInline}} - : A string, starting with `'::'`, containing the name of the [pseudo-element](/en-US/docs/Web/CSS/Pseudo-elements) the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: `''`. ## Examples This code uses `animationiteration` to keep track of the number of iterations an animation has completed: ```js const animated = document.querySelector(".animated"); let iterationCount = 0; animated.addEventListener("animationiteration", () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }); ``` The same, but using the `onanimationiteration` event handler property: ```js const animated = document.querySelector(".animated"); let iterationCount = 0; animated.onanimationiteration = () => { iterationCount++; console.log(`Animation iteration count: ${iterationCount}`); }; ``` ### Live example #### HTML ```html <div class="animation-example"> <div class="container"> <p class="animation">You chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">Activate animation</button> <div class="event-log"></div> </div> ``` #### CSS ```css .container { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: 0.2rem; padding: 0.2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { transform: translateX(100%) scaleX(3); } to { transform: translateX(0) scaleX(1); } } ``` #### JavaScript ```js const animation = document.querySelector("p.animation"); const animationEventLog = document.querySelector( ".animation-example>.event-log", ); const applyAnimation = document.querySelector( ".animation-example>button.activate", ); let iterationCount = 0; animation.addEventListener("animationstart", () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation started' `; }); animation.addEventListener("animationiteration", () => { iterationCount++; animationEventLog.textContent = `${animationEventLog.textContent}'animation iterations: ${iterationCount}' `; }); animation.addEventListener("animationend", () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation ended'`; animation.classList.remove("active"); applyAnimation.textContent = "Activate animation"; }); animation.addEventListener("animationcancel", () => { animationEventLog.textContent = `${animationEventLog.textContent}'animation canceled'`; }); applyAnimation.addEventListener("click", () => { animation.classList.toggle("active"); animationEventLog.textContent = ""; iterationCount = 0; const active = animation.classList.contains("active"); applyAnimation.textContent = active ? "Cancel animation" : "Activate animation"; }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '150px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [CSS Animations](/en-US/docs/Web/CSS/CSS_animations) - [Using CSS Animations](/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations) - {{domxref("AnimationEvent")}} - Related events: {{domxref("Element/animationstart_event", "animationstart")}}, {{domxref("Element/animationend_event", "animationend")}}, {{domxref("Element/animationcancel_event", "animationcancel")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/hasattributens/index.md
--- title: "Element: hasAttributeNS() method" short-title: hasAttributeNS() slug: Web/API/Element/hasAttributeNS page-type: web-api-instance-method browser-compat: api.Element.hasAttributeNS --- {{ APIRef("DOM") }} The **`hasAttributeNS()`** method of the {{domxref("Element")}} interface returns a boolean value indicating whether the current element has the specified attribute with the specified namespace. If you are working with HTML documents and you don't need to specify the requested attribute as being part of a specific namespace, use the {{domxref("Element.hasAttribute()", "hasAttribute()")}} method instead. ## Syntax ```js-nolint hasAttributeNS(namespace,localName) ``` ### Parameters - `namespace` is a string specifying the namespace of the attribute. - `localName` is the name of the attribute. ### Return value A boolean. ## Examples ```js // Check that the attribute exists before you set a value const d = document.getElementById("div1"); if ( d.hasAttributeNS("http://www.mozilla.org/ns/specialspace/", "special-align") ) { d.setAttribute("align", "center"); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element.getAttributeNS()")}} - {{domxref("Element.setAttributeNS()")}} - {{domxref("Element.removeAttributeNS()")}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/insertadjacentelement/index.md
--- title: "Element: insertAdjacentElement() method" short-title: insertAdjacentElement() slug: Web/API/Element/insertAdjacentElement page-type: web-api-instance-method browser-compat: api.Element.insertAdjacentElement --- {{APIRef("DOM")}} The **`insertAdjacentElement()`** method of the {{domxref("Element")}} interface inserts a given element node at a given position relative to the element it is invoked upon. ## Syntax ```js-nolint insertAdjacentElement(position, element) ``` ### Parameters - `position` - : A string representing the position relative to the `targetElement`; must match (case-insensitively) one of the following strings: - `'beforebegin'`: Before the `targetElement` itself. - `'afterbegin'`: Just inside the `targetElement`, before its first child. - `'beforeend'`: Just inside the `targetElement`, after its last child. - `'afterend'`: After the `targetElement` itself. - `element` - : The element to be inserted into the tree. ### Return value The element that was inserted, or `null`, if the insertion failed. ### Exceptions - `SyntaxError` {{domxref("DOMException")}} - : Thrown if the `position` specified is not a recognized value. - {{jsxref("TypeError")}} - : Thrown if the `element` specified is not a valid element. ### Visualization of position names ```html <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> ``` > **Note:** The `beforebegin` and > `afterend` positions work only if the node is in a tree and has an element > parent. ## Examples ```js beforeBtn.addEventListener("click", () => { const tempDiv = document.createElement("div"); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement("beforebegin", tempDiv); } setListener(tempDiv); }); afterBtn.addEventListener("click", () => { const tempDiv = document.createElement("div"); tempDiv.style.backgroundColor = randomColor(); if (activeElem) { activeElem.insertAdjacentElement("afterend", tempDiv); } setListener(tempDiv); }); ``` Have a look at our [insertAdjacentElement.html](https://mdn.github.io/dom-examples/insert-adjacent/insertAdjacentElement.html) demo on GitHub (see the [source code](https://github.com/mdn/dom-examples/blob/main/insert-adjacent/insertAdjacentElement.html) too.) Here, we have a sequence of {{htmlelement("div")}} elements inside a container. When one is clicked, it becomes selected and you can then press the _Insert before_ and _Insert after_ buttons to insert new divs before or after the selected element using `insertAdjacentElement()`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Element.insertAdjacentHTML()")}} - {{domxref("Element.insertAdjacentText()")}} - {{domxref("Node.insertBefore()")}} (similar to `beforebegin`, with different arguments) - {{domxref("Node.appendChild()")}} (same effect as `beforeend`)
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/ariavaluetext/index.md
--- title: "Element: ariaValueText property" short-title: ariaValueText slug: Web/API/Element/ariaValueText page-type: web-api-instance-property browser-compat: api.Element.ariaValueText --- {{DefaultAPISidebar("DOM")}} The **`ariaValueText`** property of the {{domxref("Element")}} interface reflects the value of the [`aria-valuetext`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) attribute, which defines the human-readable text alternative of aria-valuenow for a range widget. ## Value A string. ## Examples In this example the `aria-valuetext` attribute on the element with an ID of `slider` is set to "Sunday" to give a human-readable value for the range. Using `ariaValueText` we update the value to "Monday". ```html <div id="slider" role="slider" aria-valuenow="1" aria-valuemin="1" aria-valuemax="7" aria-valuetext="Sunday"></div> ``` ```js let el = document.getElementById("slider"); console.log(el.ariaValueText); // Sunday el.ariaValueText = "Monday"; console.log(el.ariaValueText); // Monday ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/matches/index.md
--- title: "Element: matches() method" short-title: matches() slug: Web/API/Element/matches page-type: web-api-instance-method browser-compat: api.Element.matches --- {{APIRef("DOM")}} The **`matches()`** method of the {{domxref("Element")}} interface tests whether the element would be selected by the specified [CSS selector](/en-US/docs/Learn/CSS/Building_blocks/Selectors). ## Syntax ```js-nolint matches(selectors) ``` ### Parameters - `selectors` - : A string containing valid [CSS selectors](/en-US/docs/Learn/CSS/Building_blocks/Selectors) to test the {{domxref("Element")}} against. ### Return value `true` if the {{domxref("Element")}} matches the `selectors`. Otherwise, `false`. ### Exceptions - `SyntaxError` {{domxref("DOMException")}} - : Thrown if `selectors` cannot be parsed as a CSS selector list. ## Examples ### HTML ```html <ul id="birds"> <li>Orange-winged parrot</li> <li class="endangered">Philippine eagle</li> <li>Great white pelican</li> </ul> ``` ### JavaScript ```js const birds = document.querySelectorAll("li"); for (const bird of birds) { if (bird.matches(".endangered")) { console.log(`The ${bird.textContent} is endangered!`); } } ``` This will log "The Philippine eagle is endangered!" to the console, since the element has indeed a `class` attribute with value `endangered`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [CSS selectors](/en-US/docs/Web/CSS/CSS_selectors) module - Other {{domxref("Element")}} methods that take selectors: {{domxref("Element.querySelector()")}}, {{domxref("Element.querySelectorAll()")}}, and {{domxref("element.closest()")}}.
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/classlist/index.md
--- title: "Element: classList property" short-title: classList slug: Web/API/Element/classList page-type: web-api-instance-property browser-compat: api.Element.classList --- {{APIRef("DOM")}} The **`Element.classList`** is a read-only property that returns a live {{domxref("DOMTokenList")}} collection of the `class` attributes of the element. This can then be used to manipulate the class list. Using `classList` is a convenient alternative to accessing an element's list of classes as a space-delimited string via {{domxref("element.className")}}. ## Value A {{domxref("DOMTokenList")}} representing the contents of the element's `class` attribute. If the `class` attribute is not set or empty, it returns an empty `DOMTokenList`, i.e. a `DOMTokenList` with the `length` property equal to `0`. Although the `classList` property itself is read-only, you can modify its associated `DOMTokenList` using the {{domxref("DOMTokenList/add", "add()")}}, {{domxref("DOMTokenList/remove", "remove()")}}, {{domxref("DOMTokenList/replace", "replace()")}}, and {{domxref("DOMTokenList/toggle", "toggle()")}} methods. You can test whether the element contains a given class using the {{domxref("DOMTokenList/contains", "classList.contains()")}} method. ## Examples ```js const div = document.createElement("div"); div.className = "foo"; // our starting state: <div class="foo"></div> console.log(div.outerHTML); // use the classList API to remove and add classes div.classList.remove("foo"); div.classList.add("anotherclass"); // <div class="anotherclass"></div> console.log(div.outerHTML); // if visible is set remove it, otherwise add it div.classList.toggle("visible"); // add/remove visible, depending on test conditional, i less than 10 div.classList.toggle("visible", i < 10); // false console.log(div.classList.contains("foo")); // add or remove multiple classes div.classList.add("foo", "bar", "baz"); div.classList.remove("foo", "bar", "baz"); // add or remove multiple classes using spread syntax const cls = ["foo", "bar"]; div.classList.add(...cls); div.classList.remove(...cls); // replace class "foo" with class "bar" div.classList.replace("foo", "bar"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("element.className")}} - {{domxref("DOMTokenList")}} - [`classList.js`](https://github.com/eligrey/classList.js) (a cross-browser JavaScript polyfill that fully implements `element.classList`)
0
data/mdn-content/files/en-us/web/api/element
data/mdn-content/files/en-us/web/api/element/dblclick_event/index.md
--- title: "Element: dblclick event" short-title: dblclick slug: Web/API/Element/dblclick_event page-type: web-api-event browser-compat: api.Element.dblclick_event --- {{APIRef}} The **`dblclick`** event fires when a pointing device button (such as a mouse's primary button) is double-clicked; that is, when it's rapidly clicked twice on a single element within a very short span of time. `dblclick` fires after two {{domxref("Element/click_event", "click")}} events (and by extension, after two pairs of {{domxref("Element.mousedown_event", "mousedown")}} and {{domxref("Element.mouseup_event", "mouseup")}} events). ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("dblclick", (event) => {}); ondblclick = (event) => {}; ``` ## Event type A {{domxref("MouseEvent")}}. Inherits from {{domxref("UIEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("MouseEvent")}} ## Event properties _This interface also inherits properties of its parents, {{domxref("UIEvent")}} and {{domxref("Event")}}._ - {{domxref("MouseEvent.altKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>alt</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.button")}} {{ReadOnlyInline}} - : The button number that was pressed (if applicable) when the mouse event was fired. - {{domxref("MouseEvent.buttons")}} {{ReadOnlyInline}} - : The buttons being pressed (if any) when the mouse event was fired. - {{domxref("MouseEvent.clientX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.clientY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [viewport coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#viewport). - {{domxref("MouseEvent.ctrlKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>control</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.layerX")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the horizontal coordinate of the event relative to the current layer. - {{domxref("MouseEvent.layerY")}} {{Non-standard_inline}} {{ReadOnlyInline}} - : Returns the vertical coordinate of the event relative to the current layer. - {{domxref("MouseEvent.metaKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>meta</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.movementX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.movementY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the last {{domxref("Element/mousemove_event", "mousemove")}} event. - {{domxref("MouseEvent.offsetX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.offsetY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node. - {{domxref("MouseEvent.pageX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.pageY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer relative to the whole document. - {{domxref("MouseEvent.relatedTarget")}} {{ReadOnlyInline}} - : The secondary target for the event, if there is one. - {{domxref("MouseEvent.screenX")}} {{ReadOnlyInline}} - : The X coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.screenY")}} {{ReadOnlyInline}} - : The Y coordinate of the mouse pointer in [screen coordinates](/en-US/docs/Web/CSS/CSSOM_view/Coordinate_systems#screen). - {{domxref("MouseEvent.shiftKey")}} {{ReadOnlyInline}} - : Returns `true` if the <kbd>shift</kbd> key was down when the mouse event was fired. - {{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The type of device that generated the event (one of the `MOZ_SOURCE_*` constants). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). - {{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{ReadOnlyInline}} - : The amount of pressure applied when clicking. - {{domxref("MouseEvent.x")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientX")}}. - {{domxref("MouseEvent.y")}} {{ReadOnlyInline}} - : Alias for {{domxref("MouseEvent.clientY")}}. ## Examples This example toggles the size of a card when you double click on it. ### JavaScript ```js const card = document.querySelector("aside"); card.addEventListener("dblclick", (e) => { card.classList.toggle("large"); }); ``` ### HTML ```html <aside> <h3>My Card</h3> <p>Double click to resize this object.</p> </aside> ``` ### CSS ```css aside { background: #fe9; border-radius: 1em; display: inline-block; padding: 1em; transform: scale(0.9); transform-origin: 0 0; transition: transform 0.6s; user-select: none; } .large { transform: scale(1.3); } ``` ### Result {{EmbedLiveSample("Examples", 700, 200)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Introduction to events](/en-US/docs/Learn/JavaScript/Building_blocks/Events) - {{domxref("Element/auxclick_event", "auxclick")}} - {{domxref("Element/click_event", "click")}} - {{domxref("Element/contextmenu_event", "contextmenu")}} - {{domxref("Element/mousedown_event", "mousedown")}} - {{domxref("Element/mouseup_event", "mouseup")}} - {{domxref("Element/pointerdown_event", "pointerdown")}} - {{domxref("Element/pointerup_event", "pointerup")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlobjectelement/index.md
--- title: HTMLObjectElement slug: Web/API/HTMLObjectElement page-type: web-api-interface browser-compat: api.HTMLObjectElement --- {{ APIRef("HTML DOM") }} The **`HTMLObjectElement`** interface provides special properties and methods (beyond those on the {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating the layout and presentation of {{HTMLElement("object")}} element, representing external resources. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLObjectElement.align")}} {{deprecated_inline}} - : A string representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`. - {{domxref("HTMLObjectElement.archive")}} {{deprecated_inline}} - : A string that reflects the [`archive`](/en-US/docs/Web/HTML/Element/object#archive) HTML attribute, containing a list of archives for resources for this object. - {{domxref("HTMLObjectElement.border")}} {{deprecated_inline}} - : A string that reflects the [`border`](/en-US/docs/Web/HTML/Element/object#border) HTML attribute, specifying the width of a border around the object. - {{domxref("HTMLObjectElement.code")}} {{deprecated_inline}} - : A string representing the name of an applet class file, containing either the applet's subclass, or the path to get to the class, including the class file itself. - {{domxref("HTMLObjectElement.codeBase")}} {{deprecated_inline}} - : A string that reflects the [`codebase`](/en-US/docs/Web/HTML/Element/object#codebase) HTML attribute, specifying the base path to use to resolve relative URIs. - {{domxref("HTMLObjectElement.codeType")}} {{deprecated_inline}} - : A string that reflects the [`codetype`](/en-US/docs/Web/HTML/Element/object#codetype) HTML attribute, specifying the content type of the data. - {{domxref("HTMLObjectElement.contentDocument")}} {{ReadOnlyInline}} - : Returns a {{domxref("Document")}} representing the active document of the object element's nested browsing context, if any; otherwise `null`. - {{domxref("HTMLObjectElement.contentWindow")}} {{ReadOnlyInline}} - : Returns a {{glossary("WindowProxy")}} representing the window proxy of the object element's nested browsing context, if any; otherwise `null`. - {{domxref("HTMLObjectElement.data")}} - : Returns a string that reflects the [`data`](/en-US/docs/Web/HTML/Element/object#data) HTML attribute, specifying the address of a resource's data. - {{domxref("HTMLObjectElement.declare")}} {{deprecated_inline}} - : A boolean value that reflects the [`declare`](/en-US/docs/Web/HTML/Element/object#declare) HTML attribute, indicating that this is a declaration, not an instantiation, of the object. - {{domxref("HTMLObjectElement.form")}} {{ReadOnlyInline}} - : Returns a {{domxref("HTMLFormElement")}} representing the object element's form owner, or null if there isn't one. - {{domxref("HTMLObjectElement.height")}} - : Returns a string that reflects the [`height`](/en-US/docs/Web/HTML/Element/object#height) HTML attribute, specifying the displayed height of the resource in CSS pixels. - {{domxref("HTMLObjectElement.hspace")}} {{deprecated_inline}} - : A `long` representing the horizontal space in pixels around the control. - {{domxref("HTMLObjectElement.name")}} - : Returns a string that reflects the [`name`](/en-US/docs/Web/HTML/Element/object#name) HTML attribute, specifying the name of the browsing context. - {{domxref("HTMLObjectElement.standby")}} {{deprecated_inline}} - : A string that reflects the [`standby`](/en-US/docs/Web/HTML/Element/object#standby) HTML attribute, specifying a message to display while the object loads. - {{domxref("HTMLObjectElement.type")}} - : A string that reflects the [`type`](/en-US/docs/Web/HTML/Element/object#type) HTML attribute, specifying the MIME type of the resource. - {{domxref("HTMLObjectElement.useMap")}} {{deprecated_inline}} - : A string that reflects the [`usemap`](/en-US/docs/Web/HTML/Element/object#usemap) HTML attribute, specifying a {{HTMLElement("map")}} element to use. - {{domxref("HTMLObjectElement.validationMessage")}} {{ReadOnlyInline}} - : Returns a string representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints. - {{domxref("HTMLObjectElement.validity")}} {{ReadOnlyInline}} - : Returns a {{domxref("ValidityState")}} with the validity states that this element is in. - {{domxref("HTMLObjectElement.vspace")}} {{deprecated_inline}} - : A `long` representing the horizontal space in pixels around the control. - {{domxref("HTMLObjectElement.width")}} - : A string that reflects the [`width`](/en-US/docs/Web/HTML/Element/object#width) HTML attribute, specifying the displayed width of the resource in CSS pixels. - {{domxref("HTMLObjectElement.willValidate")}} {{ReadOnlyInline}} - : Returns a boolean value that indicates whether the element is a candidate for constraint validation. Always `false` for `HTMLObjectElement` objects. ## Instance methods _Inherits methods from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLObjectElement.checkValidity()")}} - : Returns a boolean value that always is `true`, because `object` objects are never candidates for constraint validation. - {{domxref("HTMLObjectElement.setCustomValidity()")}} - : Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML element implementing this interface: {{HTMLElement("object")}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/checkvalidity/index.md
--- title: "HTMLObjectElement: checkValidity() method" short-title: checkValidity() slug: Web/API/HTMLObjectElement/checkValidity page-type: web-api-instance-method browser-compat: api.HTMLObjectElement.checkValidity --- {{APIRef("HTML DOM")}} The **`checkValidity()`** method of the {{domxref("HTMLObjectElement")}} interface returns a boolean value that always is true, because object objects are never candidates for constraint validation. ## Syntax ```js-nolint checkValidity() ``` ### Parameters None. ### Return value `true` ### Exceptions None. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/name/index.md
--- title: "HTMLObjectElement: name property" short-title: name slug: Web/API/HTMLObjectElement/name page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.name --- {{APIRef("HTML DOM")}} The **`name`** property of the {{domxref("HTMLObjectElement")}} interface returns a string that reflects the [`name`](/en-US/docs/Web/HTML/Element/object#name) HTML attribute, specifying the name of the browsing context. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/contentdocument/index.md
--- title: "HTMLObjectElement: contentDocument property" short-title: contentDocument slug: Web/API/HTMLObjectElement/contentDocument page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.contentDocument --- {{APIRef("HTML DOM")}} The **`contentDocument`** read-only property of the {{domxref("HTMLObjectElement")}} interface Returns a {{domxref("Document")}} representing the active document of the object element's nested browsing context, if any; otherwise null. ## Value A {{domxref('Document')}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/form/index.md
--- title: "HTMLObjectElement: form property" short-title: form slug: Web/API/HTMLObjectElement/form page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.form --- {{APIRef("HTML DOM")}} The **`form`** read-only property of the {{domxref("HTMLObjectElement")}} interface returns a {{domxref("HTMLFormElement")}} representing the object element's form owner, or null if there isn't one. ## Value A {{domxref('HTMLFormElement')}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/data/index.md
--- title: "HTMLObjectElement: data property" short-title: data slug: Web/API/HTMLObjectElement/data page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.data --- {{APIRef("HTML DOM")}} The **`data`** property of the {{domxref("HTMLObjectElement")}} interface returns a string that reflects the [`data`](/en-US/docs/Web/HTML/Element/object#data) HTML attribute, specifying the address of a resource's data. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/usemap/index.md
--- title: "HTMLObjectElement: useMap property" short-title: useMap slug: Web/API/HTMLObjectElement/useMap page-type: web-api-instance-property status: - deprecated browser-compat: api.HTMLObjectElement.useMap --- {{APIRef("HTML DOM")}}{{deprecated_header}} The **`useMap`** property of the {{domxref("HTMLObjectElement")}} interface returns a string that reflects the [`usemap`](/en-US/docs/Web/HTML/Element/object#usemap) HTML attribute, specifying a {{HTMLElement("map")}} element to use. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/setcustomvalidity/index.md
--- title: "HTMLObjectElement: setCustomValidity() method" short-title: setCustomValidity() slug: Web/API/HTMLObjectElement/setCustomValidity page-type: web-api-instance-method browser-compat: api.HTMLObjectElement.setCustomValidity --- {{APIRef("HTML DOM")}} The **`setCustomValidity()`** method of the {{domxref("HTMLObjectElement")}} interface sets a custom validity message for the element. ## Syntax ```js-nolint setCustomValidity(errorMessage) ``` ### Parameters - `errorMessage` - : The message to use for validity errors. ### Return value None ({{jsxref("undefined")}}). ### Exceptions None. ## Examples In this example, we pass the ID of an input element, and set different error messages depending on whether the value is missing, too low or too high. Additionally you _must_ call the [reportValidity](/en-US/docs/Web/API/HTMLFormElement/reportValidity) method on the same element or nothing will happen. ```js function validate(inputID) { const input = document.getElementById(inputID); const validityState = input.validity; if (validityState.valueMissing) { input.setCustomValidity("You gotta fill this out, yo!"); } else if (validityState.rangeUnderflow) { input.setCustomValidity("We need a higher number!"); } else if (validityState.rangeOverflow) { input.setCustomValidity("Thats too high!"); } else { input.setCustomValidity(""); } input.reportValidity(); } ``` It's vital to set the message to an empty string if there are no errors. As long as the error message is not empty, the form will not pass validation and will not be submitted. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref('validityState')}} - {{domxref('validityState.valueMissing')}} - {{domxref('validityState.typeMismatch')}} - {{domxref('validityState.patternMismatch')}} - {{domxref('validityState.tooLong')}} - {{domxref('validityState.tooShort')}} - {{domxref('validityState.rangeUnderflow')}} - {{domxref('validityState.rangeOverflow')}} - {{domxref('validityState.stepMismatch')}} - {{domxref('validityState.valid')}} - {{domxref('validityState.customError')}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/validity/index.md
--- title: "HTMLObjectElement: validity property" short-title: validity slug: Web/API/HTMLObjectElement/validity page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.validity --- {{APIRef("HTML DOM")}} The **`validity`** read-only property of the {{domxref("HTMLObjectElement")}} interface returns a {{domxref("ValidityState")}} with the validity states that this element is in. ## Value A {{domxref("ValidityState")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/width/index.md
--- title: "HTMLObjectElement: width property" short-title: width slug: Web/API/HTMLObjectElement/width page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.width --- {{APIRef("HTML DOM")}} The **`width`** property of the {{domxref("HTMLObjectElement")}} interface returns a string that reflects the [`width`](/en-US/docs/Web/HTML/Element/object#width) HTML attribute, specifying the displayed width of the resource in CSS pixels. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.width")}} - {{domxref("HTMLEmbedElement.width")}} - {{domxref("HTMLIFrameElement.width")}} - {{domxref("HTMLImageElement.width")}} - {{domxref("HTMLSourceElement.width")}} - {{domxref("HTMLVideoElement.width")}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/contentwindow/index.md
--- title: "HTMLObjectElement: contentWindow property" short-title: contentWindow slug: Web/API/HTMLObjectElement/contentWindow page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.contentWindow --- {{APIRef("HTML DOM")}} The **`contentWindow`** read-only property of the {{domxref("HTMLObjectElement")}} interface returns a {{glossary("WindowProxy")}} representing the window proxy of the object element's nested browsing context, if any; otherwise null. ## Value A {{domxref('Window')}}, or `null` if there are none. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/type/index.md
--- title: "HTMLObjectElement: type property" short-title: type slug: Web/API/HTMLObjectElement/type page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.type --- {{APIRef("HTML DOM")}} The **`type`** property of the {{domxref("HTMLObjectElement")}} interface returns a string that reflects the [`type`](/en-US/docs/Web/HTML/Element/object#type) HTML attribute, specifying the MIME type of the resource. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/height/index.md
--- title: "HTMLObjectElement: height property" short-title: height slug: Web/API/HTMLObjectElement/height page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.height --- {{APIRef("HTML DOM")}} The **`height`** property of the {{domxref("HTMLObjectElement")}} interface Returns a string that reflects the [`height`](/en-US/docs/Web/HTML/Element/object#height) HTML attribute, specifying the displayed height of the resource in CSS pixels. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.height")}} - {{domxref("HTMLEmbedElement.height")}} - {{domxref("HTMLIFrameElement.height")}} - {{domxref("HTMLImageElement.height")}} - {{domxref("HTMLSourceElement.height")}} - {{domxref("HTMLVideoElement.height")}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/validationmessage/index.md
--- title: "HTMLObjectElement: validationMessage property" short-title: validationMessage slug: Web/API/HTMLObjectElement/validationMessage page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.validationMessage --- {{APIRef("HTML DOM")}} The **`validationMessage`** read-only property of the {{domxref("HTMLObjectElement")}} interface returns a string representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlobjectelement
data/mdn-content/files/en-us/web/api/htmlobjectelement/willvalidate/index.md
--- title: "HTMLObjectElement: willValidate property" short-title: willValidate slug: Web/API/HTMLObjectElement/willValidate page-type: web-api-instance-property browser-compat: api.HTMLObjectElement.willValidate --- {{APIRef("HTML DOM")}} The **`willValidate`** read-only property of the {{domxref("HTMLObjectElement")}} interface returns a boolean value that indicates whether the element is a candidate for constraint validation. Always false for HTMLObjectElement objects. ## Value A boolean value. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/messageevent/index.md
--- title: MessageEvent slug: Web/API/MessageEvent page-type: web-api-interface browser-compat: api.MessageEvent --- {{APIRef("HTML DOM")}} The **`MessageEvent`** interface represents a message received by a target object. This is used to represent messages in: - [Server-sent events](/en-US/docs/Web/API/Server-sent_events) (see {{domxref("EventSource.message_event")}}). - [Web sockets](/en-US/docs/Web/API/WebSockets_API) (see the `onmessage` property of the [WebSocket](/en-US/docs/Web/API/WebSocket) interface). - Cross-document messaging (see {{domxref("Window.postMessage()")}} and {{domxref("Window.message_event")}}). - [Channel messaging](/en-US/docs/Web/API/Channel_Messaging_API) (see {{domxref("MessagePort.postMessage()")}} and {{domxref("MessagePort.message_event")}}). - Cross-worker/document messaging (see the above two entries, but also {{domxref("Worker.postMessage()")}}, {{domxref("Worker.message_event")}}, {{domxref("ServiceWorkerGlobalScope.message_event")}}, etc.) - [Broadcast channels](/en-US/docs/Web/API/Broadcast_Channel_API) (see {{domxref("BroadcastChannel.postMessage()")}}) and {{domxref("BroadcastChannel.message_event")}}). - WebRTC data channels (see {{domxref("RTCDataChannel.message_event", "onmessage")}}). The action triggered by this event is defined in a function set as the event handler for the relevant `message` event (e.g. using an `onmessage` handler as listed above). {{AvailableInWorkers}} {{InheritanceDiagram}} ## Constructor - {{domxref("MessageEvent.MessageEvent", "MessageEvent()")}} - : Creates a new `MessageEvent`. ## Instance properties _This interface also inherits properties from its parent, {{domxref("Event")}}._ - {{domxref("MessageEvent.data")}} {{ReadOnlyInline}} - : The data sent by the message emitter. - {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}} - : A string representing the origin of the message emitter. - {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}} - : A string representing a unique ID for the event. - {{domxref("MessageEvent.source")}} {{ReadOnlyInline}} - : A `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter. - {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}} - : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). ## Instance methods _This interface also inherits methods from its parent, {{domxref("Event")}}._ - {{domxref("MessageEvent.initMessageEvent","initMessageEvent()")}} {{deprecated_inline}} - : Initializes a message event. **Do not use this anymore** — **use the {{domxref("MessageEvent.MessageEvent", "MessageEvent()")}} constructor instead.** ## Examples In our [Basic shared worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker) ([run shared worker](https://mdn.github.io/dom-examples/web-workers/simple-shared-worker/)), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows. The following code snippet shows creation of a {{domxref("SharedWorker")}} object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Both scripts contain this: ```js const myWorker = new SharedWorker("worker.js"); ``` Both scripts then access the worker through a {{domxref("MessagePort")}} object created using the {{domxref("SharedWorker.port")}} property. If the onmessage event is attached using addEventListener, the port is manually started using its `start()` method: ```js myWorker.port.start(); ``` When the port is started, both scripts post messages to the worker and handle messages sent from it using `port.postMessage()` and `port.onmessage`, respectively: ```js first.onchange = () => { myWorker.port.postMessage([first.value, second.value]); console.log("Message posted to worker"); }; second.onchange = () => { myWorker.port.postMessage([first.value, second.value]); console.log("Message posted to worker"); }; myWorker.port.onmessage = (e) => { result1.textContent = e.data; console.log("Message received from worker"); }; ``` Inside the worker we use the {{domxref("SharedWorkerGlobalScope.connect_event", "onconnect")}} handler to connect to the same port discussed above. The ports associated with that worker are accessible in the {{domxref("SharedWorkerGlobalScope/connect_event", "connect")}} event's `ports` property — we then use {{domxref("MessagePort")}} `start()` method to start the port, and the `onmessage` handler to deal with messages sent from the main threads. ```js onconnect = (e) => { const port = e.ports[0]; port.addEventListener("message", (e) => { const workerResult = `Result: ${e.data[0] * e.data[1]}`; port.postMessage(workerResult); }); port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter. }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ExtendableMessageEvent")}} — similar to this interface but used in interfaces that needs to give more flexibility to authors.
0
data/mdn-content/files/en-us/web/api/messageevent
data/mdn-content/files/en-us/web/api/messageevent/origin/index.md
--- title: "MessageEvent: origin property" short-title: origin slug: Web/API/MessageEvent/origin page-type: web-api-instance-property browser-compat: api.MessageEvent.origin --- {{APIRef("HTML DOM")}} The **`origin`** read-only property of the {{domxref("MessageEvent")}} interface is a string representing the origin of the message emitter. ## Value A string representing the origin. ## Examples ```js myWorker.onmessage = (e) => { result.textContent = e.data; console.log("Message received from worker"); console.log(e.origin); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ExtendableMessageEvent")}} — similar to this interface but used in interfaces that needs to give more flexibility to authors.
0
data/mdn-content/files/en-us/web/api/messageevent
data/mdn-content/files/en-us/web/api/messageevent/source/index.md
--- title: "MessageEvent: source property" short-title: source slug: Web/API/MessageEvent/source page-type: web-api-instance-property browser-compat: api.MessageEvent.source --- {{APIRef("HTML DOM")}} The **`source`** read-only property of the {{domxref("MessageEvent")}} interface is a `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter. ## Value a `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter. ## Examples ```js myWorker.onmessage = (e) => { result.textContent = e.data; console.log("Message received from worker"); console.log(e.source); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ExtendableMessageEvent")}} — similar to this interface but used in interfaces that needs to give more flexibility to authors.
0
data/mdn-content/files/en-us/web/api/messageevent
data/mdn-content/files/en-us/web/api/messageevent/data/index.md
--- title: "MessageEvent: data property" short-title: data slug: Web/API/MessageEvent/data page-type: web-api-instance-property browser-compat: api.MessageEvent.data --- {{APIRef("HTML DOM")}} The **`data`** read-only property of the {{domxref("MessageEvent")}} interface represents the data sent by the message emitter. ## Value The data sent by the message emitter; this can be any data type, depending on what originated this event. ## Examples ```js myWorker.onmessage = (e) => { result.textContent = e.data; console.log("Message received from worker"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ExtendableMessageEvent")}} — similar to this interface but used in interfaces that needs to give more flexibility to authors.
0
data/mdn-content/files/en-us/web/api/messageevent
data/mdn-content/files/en-us/web/api/messageevent/messageevent/index.md
--- title: "MessageEvent: MessageEvent() constructor" short-title: MessageEvent() slug: Web/API/MessageEvent/MessageEvent page-type: web-api-constructor browser-compat: api.MessageEvent.MessageEvent --- {{APIRef("HTML DOM")}} The **`MessageEvent()`** constructor creates a new {{domxref("MessageEvent")}} object. ## Syntax ```js-nolint new MessageEvent(type) new MessageEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers always set it to `message`. - `options` {{optional_inline}} - : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties: - `data` {{optional_inline}} - : The data you want contained in the MessageEvent. This can be of any data type, and will default to `null` if not specified. - `origin` {{optional_inline}} - : A string representing the origin of the message emitter. This defaults to an empty string (`''`) if not specified. - `lastEventId` {{optional_inline}} - : A string representing a unique ID for the event. This defaults to an empty string ("") if not specified. - `source` {{optional_inline}} - : A `MessageEventSource` (which can be a {{domxref("Window")}}, a {{domxref("MessagePort")}}, or a {{domxref("ServiceWorker")}} object) representing the message emitter. This defaults to `null` if not set. - `ports` {{optional_inline}} - : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through where appropriate (E.g. in channel messaging or when sending a message to a shared worker). This defaults to an empty array (`[]`) if not specified. ## Return value A new {{domxref("MessageEvent")}} object. ## Examples ```js const myMessage = new MessageEvent("message", { data: "hello", }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ExtendableMessageEvent")}} — similar to this interface but used in interfaces that needs to give more flexibility to authors.
0
data/mdn-content/files/en-us/web/api/messageevent
data/mdn-content/files/en-us/web/api/messageevent/lasteventid/index.md
--- title: "MessageEvent: lastEventId property" short-title: lastEventId slug: Web/API/MessageEvent/lastEventId page-type: web-api-instance-property browser-compat: api.MessageEvent.lastEventId --- {{APIRef("HTML DOM")}} The **`lastEventId`** read-only property of the {{domxref("MessageEvent")}} interface is a string representing a unique ID for the event. ## Value A string representing the ID. ## Examples ```js myWorker.onmessage = (e) => { result.textContent = e.data; console.log("Message received from worker"); console.log(e.lastEventId); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ExtendableMessageEvent")}} — similar to this interface but used in interfaces that needs to give more flexibility to authors.
0
data/mdn-content/files/en-us/web/api/messageevent
data/mdn-content/files/en-us/web/api/messageevent/ports/index.md
--- title: "MessageEvent: ports property" short-title: ports slug: Web/API/MessageEvent/ports page-type: web-api-instance-property browser-compat: api.MessageEvent.ports --- {{APIRef("HTML DOM")}} The **`ports`** read-only property of the {{domxref("MessageEvent")}} interface is an array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). ## Value An array of {{domxref("MessagePort")}} objects. ## Examples ```js onconnect = (e) => { const port = e.ports[0]; port.addEventListener("message", (e) => { const workerResult = `Result: ${e.data[0] * e.data[1]}`; port.postMessage(workerResult); }); port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter. }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("ExtendableMessageEvent")}} — similar to this interface but used in interfaces that needs to give more flexibility to authors.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/identitycredential/index.md
--- title: IdentityCredential slug: Web/API/IdentityCredential page-type: web-api-interface status: - experimental browser-compat: api.IdentityCredential --- {{APIRef("FedCM API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`IdentityCredential`** interface of the [Federated Credential Management API (FedCM)](/en-US/docs/Web/API/FedCM_API) represents a user identity credential arising from a successful federated sign-in. A successful {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} call that includes an `identity` option fulfills with an `IdentityCredential` instance. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its ancestor, {{domxref("Credential")}}._ - {{domxref("IdentityCredential.isAutoSelected")}} {{ReadOnlyInline}} {{experimental_inline}} {{non-standard_inline}} - : A boolean value that indicates whether the federated sign-in was carried out using [auto-reauthentication](/en-US/docs/Web/API/FedCM_API/RP_sign-in#auto-reauthentication) (i.e. without user mediation) or not. - {{domxref("IdentityCredential.token")}} {{experimental_inline}} - : Returns the token used to validate the associated sign-in. ## Examples Relying parties (RPs) can call `navigator.credentials.get()` with the `identity` option to make a request for users to sign in to the RP via an identity provider (IdP), using identity federation. A typical request would look like this: ```js async function signIn() { const identityCredential = await navigator.credentials.get({ identity: { providers: [ { configURL: "https://accounts.idp.example/config.json", clientId: "********", nonce: "******", }, ], }, }); } ``` If successful, this call will fulfill with an `IdentityCredential` instance. From this, you could return the {{domxref("IdentityCredential.token")}} value, for example: ```js console.log(identityCredential.token); ``` Check out [Federated Credential Management API (FedCM)](/en-US/docs/Web/API/FedCM_API) for more details on how this works. This call will start off the sign-in flow described in [FedCM sign-in flow](/en-US/docs/Web/API/FedCM_API/RP_sign-in#fedcm_sign-in_flow). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Federated Credential Management API](https://developer.chrome.com/docs/privacy-sandbox/fedcm/)
0
data/mdn-content/files/en-us/web/api/identitycredential
data/mdn-content/files/en-us/web/api/identitycredential/token/index.md
--- title: "IdentityCredential: token property" short-title: token slug: Web/API/IdentityCredential/token page-type: web-api-instance-property status: - experimental browser-compat: api.IdentityCredential.token --- {{APIRef("FedCM API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`token`** read-only property of the {{domxref("IdentityCredential")}} interface returns the token used to validate the associated sign-in. The token includes user identity information that has been signed with the identity provider (IdP)'s {{glossary("digital certificate")}}. The relying party (RP) sends the token to its server to validate the certificate, and on success can use the (now trusted) identity information in the token to sign them into their service (starting a new session), sign them up to their service if they are a new user, etc. If the user has never signed into the IdP or is logged out, the associated {{domxref("CredentialsContainer.get", "get()")}} call rejects with an error and the RP can direct the user to the IdP login page to sign in or create an account. > **Note:** The exact structure and content of the validation token token is opaque to the FedCM API, and to the browser. The IdP decides on the syntax and usage of it, and the RP needs to follow the instructions provided by the IdP (see [Verify the Google ID token on your server side](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token), for example) to make sure they are using it correctly. ## Value A string. ## Examples Relying parties (RPs) can call `navigator.credentials.get()` with the `identity` option to make a request for users to sign in to the RP via an identity provider (IdP), using identity federation. A typical request would look like this: ```js async function signIn() { const identityCredential = await navigator.credentials.get({ identity: { providers: [ { configURL: "https://accounts.idp.example/config.json", clientId: "********", nonce: "******", }, ], }, }); console.log(identityCredential.token); } ``` A successful {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} call that includes an `identity` option fulfills with an `IdentityCredential` instance, which can be used to access the token used to validate the sign-in. Check out [Federated Credential Management API (FedCM)](/en-US/docs/Web/API/FedCM_API) for more details on how this works. This call will start off the sign-in flow described in [FedCM sign-in flow](/en-US/docs/Web/API/FedCM_API/RP_sign-in#fedcm_sign-in_flow). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Federated Credential Management API](https://developer.chrome.com/docs/privacy-sandbox/fedcm/)
0
data/mdn-content/files/en-us/web/api/identitycredential
data/mdn-content/files/en-us/web/api/identitycredential/isautoselected/index.md
--- title: "IdentityCredential: isAutoSelected property" short-title: isAutoSelected slug: Web/API/IdentityCredential/isAutoSelected page-type: web-api-instance-property status: - experimental - non-standard browser-compat: api.IdentityCredential.isAutoSelected --- {{securecontext_header}}{{APIRef("FedCM API")}}{{SeeCompatTable}}{{non-standard_header}} The **`isAutoSelected`** read-only property of the {{domxref("IdentityCredential")}} interface indicates whether the federated sign-in flow was carried out using [auto-reauthentication](/en-US/docs/Web/API/FedCM_API/RP_sign-in#auto-reauthentication) (i.e. without user mediation) or not. Automatic reauthentication can occur when a {{domxref("CredentialsContainer.get", "navigator.credentials.get()")}} call is issued with a [`mediation`](/en-US/docs/Web/API/CredentialsContainer/get#mediation) option value of `"optional"` or `"silent"`. It is useful for a relying party (RP) to know whether auto reauthentication occurred for analytics/performance evaluation and for UX purposes — automatic sign-in may warrant a different UI flow to non-automatic sign-in. ## Value A boolean value. `true` indicates that automatic reauthentication was used; `false` indicates that it was not. ## Examples RPs can call `navigator.credentials.get()` with the `identity` option to make a request for users to sign in to the RP via an identity provider (IdP), using identity federation. Auto-reauthentication behavior is controlled by the [`mediation`](/en-US/docs/Web/API/CredentialsContainer/get#mediation) option in the `get()` call: ```js async function signIn() { const identityCredential = await navigator.credentials.get({ identity: { providers: [ { configURL: "https://accounts.idp.example/config.json", clientId: "********", }, ], }, mediation: "optional", // this is the default }); // isAutoSelected is true if auto-reauthentication occurred. const isAutoSelected = identityCredential.isAutoSelected; } ``` Check out [Federated Credential Management API (FedCM)](/en-US/docs/Web/API/FedCM_API) for more details on how this works. This call will start off the sign-in flow described in [FedCM sign-in flow](/en-US/docs/Web/API/FedCM_API/RP_sign-in#fedcm_sign-in_flow). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Federated Credential Management API](https://developer.chrome.com/docs/privacy-sandbox/fedcm/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/geolocationposition/index.md
--- title: GeolocationPosition slug: Web/API/GeolocationPosition page-type: web-api-interface browser-compat: api.GeolocationPosition --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`GeolocationPosition`** interface represents the position of the concerned device at a given time. The position, represented by a {{domxref("GeolocationCoordinates")}} object, comprehends the 2D position of the device, on a spheroid representing the Earth, but also its altitude and its speed. ## Instance properties _The `GeolocationPosition` interface doesn't inherit any properties._ - {{domxref("GeolocationPosition.coords")}} {{ReadOnlyInline}} - : Returns a {{domxref("GeolocationCoordinates")}} object defining the current location. - {{domxref("GeolocationPosition.timestamp")}} {{ReadOnlyInline}} - : Returns a timestamp, given as {{Glossary("Unix time")}} in milliseconds, representing the time at which the location was retrieved. ## Instance methods _The `GeolocationPosition` interface neither implements, nor inherits any methods._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Geolocation API](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - {{domxref("Geolocation")}}
0
data/mdn-content/files/en-us/web/api/geolocationposition
data/mdn-content/files/en-us/web/api/geolocationposition/coords/index.md
--- title: "GeolocationPosition: coords property" short-title: coords slug: Web/API/GeolocationPosition/coords page-type: web-api-instance-property browser-compat: api.GeolocationPosition.coords --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`coords`** read-only property of the {{domxref("GeolocationPosition")}} interface returns a {{domxref("GeolocationCoordinates")}} object representing a geographic position. It contains the location, that is longitude and latitude on the Earth, the altitude, and the speed of the object concerned, regrouped inside the returned value. It also contains accuracy information about these values. ## Value A {{domxref("GeolocationCoordinates")}} object instance. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Geolocation API](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - {{domxref("GeolocationPosition")}}
0
data/mdn-content/files/en-us/web/api/geolocationposition
data/mdn-content/files/en-us/web/api/geolocationposition/timestamp/index.md
--- title: "GeolocationPosition: timestamp property" short-title: timestamp slug: Web/API/GeolocationPosition/timestamp page-type: web-api-instance-property browser-compat: api.GeolocationPosition.timestamp --- {{securecontext_header}}{{APIRef("Geolocation API")}} The **`timestamp`** read-only property of the {{domxref("GeolocationPosition")}} interface represents the date and time that the position was acquired by the device. ## Value A number containing a timestamp, given as {{Glossary("Unix time")}} in milliseconds. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Geolocation API](/en-US/docs/Web/API/Geolocation_API/Using_the_Geolocation_API) - {{domxref("GeolocationPosition")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/permissionstatus/index.md
--- title: PermissionStatus slug: Web/API/PermissionStatus page-type: web-api-interface browser-compat: api.PermissionStatus --- {{APIRef("Permissions API")}} {{AvailableInWorkers}} The **`PermissionStatus`** interface of the [Permissions API](/en-US/docs/Web/API/Permissions_API) provides the state of an object and an event handler for monitoring changes to said state. {{InheritanceDiagram}} ## Instance properties - {{domxref("PermissionStatus.name")}} {{ReadOnlyInline}} - : Returns the name of a requested permission, identical to the `name` passed to {{domxref("Permissions.query")}}. - {{domxref("PermissionStatus.state")}} {{ReadOnlyInline}} - : Returns the state of a requested permission; one of `'granted'`, `'denied'`, or `'prompt'`. - `PermissionStatus.status` {{ReadOnlyInline}} {{deprecated_inline}} - : Returns the state of a requested permission; one of `'granted'`, `'denied'`, or `'prompt'`. Later versions of the specification replace this with {{domxref("PermissionStatus.state")}}. ### Events - {{domxref("PermissionStatus.change_event", "change")}} - : Invoked upon changes to `PermissionStatus.state`, or the deprecated `PermissionStatus.status` in the case of older browsers. ## Example ```js navigator.permissions .query({ name: "geolocation" }) .then((permissionStatus) => { console.log(`geolocation permission status is ${permissionStatus.state}`); permissionStatus.onchange = () => { console.log( `geolocation permission status has changed to ${permissionStatus.state}`, ); }; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/permissionstatus
data/mdn-content/files/en-us/web/api/permissionstatus/name/index.md
--- title: "PermissionStatus: name property" short-title: name slug: Web/API/PermissionStatus/name page-type: web-api-instance-property browser-compat: api.PermissionStatus.name --- {{APIRef("Permissions API")}} The **`name`** read-only property of the {{domxref("PermissionStatus")}} interface returns the name of a requested permission. ## Value A read-only value that is identical to the `name` argument passed to {{domxref("Permissions.query", "navigator.permissions.query()")}}. ## Examples ```js function stateChangeListener() { console.log(`${this.name} permission status changed to ${this.state}`); } function queryAndTrackPermission(permissionName) { navigator.permissions .query({ name: permissionName }) .then((permissionStatus) => { console.log( `${permissionName} permission state is ${permissionStatus.state}`, ); permissionStatus.onchange = stateChangeListener; }); } queryAndTrackPermission("geolocation"); queryAndTrackPermission("midi"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/permissionstatus
data/mdn-content/files/en-us/web/api/permissionstatus/state/index.md
--- title: "PermissionStatus: state property" short-title: state slug: Web/API/PermissionStatus/state page-type: web-api-instance-property browser-compat: api.PermissionStatus.state --- {{APIRef("Permissions API")}} The **`state`** read-only property of the {{domxref("PermissionStatus")}} interface returns the state of a requested permission. This property returns one of `'granted'`, `'denied'`, or `'prompt'`. ## Value One of the following: - `'granted'` - `'denied'` - `'prompt'` ## Examples ```js navigator.permissions .query({ name: "geolocation" }) .then((permissionStatus) => { console.log(`geolocation permission state is ${permissionStatus.state}`); permissionStatus.onchange = () => { console.log( `geolocation permission status has changed to ${permissionStatus.state}`, ); }; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/permissionstatus
data/mdn-content/files/en-us/web/api/permissionstatus/change_event/index.md
--- title: "PermissionStatus: change event" short-title: change slug: Web/API/PermissionStatus/change_event page-type: web-api-event browser-compat: api.PermissionStatus.change_event --- {{APIRef("Permissions API")}} The **`change`** event of the {{domxref("PermissionStatus")}} interface fires whenever the {{domxref("PermissionStatus.state")}} property changes. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("change", (event) => {}); onchange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example ```js navigator.permissions .query({ name: "geolocation" }) .then((permissionStatus) => { console.log(`geolocation permission state is ${permissionStatus.state}`); permissionStatus.onchange = () => { console.log( `geolocation permission state has changed to ${permissionStatus.state}`, ); }; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/mediakeysystemaccess/index.md
--- title: MediaKeySystemAccess slug: Web/API/MediaKeySystemAccess page-type: web-api-interface browser-compat: api.MediaKeySystemAccess --- {{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}} The **`MediaKeySystemAccess`** interface of the [Encrypted Media Extensions API](/en-US/docs/Web/API/Encrypted_Media_Extensions_API) provides access to a Key System for decryption and/or a content protection provider. You can request an instance of this object using the {{domxref("Navigator.requestMediaKeySystemAccess","Navigator.requestMediaKeySystemAccess()")}} method. ## Instance properties - {{domxref("MediaKeySystemAccess.keySystem")}} {{ReadOnlyInline}} - : Returns a string identifying the key system being used. ## Instance methods - {{domxref("MediaKeySystemAccess.createMediaKeys()")}} - : Returns a {{jsxref('Promise')}} that resolves to a new {{domxref("MediaKeys")}} object. - {{domxref("MediaKeySystemAccess.getConfiguration()")}} - : Returns an object with the supported combination of configuration options. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mediakeysystemaccess
data/mdn-content/files/en-us/web/api/mediakeysystemaccess/createmediakeys/index.md
--- title: "MediaKeySystemAccess: createMediaKeys() method" short-title: createMediaKeys() slug: Web/API/MediaKeySystemAccess/createMediaKeys page-type: web-api-instance-method browser-compat: api.MediaKeySystemAccess.createMediaKeys --- {{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}} The `MediaKeySystemAccess.createMediaKeys()` method returns a {{jsxref('Promise')}} that resolves to a new {{domxref('MediaKeys')}} object. ## Syntax ```js-nolint createMediaKeys() ``` ### Parameters None. ### Return value A {{jsxref('Promise')}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mediakeysystemaccess
data/mdn-content/files/en-us/web/api/mediakeysystemaccess/getconfiguration/index.md
--- title: "MediaKeySystemAccess: getConfiguration() method" short-title: getConfiguration() slug: Web/API/MediaKeySystemAccess/getConfiguration page-type: web-api-instance-method browser-compat: api.MediaKeySystemAccess.getConfiguration --- {{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}} The `MediaKeySystemAccess.getConfiguration()` method returns an object with the supported combination of the following configuration options: - `initDataTypes` {{ReadOnlyInline}} - : Returns a list of supported initialization data type names. An initialization data type is a string indicating the format of the initialization data. - `audioCapabilities` {{ReadOnlyInline}} - : Returns a list of supported audio type and capability pairs. - `videoCapabilities` {{ReadOnlyInline}} - : Returns a list of supported video type and capability pairs. - `distinctiveIdentifier` {{ReadOnlyInline}} - : Indicates whether a persistent distinctive identifier is required. - `persistentState` {{ReadOnlyInline}} - : Indicates whether the ability to persist state is required. ## Syntax ```js-nolint getConfiguration() ``` ### Parameters None. ### Return value An object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mediakeysystemaccess
data/mdn-content/files/en-us/web/api/mediakeysystemaccess/keysystem/index.md
--- title: "MediaKeySystemAccess: keySystem property" short-title: keySystem slug: Web/API/MediaKeySystemAccess/keySystem page-type: web-api-instance-property browser-compat: api.MediaKeySystemAccess.keySystem --- {{APIRef("EncryptedMediaExtensions")}}{{SecureContext_Header}} The `MediaKeySystemAccess.keySystem` read-only property returns a string identifying the key system being used. ## Value A string. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/resizeobserversize/index.md
--- title: ResizeObserverSize slug: Web/API/ResizeObserverSize page-type: web-api-interface browser-compat: api.ResizeObserverSize --- {{DefaultAPISidebar("Resize Observer API")}} The **`ResizeObserverSize`** interface of the {{domxref('Resize Observer API')}} is used by the {{domxref("ResizeObserverEntry")}} interface to access the box sizing properties of the element being observed. > **Note:** In [multi-column layout](/en-US/docs/Web/CSS/CSS_multicol_layout), which is a fragmented context, the sizing returned by `ResizeObserverSize` will be the size of the first column. ## Instance properties - {{domxref("ResizeObserverSize.blockSize")}} {{ReadOnlyInline}} - : The length of the observed element's border box in the block dimension. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width. - {{domxref("ResizeObserverSize.inlineSize")}} {{ReadOnlyInline}} - : The length of the observed element's border box in the inline dimension. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height. > **Note:** For more explanation of writing modes and block and inline dimensions, read [Handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions). ## Examples In this example the {{domxref("ResizeObserverEntry.contentBoxSize")}} property returns a `ResizeObserverSize` object. This is an array containing the sizing information for the content box of the observed element. ```js const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { console.log(entry.contentBoxSize[0]); // a ResizeObserverSize } }); resizeObserver.observe(divElem); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/resizeobserversize
data/mdn-content/files/en-us/web/api/resizeobserversize/blocksize/index.md
--- title: "ResizeObserverSize: blockSize property" short-title: blockSize slug: Web/API/ResizeObserverSize/blockSize page-type: web-api-instance-property browser-compat: api.ResizeObserverSize.blockSize --- {{DefaultAPISidebar("Resize Observer API")}} The **`blockSize`** read-only property of the {{domxref("ResizeObserverSize")}} interface returns the length of the observed element's border box in the block dimension. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width. > **Note:** For more explanation of writing modes and block and inline dimensions, read [Handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions). ## Value A decimal representing the block size in pixels. ## Examples In this example we return an array of sizing information with {{domxref("ResizeObserverEntry.contentBoxSize")}}. The `blockSize` property returns the block dimension size of the observed element. ```js const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { const elemSize = entry.contentBoxSize[0]; console.log(elemSize.blockSize); // a decimal } }); resizeObserver.observe(divElem); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/resizeobserversize
data/mdn-content/files/en-us/web/api/resizeobserversize/inlinesize/index.md
--- title: "ResizeObserverSize: inlineSize property" short-title: inlineSize slug: Web/API/ResizeObserverSize/inlineSize page-type: web-api-instance-property browser-compat: api.ResizeObserverSize.inlineSize --- {{DefaultAPISidebar("Resize Observer API")}} The **`inlineSize`** read-only property of the {{domxref("ResizeObserverSize")}} interface returns the length of the observed element's border box in the inline dimension. For boxes with a horizontal {{cssxref("writing-mode")}}, this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height. > **Note:** For more explanation of writing modes and block and inline dimensions, read [Handling different text directions](/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions). ## Value A decimal representing the inline size in pixels. ## Examples In this example we return an array of sizing information with {{domxref("ResizeObserverEntry.contentBoxSize")}}. The `inlineSize` property returns the inline dimension size of the observed element. ```js const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { const elemSize = entry.contentBoxSize[0]; console.log(elemSize.inlineSize); // a decimal } }); resizeObserver.observe(divElem); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/highlightregistry/index.md
--- title: HighlightRegistry slug: Web/API/HighlightRegistry page-type: web-api-interface browser-compat: api.HighlightRegistry --- {{APIRef("CSS Custom Highlight API")}} The **`HighlightRegistry`** interface of the [CSS Custom Highlight API](/en-US/docs/Web/API/CSS_Custom_Highlight_API) is used to register {{domxref("Highlight")}} objects to be styled using the API. It is accessed via {{domxref("CSS.highlights_static", "CSS.highlights")}}. A `HighlightRegistry` instance is a [`Map`-like object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#map-like_browser_apis), in which each key is the name string for a custom highlight, and the corresponding value is the associated {{domxref("Highlight")}} object. {{InheritanceDiagram}} ## Instance properties _The `HighlightRegistry` interface doesn't inherit any properties._ - {{domxref("HighlightRegistry.size")}} {{ReadOnlyInline}} - : Returns the number of `Highlight` objects currently registered. ## Instance methods _The `HighlightRegistry` interface doesn't inherit any methods_. - {{domxref("HighlightRegistry.clear()")}} - : Remove all `Highlight` objects from the registry. - {{domxref("HighlightRegistry.delete()")}} - : Remove the named `Highlight` object from the registry. - {{domxref("HighlightRegistry.entries()")}} - : Returns a new iterator object that contains each `Highlight` object in the registry, in insertion order. - {{domxref("HighlightRegistry.forEach()")}} - : Calls the given callback once for each `Highlight` object in the registry, in insertion order. - {{domxref("HighlightRegistry.get()")}} - : Gets the named `Highlight` object from the registry. - {{domxref("HighlightRegistry.has()")}} - : Returns a boolean asserting whether a `Highlight` object is present the registry or not. - {{domxref("HighlightRegistry.keys()")}} - : An alias for {{domxref("HighlightRegistry.values()")}}. - {{domxref("HighlightRegistry.set()")}} - : Adds the given `Highlight` object to the registry with the given name, or updates the named `Highlight` object, if it already exists in the registry. - {{domxref("HighlightRegistry.values()")}} - : Returns a new iterator object that yields the `Highlight` objects in the registry, in insertion order. ## Examples ### Registering a highlight The following example demonstrates how to create ranges, instantiate a new `Highlight` object for them, and register the highlight using the `HighlightRegistry`, to style it on the page: #### HTML ```html <p id="foo">CSS Custom Highlight API</p> ``` #### CSS ```css ::highlight(my-custom-highlight) { background-color: peachpuff; } ``` #### JavaScript ```js const text = document.getElementById("foo").firstChild; if (!CSS.highlights) { text.textContent = "The CSS Custom Highlight API is not supported in this browser!"; } // Create a couple of ranges. const range1 = new Range(); range1.setStart(text, 0); range1.setEnd(text, 3); const range2 = new Range(); range2.setStart(text, 21); range2.setEnd(text, 24); // Create a custom highlight for these ranges. const highlight = new Highlight(range1, range2); // Register the ranges in the HighlightRegistry. CSS.highlights.set("my-custom-highlight", highlight); ``` #### Result {{ EmbedLiveSample("Registering a highlight") }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/get/index.md
--- title: "HighlightRegistry: get() method" short-title: get() slug: Web/API/HighlightRegistry/get page-type: web-api-instance-method browser-compat: api.HighlightRegistry.get spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.get --- {{APIRef("CSS Custom Highlight API")}} The **`get()`** method of the {{domxref("HighlightRegistry")}} interface returns the named {{domxref("Highlight")}} object from the registry. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.get()")}}. ## Syntax ```js-nolint get(name) ``` ### Parameters - `name` - : The name of the `Highlight` object to return from the registry. The name must be a {{jsxref("String")}}. ### Return value The `Highlight` object associated with the specified name, or {{jsxref("undefined")}} if the name can't be found in the `HighlightRegistry`. ## Examples The following code sample demonstrates how to create a new `Highlight`, add it to the registry, and retrieve it by its name using the `get()` method: ```js const fooHighlight = new Highlight(); CSS.highlights.set("foo", fooHighlight); console.log(CSS.highlights.get("foo")); // Returns the fooHighlight object. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/has/index.md
--- title: "HighlightRegistry: has() method" short-title: has() slug: Web/API/HighlightRegistry/has page-type: web-api-instance-method browser-compat: api.HighlightRegistry.has spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.has --- {{APIRef("CSS Custom Highlight API")}} The **`has()`** method of the {{domxref("HighlightRegistry")}} interface returns a boolean indicating whether or not a {{domxref("Highlight")}} object with the specified name exists in the registry. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.has()")}}. ## Syntax ```js-nolint has(name) ``` ### Parameters - `name` - : The name of the `Highlight` object to test for presence in the registry. ### Return value Returns `true` if a highlight with the specified name exists in the registry; otherwise `false`. ## Examples ```js const fooHighlight = new Highlight(); CSS.highlights.set("foo", fooHighlight); myHighlight.has("foo"); // true myHighlight.has("bar"); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/set/index.md
--- title: "HighlightRegistry: set() method" short-title: set() slug: Web/API/HighlightRegistry/set page-type: web-api-instance-method browser-compat: api.HighlightRegistry.set spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.set --- {{APIRef("CSS Custom Highlight API")}} The **`set()`** method of the {{domxref("HighlightRegistry")}} interface adds or updates a {{domxref("Highlight")}} object in the registry with the specified name. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.set()")}}. ## Syntax ```js-nolint set(name, highlight) ``` ### Parameters - `name` - : The name of the `Highlight` object to add or update. The name must be a {{jsxref("String")}}. - `highlight` - : The `Highlight` object to add or update. This must be a {{domxref("Highlight")}} interface instance. ### Return value The `HighlightRegistry` object. ## Examples ### Using set() ```js const fooHighlight = new Highlight(); CSS.highlights.set("foo", fooHighlight); ``` ### Using set() with chaining Since the `set()` method returns back the registry, you can chain the method call like below: ```js const fooHighlight = new Highlight(); const barHighlight = new Highlight(); const bazHighlight = new Highlight(); CSS.highlights .set("foo", fooHighlight) .set("bar", barHighlight) .set("baz", bazHighlight); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/keys/index.md
--- title: "HighlightRegistry: keys() method" short-title: keys() slug: Web/API/HighlightRegistry/keys page-type: web-api-instance-method browser-compat: api.HighlightRegistry.keys spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.keys --- {{APIRef("CSS Custom Highlight API")}} The **`keys()`** method of the {{domxref("HighlightRegistry")}} interface returns a new [Iterator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) object that contains the keys for each `Highlight` object in the `HighlightRegistry` object in insertion order. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.keys()")}}. ## Syntax ```js-nolint keys() ``` ### Return value A new iterator object containing the names of each `Highlight` object in the registry, in insertion order. ## Examples The following code snippet shows how to create and register three `Highlight` objects, and use the iterator returned by the `keys()` method to log their names: ```js const fooHighlight = new Highlight(); const barHighlight = new Highlight(); const bazHighlight = new Highlight(); CSS.highlights.set("foo", fooHighlight); CSS.highlights.set("bar", barHighlight); CSS.highlights.set("baz", bazHighlight); const iter = CSS.highlights.keys(); console.log(iter.next().value); // "foo" console.log(iter.next().value); // "bar" console.log(iter.next().value); // "baz" ``` The following code example shows how to iterate over the highlights in the registry by using a [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop: ```js const fooHighlight = new Highlight(); const barHighlight = new Highlight(); const bazHighlight = new Highlight(); CSS.highlights.set("foo", fooHighlight); CSS.highlights.set("bar", barHighlight); CSS.highlights.set("baz", bazHighlight); for (const name of CSS.highlights.keys()) { console.log(name); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/clear/index.md
--- title: "HighlightRegistry: clear() method" short-title: clear() slug: Web/API/HighlightRegistry/clear page-type: web-api-instance-method browser-compat: api.HighlightRegistry.clear spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.clear --- {{APIRef("CSS Custom Highlight API")}} The **`clear()`** method of the {{domxref("HighlightRegistry")}} interface removes all the {{domxref("Highlight")}} objects registered in the `HighlightRegistry`. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.clear()")}}. ## Syntax ```js-nolint clear() ``` ### Return value None ({{jsxref("undefined")}}). ## Examples The code snippet below registers two highlight objects in the registry and then clears the registry: ```js const customHighlight1 = new Highlight(range1, range2); const customHighlight2 = new Highlight(range3, range4, range5); CSS.highlights.set("custom-highlight-1", customHighlight1); CSS.highlights.set("custom-highlight-2", customHighlight2); console.log(CSS.highlights.size); // 2 CSS.highlights.clear(); console.log(CSS.highlights.size); // 0 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/size/index.md
--- title: "HighlightRegistry: size property" short-title: size slug: Web/API/HighlightRegistry/size page-type: web-api-instance-property browser-compat: api.HighlightRegistry.size spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-get-map.prototype.size --- {{APIRef("CSS Custom Highlight API")}} The **`size`** property returns the number of {{domxref("Highlight")}} objects in the {{domxref("HighlightRegistry")}}. ## Value A read-only integer indicating how many `Highlight` objects the registry contains. ## Examples ### Using size ```js const highlight1 = new Highlight(); const highlight2 = new Highlight(); CSS.highlights.set("highlight-1", highlight1); CSS.highlights.set("highlight-2", highlight2); console.log(CSS.highlights.size); // 2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/values/index.md
--- title: "HighlightRegistry: values() method" short-title: values() slug: Web/API/HighlightRegistry/values page-type: web-api-instance-method browser-compat: api.HighlightRegistry.values spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.values --- {{APIRef("CSS Custom Highlight API")}} The **`values()`** method of the {{domxref("HighlightRegistry")}} interface returns a new [Iterator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) object that contains the values for each `Highlight` object in the `HighlightRegistry` object in insertion order. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.values()")}}. ## Syntax ```js-nolint values() ``` ### Return value A new iterator object containing each `Highlight` object in the registry, in insertion order. ## Examples The following code snippet shows how to create and register three `Highlight` objects, and use the iterator returned by the `values()` method to log the highlights: ```js const fooHighlight = new Highlight(); const barHighlight = new Highlight(); const bazHighlight = new Highlight(); CSS.highlights.set("foo", fooHighlight); CSS.highlights.set("bar", barHighlight); CSS.highlights.set("baz", bazHighlight); const iter = CSS.highlights.values(); console.log(iter.next().value); // Highlight console.log(iter.next().value); // Highlight console.log(iter.next().value); // Highlight ``` The following code example shows how to iterate over the highlights in the registry by using a [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop: ```js const fooHighlight = new Highlight(); const barHighlight = new Highlight(); const bazHighlight = new Highlight(); CSS.highlights.set("foo", fooHighlight); CSS.highlights.set("bar", barHighlight); CSS.highlights.set("baz", bazHighlight); for (const highlight of CSS.highlights.values()) { console.log(highlight); // Highlight } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/delete/index.md
--- title: "HighlightRegistry: delete() method" short-title: delete() slug: Web/API/HighlightRegistry/delete page-type: web-api-instance-method browser-compat: api.HighlightRegistry.delete spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.delete --- {{APIRef("CSS Custom Highlight API")}} The **`delete()`** method of the {{domxref("HighlightRegistry")}} interface removes a the named {{domxref("Highlight")}} object from the `HighlightRegistry`. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.delete()")}}. ## Syntax ```js-nolint delete(customHighlightName) ``` ### Parameters - `customHighlightName` - : The name, as a {{jsxref("String")}}, of the {{domxref("Highlight")}} object to remove from the `HighlightRegistry`. ### Return value Returns `true` if a `Highlight` object under the provided name was in the `HighlightRegistry`; otherwise `false`. ## Examples The following code sample registers a highlight in the registry, and then deletes it: ```js const myHighlight = new Highlight(range1, range2); CSS.highlights.set("my-highlight", myHighlight); CSS.highlights.delete("foo"); // false CSS.highlights.delete("my-highlight"); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/foreach/index.md
--- title: "HighlightRegistry: forEach() method" short-title: forEach() slug: Web/API/HighlightRegistry/forEach page-type: web-api-instance-method browser-compat: api.HighlightRegistry.forEach spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.foreach --- {{APIRef("CSS Custom Highlight API")}} The **`forEach()`** method of the {{domxref("HighlightRegistry")}} interface executes a provided function once for each {{domxref("Highlight")}} object in the registry, in insertion order. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.forEach()")}}. ## Syntax ```js-nolint forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callback` - : Function to execute for each `Highlight` object, taking three arguments: - `highlight` - : The current highlight. - `name` - : The highlight name. - `registry` - : The registry object which `forEach()` was called upon. - `thisArg` - : Value to use as `this` when executing `callbackFn`. ### Return value None ({{jsxref("undefined")}}). ## Examples The code snippet below shows how create a new highlight with two ranges, and then log the ranges by using the `forEach()` method: ```js function logAllHighlights(highlight, name) { console.log(`Highlight ${name} exists in the registry`, highlight); } const customHighlight1 = new Highlight(); const customHighlight2 = new Highlight(); const customHighlight3 = new Highlight(); CSS.highlights.set("custom-highlight-1", customHighlight1); CSS.highlights.set("custom-highlight-2", customHighlight2); CSS.highlights.set("custom-highlight-3", customHighlight3); CSS.highlights.forEach(logAllHighlights); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api/highlightregistry
data/mdn-content/files/en-us/web/api/highlightregistry/entries/index.md
--- title: "HighlightRegistry: entries() method" short-title: entries() slug: Web/API/HighlightRegistry/entries page-type: web-api-instance-method browser-compat: api.HighlightRegistry.entries spec-urls: https://tc39.es/ecma262/multipage/keyed-collections.html#sec-map.prototype.entries --- {{APIRef("CSS Custom Highlight API")}} The **`entries()`** method of the {{domxref("HighlightRegistry")}} interface returns a new [Iterator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) object that contains the `[name, highlight]` pairs for each element in the `HighlightRegistry` object, in insertion order. `HighlightRegistry` is a {{jsxref("Map")}}-like object, so this is similar to using {{jsxref("Map.entries()")}}. ## Syntax ```js-nolint entries() ``` ### Return value A new iterator object that contains an array of `[name, highlight]` for each `Highlight` object in the `HighlightRegistry`, in insertion order. ## Examples The code snippet below creates and registers two new highlights, and then logs the highlights and their names by using the iterator returned by the `entries()` method: ```js const myHighlight1 = new Highlight(); const myHighlight2 = new Highlight(); CSS.highlights.set("first-highlight", myHighlight1); CSS.highlights.set("second-highlight", myHighlight2); const iter = CSS.highlights.entries(); console.log(iter.next().value); // ['first-highlight', Highlight] console.log(iter.next().value); // ['second-highlight', Highlight] ``` The following code example shows how to iterate over the highlights in the registry by using a [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop: ```js const myHighlight1 = new Highlight(); const myHighlight2 = new Highlight(); CSS.highlights.set("first-highlight", myHighlight1); CSS.highlights.set("second-highlight", myHighlight2); for (const [name, highlight] of CSS.highlights.entries()) { console.log(`Highlight ${name}`, highlight); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}} - [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlscriptelement/index.md
--- title: HTMLScriptElement slug: Web/API/HTMLScriptElement page-type: web-api-interface browser-compat: api.HTMLScriptElement --- {{APIRef("HTML DOM")}} HTML {{HTMLElement("script")}} elements expose the **`HTMLScriptElement`** interface, which provides special properties and methods for manipulating the behavior and execution of `<script>` elements (beyond the inherited {{domxref("HTMLElement")}} interface). JavaScript files should be served with the `text/javascript` [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types), but browsers are lenient and block them only if the script is served with an image type (`image/*`), video type (`video/*`), audio type (`audio/*`), or `text/csv`. If the script is blocked, its element receives an {{domxref("HTMLElement/error_event", "error")}} event; otherwise, it receives a {{domxref("Window/load_event", "load")}} event. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLScriptElement.type")}} - : A string representing the MIME type of the script. It reflects the [`type`](/en-US/docs/Web/HTML/Element/script#type) attribute. - {{domxref("HTMLScriptElement.src")}} - : A string representing the URL of an external script. It reflects the [`src`](/en-US/docs/Web/HTML/Element/script#src) attribute. - {{domxref("HTMLScriptElement.event")}} {{deprecated_inline}} - : A string; an obsolete way of registering event handlers on elements in an HTML document. - {{domxref("HTMLScriptElement.charset")}} {{deprecated_inline}} - : A string representing the character encoding of an external script. It reflects the [`charset`](/en-US/docs/Web/HTML/Element/script#charset) attribute. - {{domxref("HTMLScriptElement.async")}}, {{domxref("HTMLScriptElement.defer")}} - : The `async` and `defer` attributes are boolean attributes that control how the script should be executed. **The `defer` and `async` attributes must not be specified if the `src` attribute is absent.** There are three possible execution modes: 1. If the `async` attribute is present, then the script will be executed asynchronously as soon as it downloads. 2. If the `async` attribute is absent but the `defer` attribute is present, then the script is executed when [the page has finished parsing](/en-US/docs/Web/API/Document/DOMContentLoaded_event). 3. If neither attribute is present, then the script is fetched and executed immediately, blocking further parsing of the page. The `defer` attribute may be specified with the `async` attribute, so legacy browsers that only support `defer` (and not `async`) fall back to the `defer` behavior instead of the default blocking behavior. > **Note:** The exact processing details for these attributes are complex, involving many different aspects of HTML, and therefore are scattered throughout the specification. [These algorithms](https://html.spec.whatwg.org/multipage/scripting.html) describe the core ideas, but they rely on the parsing rules for {{HTMLElement("script")}} [start](https://html.spec.whatwg.org/multipage/syntax.html#start-tags) and [end](https://html.spec.whatwg.org/multipage/syntax.html#end-tags) tags in HTML, [in foreign content](https://html.spec.whatwg.org/multipage/syntax.html#foreign-elements), and [in XML](https://html.spec.whatwg.org/multipage/xhtml.html); the rules for the [`document.write()`](/en-US/docs/Web/API/Document/write) method; the handling of [scripting](https://html.spec.whatwg.org/multipage/webappapis.html); and so on. - {{domxref("HTMLScriptElement.crossOrigin")}} - : A string reflecting the [CORS setting](/en-US/docs/Web/HTML/Attributes/crossorigin) for the script element. For classic scripts from other [origins](/en-US/docs/Glossary/Origin), this controls if error information will be exposed. - {{domxref("HTMLScriptElement.text")}} - : A string that joins and returns the contents of all [`Text` nodes](/en-US/docs/Web/API/Text) inside the {{HTMLElement("script")}} element (ignoring other nodes like comments) in tree order. On setting, it acts the same way as the [`textContent`](/en-US/docs/Web/API/Node/textContent) IDL attribute. > **Note:** When inserted using the [`document.write()`](/en-US/docs/Web/API/Document/write) method, {{HTMLElement("script")}} elements execute (typically synchronously), but when inserted using [`innerHTML`](/en-US/docs/Web/API/Element/innerHTML) or [`outerHTML`](/en-US/docs/Web/API/Element/outerHTML), they do not execute at all. - {{domxref("HTMLScriptElement.fetchPriority")}} - : An optional string representing a hint given to the browser on how it should prioritize fetching of an external script relative to other external scripts. 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("HTMLScriptElement.noModule")}} - : A boolean value that if true, stops the script's execution in browsers that support [ES modules](/en-US/docs/Web/JavaScript/Guide/Modules) — used to run fallback scripts in older browsers that do _not_ support JavaScript modules. - {{domxref("HTMLScriptElement.referrerPolicy")}} - : A string that reflects the [`referrerPolicy`](/en-US/docs/Web/HTML/Element/script#referrerpolicy) HTML attribute indicating which referrer to use when fetching the script, and fetches done by that script. ## Static methods - {{domxref("HTMLScriptElement.supports_static", "HTMLScriptElement.supports()")}} - : Returns `true` if the browser supports scripts of the specified type and `false` otherwise. This method provides a simple and unified method for script-related feature detection. ## Instance methods _No specific methods; inherits methods from its parent, {{domxref("HTMLElement")}}._ ## Events _No specific events; inherits events from its parent, {{domxref("HTMLElement")}}._ ## Examples ### Dynamically importing scripts Let's create a function that imports new scripts within a document creating a {{HTMLElement("script")}} node _immediately before_ the {{HTMLElement("script")}} that hosts the following code (through {{domxref("document.currentScript")}}). These scripts will be **asynchronously** executed. For more details, see the [`defer`](#defer_property) and [`async`](#async_property) properties. ```js function loadError(oError) { throw new URIError(`The script ${oError.target.src} didn't load correctly.`); } function prefixScript(url, onloadFunction) { const newScript = document.createElement("script"); newScript.onerror = loadError; if (onloadFunction) { newScript.onload = onloadFunction; } document.currentScript.parentNode.insertBefore( newScript, document.currentScript, ); newScript.src = url; } ``` This next function, instead of prepending the new scripts immediately before the {{domxref("document.currentScript")}} element, appends them as children of the {{HTMLElement("head")}} tag. ```js function loadError(oError) { throw new URIError(`The script ${oError.target.src} didn't load correctly.`); } function affixScriptToHead(url, onloadFunction) { const newScript = document.createElement("script"); newScript.onerror = loadError; if (onloadFunction) { newScript.onload = onloadFunction; } document.head.appendChild(newScript); newScript.src = url; } ``` Sample usage: ```js affixScriptToHead("myScript1.js"); affixScriptToHead("myScript2.js", () => { alert('The script "myScript2.js" has been correctly loaded.'); }); ``` ### Checking if a script type is supported {{domxref("HTMLScriptElement.supports_static", "HTMLScriptElement.supports()")}} provides a unified mechanism for checking whether a browser supports particular types of scripts. The example below shows how to check for module support, using the existence of the `noModule` attribute as a fallback. ```js function checkModuleSupport() { if ("supports" in HTMLScriptElement) { return HTMLScriptElement.supports("module"); } return "noModule" in document.createElement("script"); } ``` Classic scripts are assumed to be supported on all browsers. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML {{HTMLElement("script")}} element - HTML {{HTMLElement("noscript")}} element - {{domxref("document.currentScript")}} - [Web Workers](/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) (code snippets similar to scripts but executed in [another global context](/en-US/docs/Web/API/DedicatedWorkerGlobalScope))
0
data/mdn-content/files/en-us/web/api/htmlscriptelement
data/mdn-content/files/en-us/web/api/htmlscriptelement/crossorigin/index.md
--- title: "HTMLScriptElement: crossOrigin property" short-title: crossOrigin slug: Web/API/HTMLScriptElement/crossOrigin page-type: web-api-instance-property browser-compat: api.HTMLScriptElement.crossOrigin --- {{APIRef("HTML DOM")}} The **`crossOrigin`** property of the {{domxref("HTMLScriptElement")}} interface reflects the {{Glossary("CORS", "Cross-Origin Resource Sharing")}} settings for the script element. For classic scripts from other [origins](/en-US/docs/Glossary/Origin), this controls if full error information will be exposed. For module scripts, it controls the script itself and any script it imports. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for details. ## Value A string of a keyword specifying the CORS mode to use when fetching the resource. Possible values are: - `anonymous` or an empty string (`""`) - : Requests sent by the {{domxref("HTMLScriptElement")}} will use the `cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `same-origin` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode. This means that CORS is enabled and credentials are sent _if_ the resource is fetched from the same origin from which the document was loaded. - `use-credentials` - : Requests sent by the {{domxref("HTMLScriptElement")}} will use the `cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `include` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode. All resources requests by the element will use CORS, regardless of which domain the fetch is from. If the `crossOrigin` property is specified with any other value, it is the same as specifing it as the `anonymous`. If the `crossOrigin` property is not specified, the resource is fetched without CORS (the `no-cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `same-origin` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLImageElement.crossOrigin")}} - {{domxref("HTMLLinkElement.crossOrigin")}} - {{domxref("HTMLMediaElement.crossOrigin")}}
0
README.md exists but content is empty.
Downloads last month
38