Search completed in 0.96 seconds.
CSS selectors - Learn web development
previous overview: building blocks next in css,
selectors are used to target the html elements on our web pages that we want to style. there are a wide variety of css
selectors available, allowing for fine-grained precision when selecting elements to style. in this article and its sub-articles we'll run through the different types in great detail, seeing how they work. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn how css
selectors work in detail. what is a
selector? you have met
selectors already. a css
selector is the first part of a css rule. it is a pattern of elements and...
...eps.) objective: to learn how css
selectors work in detail. what is a
selector? ...
...electors work in detail. what is a
selector? ...
...And 26 more matches
Element.querySelectorAll() - Web APIs
the element method query
selectorall() returns a static (not live) nodelist representing a list of elements matching the specified group of
selectors which are descendants of the element on which the method was called. note: this method is implemented based on the parentnode mixin's query
selectorall() method. syntax elementlist = parentnode.query
selectorall(
selectors); parameters
selectors a domstring containing one or more
selectors to match against. this string must be a valid css
selector string; if it's not, a syntaxerror exception is thrown. see locating dom elements using
selectors for more information about using
selectors to identify elements. multiple
selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must b...
...ich are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. ...
...tax must be escaped using a backslash character. since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. return value a non-live nodelist containing one element object for each descendant node that matches at least one of the specified
selectors. ...
...And 21 more matches
ParentNode.querySelectorAll() - Web APIs
the parentnode mixin defines the query
selectorall() method as returning a nodelist representing a list of elements matching the specified group of
selectors which are descendants of the object on which the method was called. if you need only a single result, consider the query
selector() method instead. note: this method is implemented as element.query
selectorall(), document.query
selectorall(), and documentfragment.query
selectorall() syntax elementlist = parentnode.query
selectorall(
selectors); parameters
selectors a domstring containing one or more
selectors to match against. this string must be a valid css
selector string; if it's not, a syntaxerror exception is thrown. see locating dom elements using
selectors for more information about using
selectors to identify elements. multiple ...
... note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. ...
...ich are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. ...
...And 14 more matches
Document.querySelectorAll() - Web APIs
the document method query
selectorall() returns a static (not live) nodelist representing a list of the document's elements that match the specified group of
selectors. note: this method is implemented based on the parentnode mixin's query
selectorall() method. syntax elementlist = parentnode.query
selectorall(
selectors); parameters
selectors a domstring containing one or more
selectors to match against. this string must be a valid css
selector string; if it's not, a syntaxerror exception is thrown. see locating dom elements using
selectors for more information about using
selectors to identify elements. multiple
selectors may be specified by separating them using commas. note: characters which are not part of standard css syntax must be escaped using a backslash character. since javas...
...cters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. ...
...sh character. since javascript also uses backslash escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. return value a non-live nodelist containing one element object for each element that matches at least one of the specified
selectors or an empty nodelist in case of no matches. note: if the specified
selectors include a css pseudo-element, the returned list is always empty. ...
...And 13 more matches
Type, class, and ID selectors - Learn web development
previous overview: building blocks next in this lesson we will take a look at the simplest
selectors that are available, which you will probably use the most in your work. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn about the different css
selectors we can use to apply css to a document. type
selectors a type
selector is sometimes referred to as a tag name
selector or element
selector, because it selects an html tag/element in your document. in the example below we have used the span, em and strong
selectors. all instances of <span>, <em> and <strong> elements are therefore ...
...tors a type
selector is sometimes referred to as a tag name
selector or element
selector, because it selects an html tag/element in your document. in the example below we have used the span, em and strong
selectors. all instances of <span>, <em> and <strong> elements are therefore styled accordingly. try adding a css rule to select the <h1> element and change its color to blue. the universal
selector the universal
selector is indicated by an asterisk (*) and selects everything in the document (or inside the parent element if it is being chained together with another element and a descendant combinator). in the following example we have used the universal
selector to remove the margins on all elements. this means that instead of the default styling added by the browser, which spaces out headi...
...he universal
selector to remove the margins on all elements. this means that instead of the default styling added by the browser, which spaces out headings and paragraphs with margins, everything is close together and we can't see the different paragraphs easily. this kind of behavior can sometimes be seen in "reset stylesheets", which strips out all of the browser styling. since the universal
selector makes global changes, we use it to deal with very specific situations such as the one outlined below. using the universal
selector to make your
selectors easier to read one use of the universal
selector is to make
selectors easier to read and more obvious in terms of what they are doing. for example, if i wanted to select the first child of any descendant element of <article> , no matter what e...
...And 11 more matches
Attribute selectors - Learn web development
previous overview: building blocks next as you know from your study of html, elements can have attributes that give further detail about the element being marked up. in css you can use attribute
selectors to target elements with certain attributes. this lesson will show you how to use these very useful
selectors. ...
... can use attribute
selectors to target elements with certain attributes. this lesson will show you how to use these very useful
selectors. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn what attribute
selectors are and how to use them. presence and value
selectors these
selectors enable the selection of an element based on the presence of an attribute alone (for example href), or on various different matches against the value of the attribute. ...
...ics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn what attribute
selectors are and how to use them. presence and value
selectors these
selectors enable the selection of an element based on the presence of an attribute alone (for example href), or on various different matches against the value of the attribute.
selector example description [attr] a[title] matches elements with an attr attribute (whose name is the value in square brackets). [attr=value] a[href="https://example.com"] matches elements with an attr attribute whose value is exactly value — the string inside the quotes. [attr~=value] p[class~="special"] matches elements with an attr a...
...And 9 more matches
QuerySelector - Archive of obsolete content
along the lines of other frameworks such as jquery or prototype, shortening the "query
selector" name can be convenient: function $ (
selector, el) { if (!el) {el = document;} return el.query
selector(
selector); } function $$ (
selector, el) { if (!el) {el = document;} return el.query
selectorall(
selector); // note: the returned object is a nodelist. ...
...be convenient: function $ (
selector, el) { if (!el) {el = document;} return el.query
selector(
selector); } function $$ (
selector, el) { if (!el) {el = document;} return el.query
selectorall(
selector); // note: the returned object is a nodelist. ...
...t: function $ (
selector, el) { if (!el) {el = document;} return el.query
selector(
selector); } function $$ (
selector, el) { if (!el) {el = document;} return el.query
selectorall(
selector); // note: the returned object is a nodelist. ...
...And 6 more matches
Document.querySelector() - Web APIs
the document method query
selector() returns the first element within the document that matches the specified
selector, or group of
selectors. if no matches are found, null is returned. note: the matching is done using depth-first pre-order traversal of the document's nodes starting with the first element in the document's markup and iterating through sequential nodes by order of the number of child nodes. syntax element = document.query
selector(
selectors); parameters
selectors a domstring containing one or more
selectors to match. this string must be a valid css
selector string; if it isn't, a syntax_err exception is thrown. see locating dom elements using
selectors for more about
selectors and how to manage them. note: characters that are not part of standard css syntax must be esc...
...te: characters that are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backslash escaping, be especially careful when writing string literals using these characters. see escaping special characters for more information. return value an htmlelement object representing the first element in the document that matches the specified set of css
selectors, or null is returned if there are no matches. if you need a list of all elements matching the specified
selectors, you should use query
selectorall() instead. exceptions syntax_err the syntax of the specified
selectors is invalid. usage notes if the specified
selector matches an id that is incorrectly used more than once in the document, the first element with that id is returned. css p...
... of all elements matching the specified
selectors, you should use query
selectorall() instead. exceptions syntax_err the syntax of the specified
selectors is invalid. usage notes if the specified
selector matches an id that is incorrectly used more than once in the document, the first element with that id is returned. css pseudo-elements will never return any elements, as specified in the
selectors api. escaping special characters to match against an id or
selectors that do not follow standard css syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\"). as the backslash is also an escape character in javascript, if you are entering a literal string, you must escape it twice (once for the javascript string, and another time for...
...And 6 more matches
DocumentFragment.querySelector() - Web APIs
the documentfragment.query
selector() method returns the first element, or null if no matches are found, within the documentfragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of
selectors. if the
selector matches an id and this id is erroneously used several times in the document, it returns the first matching element. if the
selectors specified in parameter are invalid a domexception with a syntax_err value is raised. syntax element = documentfragment.query
selector(
selectors); parameters
selectors is a domstring containing one or more css
selectors separated by commas. examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is returned: var el = documentfragment.querysele...
...documentfragment.query
selector(
selectors); parameters
selectors is a domstring containing one or more css
selectors separated by commas. examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is returned: var el = documentfragment.query
selector(".myclass"); css syntax and the method's argument the string argument pass to query
selector must follow the css syntax. ...
...rs
selectors is a domstring containing one or more css
selectors separated by commas. examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is returned: var el = documentfragment.query
selector(".myclass"); css syntax and the method's argument the string argument pass to query
selector must follow the css syntax. ...
...And 6 more matches
Test your skills: Selectors - Learn web development
give h2 headings a blue background and white text. cause text wrapped in a span to have a font-size of 200%. ...
... give h2 headings a blue background and white text. cause text wrapped in a span to have a font-size of 200%. ...
...nging the html, use css to do the following things: make h1 headings blue. give h2 headings a blue background and white text. cause text wrapped in a span to have a font-size of 200%. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
selectors two without changing the html, make the following changes to the look of the content in this example: give the element with an id of special a yellow background. give the element with a class of alert a 1px grey border. if the element with a class of alert also has a class of stop, make the background red. if the element with a class of alert also has a class of go, make the background gr...
...And 4 more matches
Element.querySelector() - Web APIs
the query
selector() method of the 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 element = baseelement.query
selector(
selectors); parameters
selectors a group of
selectors to match the descendant elements of the 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. ...
... 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 query
selector() method. ...
...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 query
selector() method. if no matches are found, the returned value is null. exceptions syntaxerror the specified
selectors are invalid. examples let's consider a few examples. ...
...And 4 more matches
ParentNode.querySelector() - Web APIs
the parentnode mixin defines the query
selector() method as returning an element representing the first element matching the specified group of
selectors which are descendants of the object on which the method was called. if you need all the elements matching the
selector list, use query
selectorall() instead. note: this method is implemented as document.query
selector(), documentfragment.query
selector() and element.query
selector(). syntax element = parentnode.query
selector(
selectors); parameters
selectors a domstring containing one or more
selectors to match against. this string must be a valid compound
selector list supported by the browser; if it's not, a syntaxerror exception is thrown. ...
... note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters. ...
... note: characters which are not part of standard css syntax must be escaped using a backslash character. since javascript also uses backspace escaping, special care must be taken when writing string literals using these characters. see escaping special characters for more information. ...
...And 3 more matches
CSS selectors - CSS: Cascading Style Sheets
css
selectors define the elements to which a set of css rules apply. note: there are no
selectors or combinators to select parent items, siblings of parents, or children of parent siblings. basic
selectors universal
selector selects all elements. optionally, it may be restricted to a specific namespace or to all namespaces. syntax: * ns|* *|* example: * will match all the elements of the document. type
selector selects all elements that have the given node name. syntax: elementname example: input will match any <input> element. class
selector selects all elements that have the given class attribute. syntax: .classname example: .index will match any element that has a class of "index". id
selector selects an element based on the value of its id attribute. there should be only o...
... element. class
selector selects all elements that have the given class attribute. syntax: .classname example: .index will match any element that has a class of "index". id
selector selects an element based on the value of its id attribute. there should be only one element with a given id in a document. syntax: #idname example: #toc will match the element that has the id "toc". attribute
selector selects all elements that have the given attribute. syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value] example: [autoplay] will match all elements that have the autoplay attribute set (to any value). grouping
selectors
selector list the , is a grouping method, it selects all the matching nodes. syntax: a, b example: div, span will match bo...
...tion of elements based on state information that is not contained in the document tree. example: a:visited will match all <a> elements that have been visited by the user. pseudo elements the :: pseudo represent entities that are not included in html. example: p::first-line will match the first line of all <p> elements. specifications specification status comment
selectors level 4 working draft added the || column combinator, grid structural
selectors, logical combinators, location, time-demensional, resource state, linguistic and ui pseudo-classes, modifier for ascii case-sensitive and case-insensitive attribute value selection.
selectors level 3 recommendation added the ~ general sibling combinator and tree-structural pseudo-classes. mad...
...And 2 more matches
Locating DOM elements using selectors - Web APIs
the
selectors api provides methods that make it quick and easy to retrieve element nodes from the dom by matching against a set of
selectors. this is much faster than past techniques, wherein it was necessary to, for example, use a loop in javascript code to locate the specific items you needed to find. the node
selector interface this specification adds two new methods to any objects implementing the document, documentfragment, or element interfaces: query
selector() returns the first matching element node within the node's subtree. if no matching node is found, null is returned. query
selectorall() returns a nodelist containing all matching element nodes within the node's subtree, or an empty nodelist if no matches are found. ...
...objects implementing the document, documentfragment, or element interfaces: query
selector() returns the first matching element node within the node's subtree. if no matching node is found, null is returned. query
selectorall() returns a nodelist containing all matching element nodes within the node's subtree, or an empty nodelist if no matches are found. note: the nodelist returned by query
selectorall() is not live, which means that changes in the dom are not reflected in the collection. this is different from other dom querying methods that return live node lists. ...
...l matching element nodes within the node's subtree, or an empty nodelist if no matches are found. note: the nodelist returned by query
selectorall() is not live, which means that changes in the dom are not reflected in the collection. this is different from other dom querying methods that return live node lists. you may find examples and details by reading the documentation for the element.query
selector() and element.query
selectorall() methods, as well as in the article code snippets for query
selector.
selectors the
selector methods accept one or more comma-separated
selectors to determine what element or elements should be returned. for example, to select all paragraph (p) elements in a document whose css class is either warning or note, you can do the following: var special = document.query...
...() and element.query
selectorall() methods, as well as in the article code snippets for query
selector.
selectors the
selector methods accept one or more comma-separated
selectors to determine what element or elements should be returned. for example, to select all paragraph (p) elements in a document whose css class is either warning or note, you can do the following: var special = document.query
selectorall( "p.warning, p.note" ); you can also query by id. for example: var el = document.query
selector( "#main, #basic, #exclamation" ); after executing the above code, el contains the first element in the document whose id is one of main, basic, or exclamation. you may use any css
selectors with the query
selector() and query
selectorall() methods. ...
Class selectors - CSS: Cascading Style Sheets
the css class
selector matches elements based on the contents of their class attribute. ...
...ss="spacious" */ .spacious { margin: 2em; } /* all <li> elements with class="spacious" */ li.spacious { margin: 2em; } /* all <li> elements with a class list that includes both "spacious" and "elegant" */ /* for example, class="elegant retro spacious" */ li.spacious.elegant { margin: 2em; } syntax .class_name { style properties } note that this is equivalent to the following attribute
selector: [class~=class_name] { style properties } examples css .red { color: #f33; } .yellow-bg { background: #ffa; } .fancy { font-weight: bold; text-shadow: 4px 4px 3px #77f; } html <p class="red">this paragraph has red text.</p> <p class="red yellow-bg">this paragraph has red text and a yellow background.</p> <p class="red fancy">this paragraph has red text and "fancy" styling.</p> <p...
... ...
...4px 4px 3px #77f; } html <p class="red">this paragraph has red text.</p> <p class="red yellow-bg">this paragraph has red text and a yellow background.</p> <p class="red fancy">this paragraph has red text and "fancy" styling.</p> <p>this is just a regular paragraph.</p> result specifications specification status comment
selectors level 4the definition of 'class
selectors' in that specification. working draft no changes
selectors level 3the definition of 'class
selectors' in that specification. recommendation css level 2 (revision 1)the definition of 'child
selectors' in that specification. recommendation css level 1the definition of 'child
selectors' in that specification. recommendation initial definition ...
Selector list - CSS: Cascading Style Sheets
the css
selector list (,) selects all the matching nodes. /* selects all matching elements */ span, div { border: red 2px solid; } to reduce the size of style sheets, one can group
selectors in comma-separated lists. syntax element, element, element { style properties } examples single line grouping grouping
selectors in a single line using a comma-separated lists. h1, h2, h3, h4, h5, h6 { font-family: helvetica; } multi line grouping grouping
selectors in a multiple lines using a comma-separated lists. ...
... can group
selectors in comma-separated lists. syntax element, element, element { style properties } examples single line grouping grouping
selectors in a single line using a comma-separated lists. h1, h2, h3, h4, h5, h6 { font-family: helvetica; } multi line grouping grouping
selectors in a multiple lines using a comma-separated lists. #main, .content, article { font-size: 1.1em; }
selector list invalidation a downside to using
selector lists is that the following aren't equivalent: h1 { font-family: sans-serif } h2:maybe-unsupported { font-family: sans-serif } h3 { font-family: sans-serif } h1, h2:maybe-unsupported, h3 { font-family: sans-serif } this is because a single unsupported
selector in a
selector list invalidates the whole rule. a way to remedy this us to use the :is(...
...ist invalidation a downside to using
selector lists is that the following aren't equivalent: h1 { font-family: sans-serif } h2:maybe-unsupported { font-family: sans-serif } h3 { font-family: sans-serif } h1, h2:maybe-unsupported, h3 { font-family: sans-serif } this is because a single unsupported
selector in a
selector list invalidates the whole rule. a way to remedy this us to use the :is()
selector, which simply ignores invalid
selectors in its arguments, but at the cost of all
selectors having the same specificity, because of how :is() calculates specificity. h1 { font-family: sans-serif } h2:maybe-unsupported { font-family: sans-serif } h3 { font-family: sans-serif } :is(h1, h2:maybe-unsupported, h3) { font-family: sans-serif } specifications specification status commen...
...ignores invalid
selectors in its arguments, but at the cost of all
selectors having the same specificity, because of how :is() calculates specificity. h1 { font-family: sans-serif } h2:maybe-unsupported { font-family: sans-serif } h3 { font-family: sans-serif } :is(h1, h2:maybe-unsupported, h3) { font-family: sans-serif } specifications specification status comment
selectors level 4the definition of '
selector lists' in that specification. working draft renamed to "
selector list" css level 1the definition of 'grouping' in that specification. recommendation initial definition ...
Universal selectors - CSS: Cascading Style Sheets
for instance, *.warning and .warning are equivalent. ...
...for instance, *.warning and .warning are equivalent. ...
... float: left } /* automatically clear the next sibling after a floating element */ .floating + * { clear: left; } html <p class="warning"> <span lang="en-us">a green span</span> in a red paragraph. </p> <p id="maincontent" lang="en-gb"> <span class="warning">a red span</span> in a green paragraph. ...
...ext sibling after a floating element */ .floating + * { clear: left; } html <p class="warning"> <span lang="en-us">a green span</span> in a red paragraph. </p> <p id="maincontent" lang="en-gb"> <span class="warning">a red span</span> in a green paragraph. </p> result specifications specification status comment
selectors level 4the definition of 'universal
selector' in that specification. working draft no changes
selectors level 3the definition of 'universal
selector' in that specification. recommendation defines behavior regarding namespaces and adds hint that omitting the
selector is allowed within pseudo-elements css level 2 (revision 1)the definition of 'universal
selector' in that specification. recommendation initia...
Comparison of CSS Selectors and XPath - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes this article seeks to document the difference between css
selectors and xpath for web developers to be able to better choose the right tool for the right job. ...
... xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes this article seeks to document the difference between css
selectors and xpath for web developers to be able to better choose the right tool for the right job. ...
...xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes this article seeks to document the difference between css
selectors and xpath for web developers to be able to better choose the right tool for the right job. ...
...e right job. ...
Attribute selectors - CSS: Cascading Style Sheets
/* <a> elements with a title attribute */ a[title] { color: purple; } /* <a> elements with an href matching "https://example.org" */ a[href="https://example.org"] { color: green; } /* <a> elements with an href containing "example" */ a[href*="example"] { font-size: 2em; } /* <a> elements with an href ending ".org" */ a[href$=".org"] { font-style: italic; } /* <a> elements whose class attribute contains the word "logo" */ a[class~="logo"] { padding: 2px; } syntax [attr] represents elements with an attribute name of attr. [attr=value] represents elements with an attribute name of attr whose value is exactly value. ...
... css /* list types require the case sensitive flag due to a quirk in how html treats the type attribute. */ ol[type="a"] { list-style-type: lower-alpha; background: red; } ol[type="a" s] { list-style-type: lower-alpha; background: lime; } ol[type="a" s] { list-style-type: upper-alpha; b...
...to a quirk in how html treats the type attribute. */ ol[type="a"] { list-style-type: lower-alpha; background: red; } ol[type="a" s] { list-style-type: lower-alpha; background: lime; } ol[type="a" s] { list-style-type: upper-alpha; background: lime; } html <ol type="a"> <li>example list</li> </ol> result specifications specification status comment
selectors level 4the definition of 'attribute
selectors' in that specification. working draft adds modifier for ascii case-sensitive and case-insensitive attribute value selection.
selectors level 3the definition of 'attribute
selectors' in that specification. recommendation css level 2 (revision 1)the definition of 'attribute
selectors' in that specification. recommendat...
Privacy and the :visited selector - CSS: Cascading Style Sheets
before about 2010, the css :visited
selector allowed websites to uncover a user's browsing history and figure out what sites the user had visited. this was done through window.getcomputedstyle and other techniques. this process was quick to execute, and made it possible not only to determine where the user had been on the web, but could also be used to guess a lot of information about the user's identity. to mitigate this problem, browsers have limited the amount of information that can be obtained from visited links. ...
...lso be used to guess a lot of information about the user's identity. to mitigate this problem, browsers have limited the amount of information that can be obtained from visited links. little white lies to preserve users' privacy, firefox and other browsers will lie to web applications under certain circumstances: the window.getcomputedstyle method, and similar functions such as element.query
selector, will always return values indicating that a user has never visited any of the links on a page. if you use a sibling
selector such as :visited + span, the adjacent element (span in this example) will be styled as if the link were unvisited. in rare scenarios, if you're using nested link elements and the element being matched is different from the link whose presence in history is being tested, ...
... ...
xChannelSelector - SVG: Scalable Vector Graphics
the xchannel
selector attribute indicates which color channel from in2 to use to displace the pixels in in along the x-axis. ...
...is using this attribute: <fedisplacementmap> html, body, svg { height: 100%; } <svg viewbox="0 0 440 160" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feimage xlink:href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0" width="100%" height="100%" result="abc"/> <fedisplacementmap in2="abc" in="sourcegraphic" scale="30" xchannel
selector="r"/> </filter> <filter id="displacementfilter2"> <feimage xlink:href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0" width="100%" height="100%" result="abc"/> <fedisplacementmap in2="abc" in="sourcegraphic" scale="30" xchannel
selector="b"/> </filter> <text x="10" y="60" font-size="50" filter="url(#displacementfilter)">some displaced text</tex...
...ned in in2 will be used to displace the pixels of the input image defined in in along the x-axis. a this keyword specifies that the alpha channel of the input image defined in in2 will be used to displace the pixels of the input image defined in in along the x-axis. specifications specification status comment filter effects module level 1the definition of 'xchannel
selector' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'xchannel
selector' in that specification. recommendation initial definition ...
yChannelSelector - SVG: Scalable Vector Graphics
the ychannel
selector attribute indicates which color channel from in2 to use to displace the pixels in in along the y-axis. ...
...is using this attribute: <fedisplacementmap> html, body, svg { height: 100%; } <svg viewbox="0 0 440 160" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feimage xlink:href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0" width="100%" height="100%" result="abc"/> <fedisplacementmap in2="abc" in="sourcegraphic" scale="30" ychannel
selector="r"/> </filter> <filter id="displacementfilter2"> <feimage xlink:href="https://mdn.mozillademos.org/files/12668/mdn.svg" x="0" y="0" width="100%" height="100%" result="abc"/> <fedisplacementmap in2="abc" in="sourcegraphic" scale="30" ychannel
selector="b"/> </filter> <text x="10" y="60" font-size="50" filter="url(#displacementfilter)">some displaced text</tex...
...ned in in2 will be used to displace the pixels of the input image defined in in along the y-axis. a this keyword specifies that the alpha channel of the input image defined in in2 will be used to displace the pixels of the input image defined in in along the y-axis. specifications specification status comment filter effects module level 1the definition of 'ychannel
selector' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'ychannel
selector' in that specification. recommendation initial definition ...
CSSStyleRule.selectorText - Web APIs
the cssrule.
selectortext property gets the textual representation of the
selector for the rule set. this is readonly in some browsers; to set stylesheet rules dynamically cross-browser, see using dynamic styling information. syntax string = cssrule.
selectortext example // for cssrule: body { background-color: darkblue; } var stylesheet = document.stylesheets[0]; alert(stylesheet.cssrules[0].
selectortext); // body notes the implementation may have stripped out insignificant whitespace while parsing the
selector. if set to a
selector string which cannot be parsed, a syntaxerror is thrown. specifications specification status comment css object model (cssom)the definition of 'cssstylerule.
selectortext' in that specification. working draft browser ...
... draft browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. ...
DocumentFragment.querySelectorAll() - Web APIs
the documentfragment.query
selectorall() method returns a nodelist of elements within the documentfragment (using depth-first pre-order traversal of the document's nodes) that matches the specified group of
selectors. if the
selectors specified in parameter are invalid a domexception with a syntax_err value is raised. note: the definition of this api was moved to the parentnode interface. syntax elementlist = documentfragment.query
selectorall(
selectors); parameters
selectors is a domstring containing one or more css
selectors separated by commas. ...
...: the definition of this api was moved to the parentnode interface. syntax elementlist = documentfragment.query
selectorall(
selectors); parameters
selectors is a domstring containing one or more css
selectors separated by commas. examples this example returns a list of all div elements within the documentfragment with a class of either "note" or "alert": var matches = documentfrag.query
selectorall("div.note, div.alert"); specifications specification status comment
selectors api level 1the definition of 'documentfragment.query
selectorall' in that specification. obsolete initial definition. ...
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
ints at a specific piece of a document, it can be difficult for the user to notice. find out how you can use some simple css to draw attention to the target of a url and improve the user's experience. picking a target the pseudo-class :target is used to style the target element of a url containing a fragment identifier. for example, the url http://developer.mozilla.org/en/docs/using_the_:target_
selector#example contains the fragment identifier #example. in html, identifiers are found as the values of either id or name attributes, since the two share the same namespace. thus, the example url would point to the heading "example" in this document. suppose you wish to style any h2 element that is the target of a url, but do not want any other kind of element to get a target style. this is simple en...
... possible to create styles that are specific to a particular fragment of the document. this is done using the same identifying value that is found in the uri. thus, to add a border to the #example fragment, we would write: #example:target { border: 1px solid black; } targeting all elements if the intent is to create a "blanket" style that will apply to all targeted elements, then the universal
selector comes in handy: :target { color: red; } example in the following example, there are five links that point to elements in the same document. selecting the "first" link, for example, will cause <h1 id="one"> to become the target element. note that the document may jump to a new scroll position, since target elements are placed on the top of the browser window if possible. <h4 id="one">...</h4...
ID selectors - CSS: Cascading Style Sheets
the css id
selector matches an element based on the value of the element’s id attribute. in order for the element to be selected, its id attribute must match exactly the value given in the
selector. /* the element with id="demo" */ #demo { border: red 2px solid; } syntax #id_value { style properties } note that syntactically (but not specificity-wise), this is equivalent to the following attribute
selector: [id=id_value] { style properties } examples css #identified { background-color: skyblue; } html <div id="identified">this div has a special id on it!</div> <div>this is just a regular div.</div> result specifications specification status comment
selectors level 4the definition of 'id
selectors' in that specification. working draft ...
...lector: [id=id_value] { style properties } examples css #identified { background-color: skyblue; } html <div id="identified">this div has a special id on it!</div> <div>this is just a regular div.</div> result specifications specification status comment
selectors level 4the definition of 'id
selectors' in that specification. working draft
selectors level 3the definition of 'id
selectors' in that specification. recommendation css level 2 (revision 1)the definition of 'id
selectors' in that specification. recommendation css level 1the definition of 'id
selectors' in that specification. recommendation initial definition ...
Type selectors - CSS: Cascading Style Sheets
the css type
selector matches elements by node name. in other words, it selects all elements of the given type within a document. /* all <a> elements. */ a { color: red; } syntax element { style properties } examples css span { background-color: skyblue; } html <span>here's a span with some text.</span> <p>here's a p with some text.</p> <span>here's a span with more text.</span> result specifications specification status comment
selectors level 4the definition of 'type (tag name)
selector' in that specification. working draft no changes
selectors level 3the definition of 'type
selectors' in that specification. recommendation no changes css level 2 (revision 1)the definition of 'type
selectors' in that specification. ...
...
selectors level 4the definition of 'type (tag name)
selector' in that specification. working draft no changes
selectors level 3the definition of 'type
selectors' in that specification. recommendation no changes css level 2 (revision 1)the definition of 'type
selectors' in that specification. recommendation css level 1the definition of 'type
selectors' in that specification. recommendation initial definition ...
Selector (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
a css
selector is the part of a css rule that describes what elements in a document the rule will match. the matching elements will have the rule's specified style applied to them. consider this css: p { color: green; } div.warning { width: 100%; border: 2px solid yellow; color: white; background-color: darkred; padding: 0.8em 0.8em 0.6em; } #customized { font: 16px lucida grande, arial, helvetica, sans-serif; } the
selectors here are "p" (which applies the color green to the text inside any <p> element), "div.warning" (which makes any <div> element with the class "warning" look like a warning box), and "#customized", which sets the base font of the element with the id "customized" to 16-pixel tall lucida grande or one of a few fallback fonts. we can then apply this c...
Cascade and inheritance - Learn web development
t works will become more obvious to you. the cascade stylesheets cascade — at a very simple level this means that the order of css rules matter; when two rules apply that have equal specificity the one that comes last in the css is the one that will be used. in the below example, we have two rules that could apply to the h1. ...
... one that comes last in the css is the one that will be used. in the below example, we have two rules that could apply to the h1. the h1 ends up being colored blue — these rules have an identical
selector and therefore carry the same specificity, so the last one in the source order wins. specificity specificity is how the browser decides which rule applies if multiple rules have different
selectors, but could still apply to the same element. ...
...ules that could apply to the h1. the h1 ends up being colored blue — these rules have an identical
selector and therefore carry the same specificity, so the last one in the source order wins. specificity specificity is how the browser decides which rule applies if multiple rules have different
selectors, but could still apply to the same element. it is basically a measure of how specific a
selector's selection will be: an element
selector is less specific — it will select all elements of that type that appear on a page — so will get a lower score. a class
selector is more specific — it will select only the elements on a page that have a specific class attribute value — so will get a higher score. example time! below we again have two rules that could apply to the h1. the below...
...And 24 more matches
Index - Archive of obsolete content
d-ons, extensions no summary! 201 page loading code snippets no summary! 202 post data to window add-ons, extensions, needscontent no summary! 203 preferences add-ons, code snippets, extensions, guide, mozilla, preferences no summary! 204 progress listeners add-ons, extensions no summary! 205 query
selector dom no summary! 206 rosetta c, dom, html, htmlscriptelement, javascript, non-javascript, programming languages no summary! 207 running applications add-ons, code snippets, extensions no summary! 208 svg animation needscontent no summary! 209 svg general code snippets no summary! 210 scrollbar ...
...ther shapes. 2133 -ms-wrap-through css, css property, css:microsoft extensions, non-standard, reference, recipe:css-property the -ms-wrap-through css property is a microsoft extension that specifies how content should wrap around an exclusion element. 2134 :-moz-full-screen-ancestor css, css:mozilla extensions, deprecated, non-standard, pseudo-class, reference,
selector the :-moz-full-screen-ancestor css pseudo-class is a mozilla extension that represents all ancestors of the full-screen element, except containing frames in parent documents, which are the full-screen element in their own documents. however, those elements' ancestors have this pseudo-class applied to them. 2135 :-moz-system-metric() :-moz-system-metric, css, css:mozilla exten...
...udo-class is a mozilla extension that represents all ancestors of the full-screen element, except containing frames in parent documents, which are the full-screen element in their own documents. however, those elements' ancestors have this pseudo-class applied to them. ...
...And 23 more matches
Index - Web APIs
browser how the custom property should behave; what are allowed types, whether the custom property inherits its value, and what the default value of the custom property is. 388 css.escape() api, css, cssom, method, reference, static, escape() the css.escape() static method returns a cssomstring containing the escaped string passed as parameter, mostly for use as part of a css
selector. 389 css.paintworklet (static property) api, css, css paint api, experimental, houdini, painting, property, reference, worklet, paintworklet paintworklet is a static, read-only property of the css interface that provides access to the paintworklet, which programmatically generates an image where a css property expects a file. 390 css.supports() api, css, cssom,...
...rty of the csspseudoelement interface returns a reference to the originating element of the pseudo-element, in other words its parent element. 450 csspseudoelement.type api, csspseudoelement, experimental, property, reference, type the type read-only property of the csspseudoelement interface returns the type of the pseudo-element as a string, represented in the form of a css
selector. 451 cssrule api, cssom, interface, reference the cssrule interface represents a single css rule. there are several types of rules, listed in the type constants section below. 452 cssrule.csstext api, cssom, needsspectable, property, reference the csstext property of the cssrule interface returns the actual text of a cssstylesheet style-rule. 453 ...
...pi, cssom, method, reference the cssstyledeclaration.setproperty() method interface sets a new value for a property on a css style declaration object. 465 cssstylerule api, cssom, cssstylerule, interface, reference cssstylerule represents a single css style rule. it implements the cssrule interface with a type value of 1 (cssrule.style_rule). 466 cssstylerule.
selectortext api, cssom, cssstylerule, reference the cssrule.
selectortext property gets the textual representation of the
selector for the rule set. this is readonly in some browsers; to set stylesheet rules dynamically cross-browser, see using dynamic styling information. 467 cssstylerule.style api, cssom, needsspectable, property, reference the cssrule.style property is th...
...And 23 more matches
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
note: :matches() was renamed to :is() in csswg issue #3258. the :is() css pseudo-class function takes a
selector list as its argument, and selects any element that can be selected by one of the
selectors in that list. this is useful for writing large
selectors in a more compact form. note that currently browsers support this functionality as :matches(), or through an older, prefixed pseudo-class — :any(), including older versions of chrome, firefox, and safari. :any() works in exactly the same way as :matches()/:is(), except that it requires vendor prefixes and doesn't support complex
selectors. /* selects any paragraph inside a header, main or footer element that is being hovered */ :is(header, main, footer) p:hover { color: red; cursor: pointer; } /* the above is equivalent to ...
...electors. ...
... or footer element that is being hovered */ :is(header, main, footer) p:hover { color: red; cursor: pointer; } /* the above is equivalent to the following */ header p:hover, main p:hover, footer p:hover { color: red; cursor: pointer; } /* backwards-compatible version with :-*-any() and :matches() (it is not possible to group
selectors into single rule, because presence of invalid
selector would invalidate whole rule.) */ :-webkit-any(header, main, footer) p:hover { color: red; cursor: pointer; } :-moz-any(header, main, footer) p:hover { color: red; cursor: pointer; } :matches(header, main, footer) p:hover { color: red; cursor: pointer; } syntax :is( <complex-
selector-list> )where <complex-
selector-list> = <complex-
selector>#where <complex-
selector> = <compound-selec...
...And 20 more matches
:not() - CSS: Cascading Style Sheets
the :not() css pseudo-class represents elements that do not match a list of
selectors. since it prevents specific items from being selected, it is known as the negation pseudo-class. /* selects any element that is not a paragraph */ :not(p) { color: blue; } the :not() pseudo-class has a number of quirks, tricks, and unexpected results that you should be aware of before using it. syntax the :not() pseudo-class requires a comma-separated list of one or more
selectors as its argument. the list must not contain another negation
selector or a pseudo-element. the ability to list more than one
selector is experimental and not yet widely supported. ...
...seudo-class has a number of quirks, tricks, and unexpected results that you should be aware of before using it. syntax the :not() pseudo-class requires a comma-separated list of one or more
selectors as its argument. the list must not contain another negation
selector or a pseudo-element. the ability to list more than one
selector is experimental and not yet widely supported. ...
...rks, tricks, and unexpected results that you should be aware of before using it. syntax the :not() pseudo-class requires a comma-separated list of one or more
selectors as its argument. the list must not contain another negation
selector or a pseudo-element. the ability to list more than one
selector is experimental and not yet widely supported. ...
...And 18 more matches
:where() - CSS: Cascading Style Sheets
examples comparing :where() and :is() this example shows how :where() works, and also illustrates the difference between :where() and :is(). take the following html: <article> <h2>:is()-styled links</h2> <section class="is-styling"> <p>here is my main content. this <a href="https://mozilla.org">contains a link</a>. </section> <aside class="is-styling"> <p>here is my aside content. ...
... you can see the result below (although bear in m...
... you can see the result below (although bear in mind that currently :is() and :where() are currently only enabled by default in firefox ...
...And 18 more matches
Specificity - CSS: Cascading Style Sheets
when multiple declarations have equal specificity, the last declaration found in the css is applied to the element. ...
...when multiple declarations have equal specificity, the last declaration found in the css is applied to the element. ...
...when multiple declarations have equal specificity, the last declaration found in the css is applied to the element. ...
...And 17 more matches
:nth-child() - CSS: Cascading Style Sheets
tion in a series of siblings is even: 2, 4, 6, etc. functional notation <an+b> represents elements in a list whose indices match those found in a custom pattern of numbers, defined by an+b, where: a is an integer step size, b is an integer offset, n is all positive integers, starting from 0. it can be read as the an+bth element of a list. ...
...otation <an+b> represents elements in a list whose indices match those found in a custom pattern of numbers, defined by an+b, where: a is an integer step size, b is an integer offset, n is all positive integers, starting from 0. it can be read as the an+bth element of a list. ...
...nts elements in a list whose indices match those found in a custom pattern of numbers, defined by an+b, where: a is an integer step size, b is an integer offset, n is all positive integers, starting from 0. it can be read as the an+bth element of a list. ...
...And 16 more matches
Creating annotations - Archive of obsolete content
pi is deprecated from firefox 29 onwards. please see the ui module for replacements. in particular, for a simple button, try the action button or toggle button apis, and for a more complex widget try the toolbar or sidebar apis. we'll use two objects to create annotations: a page-mod to find page elements that the user can annotate, and a panel for the user to enter the annotation text itself. ...
...om firefox 29 onwards. please see the ui module for replacements. in particular, for a simple button, try the action button or toggle button apis, and for a more complex widget try the toolbar or sidebar apis. we'll use two objects to create annotations: a page-mod to find page elements that the user can annotate, and a panel for the user to enter the annotation text itself. ...
...eplacements. in particular, for a simple button, try the action button or toggle button apis, and for a more complex widget try the toolbar or sidebar apis. we'll use two objects to create annotations: a page-mod to find page elements that the user can annotate, and a panel for the user to enter the annotation text itself.
selector page-mod
selector content scripts the content script for the
selector page-mod uses jquery to examine and manipulate the dom. its main job is to maintain a matched element: this is the page element that is the current candidate for an annotation. the matched element is highlighted and has a click handler bound to it which sends a message to the main add-on code. the
selector page mod can be switched on and off using a message from the main add-on code. it is init...
...And 15 more matches
context-menu - Archive of obsolete content
y of the options object passed to its constructor, like this: var cm = require("sdk/context-menu"); cm.item({ label: "my menu item", context: cm.urlcontext("*.mozilla.org") }); constructor description pagecontext() the page context. selectioncontext() this context occurs when the menu is invoked on a page in which the user has made a selection.
selectorcontext(
selector) this context occurs when the menu is invoked on a node that either matches
selector, a css
selector, or has an ancestor that matches.
selector may include multiple
selectors separated by commas, e.g., "a[href], img". urlcontext(matchpattern) this context occurs when the menu is invoked on pages with particular urls. matchpattern is a match pattern string or an ar...
...eturns a true value. the function is passed an object with properties describing the menu invocaton context. array an array of any of the other types. this context occurs when all contexts in the array occur. menu items also have a context property that can be used to add and remove declarative contexts after construction. for example: var context = require("sdk/context-menu").
selectorcontext("img"); mymenuitem.context.add(context); mymenuitem.context.remove(context); when a menu item is bound to more than one context, it appears in the menu when all of those contexts occur. in content scripts the declarative contexts are handy but not very powerful. for instance, you might want your menu item to appear for any page that has at least one image, but declarative contexts won't...
...or this event and it returns true, the menu item associated with the listener's content script is shown in the menu. for example, this item appears whenever the context menu is invoked on a page that contains at least one image: require("sdk/context-menu").item({ label: "this page has images", contentscript: 'self.on("context", function (node) {' + ' return !!document.query
selector("img");' + '});' }); note that the listener function has a parameter called node. this is the node in the page that the user context-clicked to invoke the menu. you can use it to determine whether your item should be shown. you can both specify declarative contexts and listen for contexts in a content script. your context listener is called even if any declarative contexts are ...
...And 14 more matches
:nth-last-child() - CSS: Cascading Style Sheets
a series of siblings is even: 2, 4, 6, etc., counting from the end. functional notation <an+b> represents elements whose numeric position in a series of siblings matches the pattern an+b, for every positive integer or zero value of n. the index of the first element, counting from the end, is 1. the values a and b must both be <integer>s. ...
.... functional notation <an+b> represents elements whose numeric position in a series of siblings matches the pattern an+b, for every positive integer or zero value of n. the index of the first element, counting from the end, is 1. the values a and b must both be <integer>s. ...
... <an+b> represents elements whose numeric position in a series of siblings matches the pattern an+b, for every positive integer or zero value of n. the index of the first element, counting from the end, is 1. the values a and b must both be <integer>s. ...
...And 14 more matches
:host() - CSS: Cascading Style Sheets
the :host() css pseudo-class function selects the shadow host of the shadow dom containing the css it is used inside (so you can select a custom element from inside its shadow dom) — but only if the
selector given as the function's parameter matches the shadow host. the most obvious use of this is to put a class name only on certain custom element instances, and then include the relevant class
selector as the function argument. you can't use this with a descendant
selector expression to select only instances of the custom element that are inside a particular ancestor. ...
... custom element instances, and then include the relevant class
selector as the function argument. you can't use this with a descendant
selector expression to select only instances of the custom element that are inside a particular ancestor. that's the job of :host-context(). note: this has no effect when used outside a shadow dom. ...
...n't use this with a descendant
selector expression to select only instances of the custom element that are inside a particular ancestor. that's the job of :host-context(). note: this has no effect when used outside a shadow dom. ...
...And 13 more matches
jspage - Archive of obsolete content
case"hash":b=new hash(c);break;case"array":b=[];for(var d=0,a=c.length;d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var browser=$merge({engine:{name:"unknown",version:0},platform:{name:(window.orientation!=undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].tolowercase()},features:{xpath:!!(document.evaluate),air:!!(window.runtime),query:!!(document.query
selector)},plugins:{},engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getelementsbyclassname)?950:925)); },trident:function(){return(!window.activexobject)?false:((window.xmlhttprequest)?((document.query
selectorall)?6:5):4);},webkit:function(){return(navigator.taintenabled)?false:((browser.features.xpath)?((browser.features.query)?525:420):419); },gecko:fun...
...rollleft:function(){return this.getscroll().x;},getscrollheight:function(){return this.getscrollsize().y; },getscrollwidth:function(){return this.getscrollsize().x;},gettop:function(){return this.getposition().y;},getleft:function(){return this.getposition().x; }});native.implement([document,element],{getelements:function(h,g){h=h.split(",");var c,e={};for(var d=0,b=h.length;d<b;d++){var a=h[d],f=
selectors.utils.search(this,a,e); if(d!=0&&f.item){f=$a(f);}c=(d==0)?f:(c.item)?$a(c).concat(f):c.concat(f);}return new elements(c,{ddup:(h.length>1),cash:!g});}});element.implement({match:function(b){if(!b||(b==this)){return true; }var d=
selectors.utils.parsetagandid(b);var a=d[0],e=d[1];if(!
selectors.filters.byid(this,e)||!
selectors.filters.bytag(this,a)){return false;}var c=
selectors.utils.parseselecto...
...his,a,e); if(d!=0&&f.item){f=$a(f);}c=(d==0)?f:(c.item)?$a(c).concat(f):c.concat(f);}return new elements(c,{ddup:(h.length>1),cash:!g});}});element.implement({match:function(b){if(!b||(b==this)){return true; }var d=
selectors.utils.parsetagandid(b);var a=d[0],e=d[1];if(!
selectors.filters.byid(this,e)||!
selectors.filters.bytag(this,a)){return false;}var c=
selectors.utils.parse
selector(b); return(c)?
selectors.utils.filter(this,c,{}):true;}});var
selectors={cache:{nth:{},parsed:{}}};
selectors.regexps={id:(/#([\w-]+)/),tag:(/^(\w+|\*)/),quick:(/^(\w+|\*)$/),splitter:(/\s*([+>~\s])\s*([a-za-z#.*:\[])/g),combined:(/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)};
selectors.utils={chk:function(b,c){if(!c){return true;}var a=$uid(b);if(!c[a]){return c[a]=true...
...And 11 more matches
How to build custom form controls - Learn web development
:focus pseudo-class in order to be sure they will behave the same. .select .active, .select:focus { outline: none; /* this box-shadow property is not exactly required, however it's imperative to ensure active state is visible, especially to keyboard users, that we use it as a default value. */ box-shadow: 0 0 3px 1px #227755; } now, let's handle the list of options: /* the .select
selector here helps to make we only select element inside our control. */ .select .optlist { /* this will make sure our list of options will be displayed below the value and out of the html flow */ position : absolute; top : 100%; left : 0; } we need an extra class to handle when the list of options is hidden. this is necessary in order to manage the differences between the activ...
...ion">strawberry</li> <li class="option">apple</li> </ul> </div> </form> </body> second, we need two new classes to let us hide the unneeded element: we visually hide the "real" <select> element if our script isn't running, or the custom control if it is running. note that, by default, our html code hides our custom control. ...
... just add the widget class to hide the <select> elements, and to dynamically add the dom tree representing the custom control after every <select> element in the page. making the job easier in the code we are about to build, we will use the standard javascript and dom apis to do all the work we need. the features we plan to use are the following: classlist addeventlistener() foreach query
selector() and query
selectorall() beyond the availability of those specific features, there is still one issue remaining before starting. the object returned by the query
selectorall() function is a nodelist rather than an array. this is important because array objects support the foreach function, but nodelist doesn't. because nodelist really looks like an array and because foreach is so convenient to u...
...And 11 more matches
Box-shadow generator - CSS: Cascading Style Sheets
="wrap-left"> <div class="colorpicker category"> <div class="title"> </div> <div id="colorpicker" class="group"> <div id="gradient" class="gradient"> <div id="gradient_picker"> </div> </div> <div id="hue" data-topic="hue" class="hue"> <div id="hue_
selector"> </div> </div> <div class="info"> <div class="input" data-topic="hue" data-title='h:' data-action="hsv"></div> <div class="input" data-topic="saturation" data-title='s:' data-action="hsv"></div> <div class="input" data-topic="value" data-title='v:' data-action="hsv"></div> ...
...ction="hsv"></div> <div class="input" data-topic="saturation" data-title='s:' data-action="hsv"></div> <div class="input" data-topic="value" data-title='v:' data-action="hsv"></div> </div> <div class="alpha"> <div id="alpha" data-topic="alpha"> <div id="alpha_
selector"> </div> </div> </div> <div class="info"> <div class="input" data-topic="r" data-title='r:' data-action="rgb"></div> <div class="input" data-topic="g" data-title='g:' data-action="rgb"></div> <div class="input" data-topic="b" data-title='b:' data-action="rgb"></d...
...; } #colorpicker #alpha { width: 100%; height: 100%; background: url("https://mdn.mozillademos.org/files/5703/alpha_mask.png"); background: -moz-linear-gradient(left, rgba(255, 0, 0, 0) 0%, rgba(255, 0, 0, 1) 100%); } #colorpicker #gradient_picker { width: 0.5em; height: 0.5em; border-radius: 0.4em; border: 2px solid #ccc; position: relative; top: 20%; left: 20%; } #colorpicker #hue_
selector, #colorpicker #alpha_
selector { width: 3px; height: 100%; border: 1px solid #777; background-color: #fff; position: relative; top: -1px; left: 0%; } /* input hsv and rgb */ #colorpicker .info { width: 200px; margin: 5px; float: left; } #colorpicker .info * { float: left; } #colorpicker .info input { margin: 0; text-align: center; width: 30px; -moz-user-select: text; -webkit-use...
...And 11 more matches
Using CSS transitions - CSS: Cascading Style Sheets
d-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration: 0.5s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 1s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 10...
...ground-color font-size left top -webkit-transform transform color; -webkit-transition-duration: 1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 1s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 2s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 10...
...ground-color font-size left top transform -webkit-transform color; -webkit-transition-duration: 2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration: 2s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 4s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 10...
...And 11 more matches
Combinators - Learn web development
previous overview: building blocks next the final
selectors we will look at are called combinators, because they combine other
selectors in a way that gives them a useful relationship to each other and the location of content in the document. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn about the different combinator
selectors that can be used in css. ...
...literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn about the different combinator
selectors that can be used in css. descendant combinator the descendant combinator — typically represented by a single space ( ) character — combines two
selectors such that elements matched by the second
selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first
selector.
selectors that utilize a descendant combinator are called descendant
selectors. body article p in the example below, we are matching only the <p> element which is inside an element with a class of .box. child c...
...descendent elements further down the hierarchy don't match. ...
...And 10 more matches
Pseudo-classes and pseudo-elements - Learn web development
previous overview: building blocks next the next set of
selectors we will look at are referred to as pseudo-classes and pseudo-elements. there are a large number of these, and they often serve quite specific purposes. once you know how to use them, you can look at the list to see if there is something which works for the task you are trying to achieve. once again the relevant mdn page for each
selector is helpful in explaining browser support. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn about the pseudo-class and pseudo-element
selectors. what is a pseudo-class? a pseudo-cla...
...lector is helpful in explaining browser support. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, html basics (study introduction to html), and an idea of how css works (study css first steps.) objective: to learn about the pseudo-class and pseudo-element
selectors. what is a pseudo-class? a pseudo-class is a
selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. they tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code. pseudo-classes are keywords that start with a colon: :pse...
... the first paragraph in an article larger and bold, we could add a class to that paragraph and then add css to that class, as shown in the first example below: however, this could be annoying to maintain — what if a new paragraph got added to the top of the document? we'd need to move the class over to the new paragraph. instead of adding the class, we could use the :first-child pseudo-class
selector — this will always target the first child element in the article, and we will no longer need to edit the html (this may not always be possible anyway, maybe due to it being generated by a cms.) all pseudo-classes behave in this same kind of way. they target some bit of your document that is in a certain state, behaving as if you had added a class into your html. take a look at some other exa...
...And 10 more matches
CSSStyleSheet.insertRule() - Web APIs
style sheet, with some restrictions. note: although insertrule() is exclusively a method of cssstylesheet, it actually inserts the rule into cssstylesheet.cssrules — its internal cssrulelist. syntax stylesheet.insertrule(rule [, index]) parameters rule a domstring containing the rule to be inserted. what the inserted rule must contain depends on its type: for rule-sets, both a
selector and a style declaration. for at-rules, both an at-identifier and the rule content. index optional a positive integer less than or equal to stylesheet.cssrules.length, representing the newly inserted rule's position in cssstylesheet.cssrules. the default is 0. (in older implementations, this was required. see browser compatibility for details.) return value the newly inserted rule's ind...
... if (array.isarray(rule[1][0])) { rule = rule[1]; j = 0; } for (var pl = rule.length; j < pl; j++) { var prop = rule[j]; propstr += prop[0] + ': ' + prop[1] + (prop[2] ? ' !important' : '') + ';\n'; } // insert css rule stylesheet.
... propstr = ''; // if the second argument of a rule is an array of arrays, correct our variables. if (array.isarray(rule[1][0])) { rule = rule[1]; j = 0; } for (var pl = rule.length; j < pl; j++) { var prop = rule[j]; propstr += prop[0] + ': ' + prop[1] + (prop[2] ? ' !important' : '') + ';\n'; } // insert css rule stylesheet.insertrule(
selector + '{' + propstr + '}', stylesheet.cssrules.length); } } polyfill the below polyfill will correct the input of the arguments of insertrule() to standardize them in internet explorer 5–8. it supplements insertrule() with a function that separates the
selector from the rules before sending the arguments to the default native insertrule(). (function(sheet_proto){ var originalinsertrule = she...
...And 10 more matches
:has() - CSS: Cascading Style Sheets
the :has() css pseudo-class represents an element if any of the
selectors passed as parameters (relative to the :scope of the given element) match at least one element. ...
... the :has() css pseudo-class represents an element if any of the
selectors passed as parameters (relative to the :scope of the given element) match at least one element. ...
... the :has() css pseudo-class represents an element if any of the
selectors passed as parameters (relative to the :scope of the given element) match at least one element. ...
...And 10 more matches
@supports - CSS: Cascading Style Sheets
rated by a colon). the declaration must be surrounded by parentheses. the following example returns true if the browser's transform-origin property considers 5% 5% valid: @supports (transform-origin: 5% 5%) {} function syntax the second basic supports condition is a supports function, the syntax for these is supported by all browsers, but the functions themselves are still being standardized.
selector() tests if the browser supports the tested
selector syntax. the following example returns true if the browser supports the child combinator: @supports
selector(a > b) {} the not operator the not operator can precede any expression to create a new expression, resulting in the negation of the original one. the following example returns true if the browser's transform-origin property doesn't c...
...ole rule is ignored. ...
...> | <supports-in-parens> [ and <supports-in-parens> ]* | <supports-in-parens> [ or <supports-in-parens> ]*where <supports-in-parens> = ( <supports-condition> ) | <supports-feature> | <general-enclosed>where <supports-feature> = <supports-decl> | <supports-
selector-fn><general-enclosed> = [ <function-token> <any-value> ) ] | ( <ident> <any-value> )where <supports-decl> = ( <declaration> )<supports-
selector-fn> =
selector( <complex-
selector> )where <complex-
selector> = <compound-
selector> [ <combinator>? ...
...And 10 more matches
Index - Learn web development
le columns, or add animations and other decorative features. 103 css building blocks beginner, css, learn, building blocks this module carries on where css first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. this module looks at the cascade and inheritance, all the
selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. 104 a cool-looking box assessment, beginner, css, learn, backgrounds, borders, box, box model, effects in this assessment, you'll get some more practice in creating cool-looking boxes by trying to create an eye-catching box. 105 advanced styling effects article, b...
...r, css, image, learn, position, borders, color we have covered quite a lot here, and you can see that there is quite a lot to adding a background or a border to a box. do explore the different property pages if you want to find out more about any of the features we have discussed. each page on mdn has more examples of usage for you to play with and enhance your knowledge. 107 css
selectors attribute, beginner, css, class, learn, pseudo,
selectors, id in css,
selectors are used to target the html elements on our web pages that we want to style. there are a wide variety of css
selectors available, allowing for fine-grained precision when selecting elements to style. in this article and its sub-articles we'll run through the different types in great detail, seeing how they ...
... class, learn, pseudo,
selectors, id in css,
selectors are used to target the html elements on our web pages that we want to style. there are a wide variety of css
selectors available, allowing for fine-grained precision when selecting elements to style. in this article and its sub-articles we'll run through the different types in great detail, seeing how they work. 108 attribute
selectors attribute, beginner, css, learn,
selectors as you know from your study of html, elements can have attributes that give further detail about the element being marked up. in css you can use attribute
selectors to target elements with certain attributes. this lesson will show you how to use these very useful
selectors. ...
...And 9 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
we need to add a gainno...
...we need to add a gainnode and connect that through our audio graph to actually apply amplitude variations to our sound. the gain node has one property: gain, which is of type audioparam. this is really use...
...the pulse modulates the first wave: <label for="hz">hz</label> <input name="hz" id="hz" type="range" min="660" max="1320" value="880" step="1" /> <label for="lfo">lfo</label> <input name="lfo" id="lfo" type="range" min="20" max="40" value="30" step="1" /> as before, we'll vary the parameters when the range input values are changed by the user. ...
...And 9 more matches
::slotted() - CSS: Cascading Style Sheets
the ::slotted() css pseudo-element represents any element that has been placed into a slot inside an html template (see using templates and slots for more information). this only works when used inside css placed within a shadow dom. note also that this
selector won't select a text node placed into a slot; it only targets actual elements. ...
...or more information). this only works when used inside css placed within a shadow dom. note also that this
selector won't select a text node placed into a slot; it only targets actual elements. ...
... works when used inside css placed within a shadow dom. note also that this
selector won't select a text node placed into a slot; it only targets actual elements. ...
...And 9 more matches
Appendix F: Monitoring DOM changes - Archive of obsolete content
s passed to the wrapped function, modifying its return value, and making changes both before and after the original method is called. this scheme is highly flexible and can be made to work under most circumstances. css animation events this technique, which works on firefox 5+, has some particular advantages. because it is based on css, it can be keyed to match new elements of any arbitrary css
selector. and because it is css-based, and is triggered when css is being applied anyway, it does not slow dom mutations. the technique was adapted from the method used by the x-tag library. the code below contains an inefficient fallback implementation for older browsers. it is worth noting, however, that while the animation-based implementation will fire any time an element which previously did not mat...
... it is css-based, and is triggered when css is being applied anyway, it does not slow dom mutations. the technique was adapted from the method used by the x-tag library. the code below contains an inefficient fallback implementation for older browsers. ...
... * @param {function(event)} callback the function which is to be called * when matching nodes become available. * @param {document} doc the document in which to watch for new nodes. ...
...And 8 more matches
Looping code - Learn web development
le> html { width: 100%; height: inherit; background: #ddd; } canvas { display: block; } body { margin: 0; } button { position: absolute; top: 5px; left: 5px; } </style> </head> <body> <button>update</button> <canvas></canvas> <script> const btn = document.query
selector('button'); const canvas = document.query
selector('canvas'); const ctx = canvas.getcontext('2d'); let width = document.documentelement.clientwidth; let height = document.documentelement.clientheight; canvas.width = width; canvas.height = height; function random(number) { return math.floor(math.random()*number); } function draw() { ctx.clearrect(0...
...e counter variable, to bring it closer to the point where the condition is no longer true. some curly braces that contain a block of code — this code will be run each time the loop iterates. let's look at a real example so we can visualize what these do more clearly. ...
... this shows a loop is used to iterate over the items in an array and do something with each of them — a very common pattern in javascript. here: the counter v...
...And 8 more matches
Debugging CSS - Learn web development
this article will give you guidance on how to go about debugging a css problem, and show you how the devtools included in all modern browsers can help you to find out what is going on. ...
...in devtools before adding it to your css file. you can click the closing curly brace in the rule to start entering a new declaration into it, at which point you can start typing the new property and devtools will show you an autocomplete list of matching properties. after selecting font-size, enter the value you want to try. you can also click the + button to add an additional rule with the same
selector, and add your new rules there. note: there are other useful features in the rules view too, for example declarations with invalid values are crossed out. you can find out more at examine and edit css. understanding the box model in previous lessons we have discussed the box model, and the fact that we have an alternate box model that changes how the size of elements are calculated based on...
... 400px. note: find out more in examining and inspecting the box model. solving specificity issues sometimes during development, but in particular when you need to edit the css on an existing site, you will find yourself having a hard time getting some css to apply. no matter what you do, the element just doesn't seem to take the css. ...
...And 7 more matches
Getting started with CSS - Learn web development
o work in styles.css locally, or you can use our interactive editor below to continue with this tutorial. the interactive editor acts as if the css in the first panel is linked to the html document, just as we have with our document above. styling html elements by making our heading red we have already demonstrated that we can target and style an html element. we do this by targeting an element
selector — this is a
selector that directly matches an html element name. to target all paragraphs in the document you would use the
selector p. to turn all paragraphs green you would use: p { color: green; } you can target multiple
selectors at once, by separating the
selectors with a comma. if i want all paragraphs and all list items to be green my rule looks like this: p, li { color: green; ...
... elements without changing the others. the most common way to do this is to add a class to your html element and target that class. in your html document, add a class attribute to the second list item. your list will now look like this: <ul> <li>item one</li> <li class="special">item two</li> <li>item <em>three</em></li> </ul> in your css you can target the class of special by creating a
selector that starts with a full stop character. add the following to your css file: .special { color: orange; font-weight: bold; } save and refresh to see what the result is. you can apply the class of special to any element on your page that you want to have the same look as this list item. for example, you might want the <span> in the paragraph to also be orange and bold. try adding a class of s...
...r: orange; font-weight: bold; } save and refresh to see what the result is. you can apply the class of special to any element on your page that you want to have the same look as this list item. for example, you might want the <span> in the paragraph to also be orange and bold. try adding a class of special to it, then reload your page and see what happens. ...
...And 7 more matches
Making decisions in your code — conditionals - Learn web development
wear shorts! go to the beach, or the park, and get an ice cream.'; } else if (choice === 'rainy') { para.textcontent = 'rain is falling outside; ta...
...wear shorts! go to the beach, or the park, and get an ice cream.'; } else if (choice === 'rainy') { para.textcontent = 'rain is falling outside; take a rain coat and an umbrella, and don\'t stay...
...wear shorts! go to the beach, or the park, and get an ice cream.'; break; case 'rainy': para.textcontent = 'rain is falling ...
...And 7 more matches
Using Objective-C from js-ctypes
[synth startspeakingstring: @"hello, firefox!"]; // wait until start speaking. while (![synth isspeaking]) {} // wait while speaking. while ([synth isspeaking]) {} [synth release]; return 0; } save this file as test.m, and run with the following command, inside the same directory as the saved file (needs xcode). $ clang -framework appkit test.m && ./a.out class, message, and
selector our task at hand is to convert objective-c syntax to c syntax. let's look at the following codelet: [nsspeechsynthesizer alloc] it passes an alloc message to the nsspeechsynthesizer class, in objective-c syntax. it performs the following through this objective-c syntax: get the nsspeechsynthesizer class definition. register the alloc
selector for the message. send a message to the class,...
... at hand is to convert objective-c syntax to c syntax. let's look at the following codelet: [nsspeechsynthesizer alloc] it passes an alloc message to the nsspeechsynthesizer class, in objective-c syntax. it performs the following through this objective-c syntax: get the nsspeechsynthesizer class definition. register the alloc
selector for the message. send a message to the class, with the
selector. get a reference to a class class definitions are retrieved with the objc_getclass function, declared in /usr/include/objc/runtime.h. the objc_getclass function receives the name of the class, looks up the definition, and returns it. class objc_getclass(const char *name); in /usr/include/objc/objc.h, class is defined as an opaque type by the following: typedef struct objc_class *class; i...
...e of the class, looks up the definition, and returns it. ...
...And 7 more matches
CSS basics - Learn web development
save index.html and load it in your browser. you should see something like this: if your paragraph text is red, congratulations! your css is working. anatomy of a css ruleset let's dissect the css code for red paragraph text to understand how it works : the whole structure is called a ruleset. (the term ruleset is often referred to as just rule.) note the names of the individual parts:
selector this is the html element name at the start of the ruleset. it defines the element(s) to be styled (in this example, <p> elements). to style a different element, change the
selector. declaration this is a single rule like color: red;. it specifies which of the element's properties you want to style. properties these are ways in which you can style an html element. (in this example, color is a...
...is a property of the <p> elements.) in css, you choose which properties you want to affect in the rule. property value to the right of the property—after the colon—there is the property value. this chooses one out of many possible appearances for a given property. (for example, there are many color values in addition to red.) note the other important parts of the syntax: apart from the
selector, each ruleset must be wrapped in curly braces. ({}) within each declaration, you must use a colon (:) to separate the property from its value or values. within each ruleset, you must use a semicolon (;) to separate each declaration from the next one. to modify multiple property values in one ruleset, write them separated by semicolons, like this: p { color: red; width: 500px; border: 1...
...values. within each ruleset, you must use a semicolon (;) to separate each declaration from the next one. to modify multiple property values in one ruleset, write them separated by semicolons, like this: p { color: red; width: 500px; border: 1px solid black; } selecting multiple elements you can also select multiple elements and apply a single ruleset to all of them. ...
...And 6 more matches
JavaScript basics - Learn web development
it. in your index.html file, enter this code on a new line, just before the closing </body> tag: <script src="scripts/main.js"></script> this is doing the same job as the <link> element for css. it applies the javascript to the page, so it can have an effect on the html (along with the css, and anything else on the page). add this code to the main.js file: const myheading = document.query
selector('h1'); myheading.textcontent = 'hello world!'; make sure the html and javascript files are saved. then load index.html in your browser. you should see something like this: note: the reason the instructions (above) place the <script> element near the bottom of the html file is that the browser reads code in the order it appears in the file. if the javascript loads first and it is supposed t...
...avascript loads first and it is supposed to affect the html that hasn't loaded yet, there could be problems. placing javascript near the bottom of an html page is one way to accommodate this dependency. to learn more about alternative approaches, see script loading strategies. what happened? the heading text changed to hello world! using javascript. you did this by using a function called query
selector() to grab a reference to your heading, and then store it in a variable called myheading. this is similar to what we did using css
selectors. when you want to do something to an element, you need to select it first. following that, the code set the value of the myheading variable's textcontent property (which represents the content of the heading) to hello world!. note: both of the features you...
...ray this is a structure that allows you to store multiple values in a single reference. let myvariable = [1,'bob','steve',10]; refer to each member of the array like this: myvariable[0], myvariable[1], etc. object this can be anything. everything in javascript is an object, and can be stored in a variable. keep this in mind as you learn. let myvariable = document.query
selector('h1'); all of the above examples too. so why do we need variables? variables are necessary to do anything interesting in programming. if values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change an image displayed in an image gallery. comments comments are snippets of text that can be added along with code. the browser ignores text m...
...And 6 more matches
Introduction to events - Learn web development
t a simple example of what we mean here. you've already seen events and event handlers used in many of the examples, but let's recap just to cement our knowledge. in the following example, we have a single <button>, which when pressed, makes the background change to a random color: <button>change color</button> button { margin: 10px }; the javascript looks like so: const btn = document.query
selector('button'); function random(number) { return math.floor(math.random() * (number+1)); } btn.onclick = function() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } in this code, we store a reference to the button inside a constant called btn, using the document.query
selector() function. we also define a funct...
...there are a number of ways to add event listener code to web pages so it runs when the associated event fires. in this section, we review the various mechanisms and discuss which ones you should use. event handler properties these are the properties that exist to contain event handler code we have seen most frequently during the course. returning to the above example: const btn = document.query
selector('button'); btn.onclick = function() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } the onclick property is the event handler property being used in this situation. it is essentially a property like any other available on the button (e.g. btn.textcontent, or btn.style), but it is a special type — when you...
...ially a property like any other available on the button (e.g. btn.textcontent, or btn.style), but it is a special type — when you set it to be equal to some code, that code is run when the event fires on the button. you could also set the handler property to be equal to a named function name (like we saw in build your own function). the following works just the same: const btn = document.query
selector('button'); function bgchange() { const rndcol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')'; document.body.style.backgroundcolor = rndcol; } btn.onclick = bgchange; there are many different event handler properties available. let's experiment. first, make a local copy of random-color-eventhandlerproperty.html, and open it in your browser. it's just a copy of the sim...
...And 6 more matches
Element.matches() - Web APIs
the matches() method checks to see if the element would be selected by the provided
selectorstring -- in other words -- checks if the element "is" the
selector. syntax var result = element.matches(
selectorstring); parameters
selectorstring is a string representing the
selector to test. return value result is a boolean. exceptions syntax_err the specified
selector string is invalid. example <ul id="birds"> <li>orange-winged parrot</li> <li class="endangered">philippine eagle</li> <li>great white pelican</li> </ul> <script type="text/javascript"> var birds = document.getelementsbytagname('li'); for (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('the ' + birds[i].textcontent + ' is endangered!'); } } </script> this...
...); for (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('the ' + birds[i].textcontent + ' is endangered!'); } } </script> this will log "the philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. ...
... if (birds[i].matches('.endangered')) { console.log('the ' + birds[i].textcontent + ' is endangered!'); } } </script> this will log "the philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered. ...
...And 6 more matches
CSS reference - CSS: Cascading Style Sheets
use this css reference to browse an alphabetical index of all of the standard css properties, pseudo-classes, pseudo-elements, data types, and at-rules. you can also browse key css concepts and a list of
selectors organized by type. also included is a brief dom-css / cssom reference. basic rule syntax style rule syntax style-rule ::=
selectors-list { properties-list } ... where :
selectors-list ::=
selector[:pseudo-class] [::pseudo-element] [,
selectors-list] properties-list ::= [property : value] [; properties-list] see the index of
selectors, pseudo-classes, and pseudo-elements below. the syntax for each specified value depends on the data type defined for each specified property. style rule examples strong { color: red; } div.menu-bar li:hover > ul { d...
...be aware that any syntax error in a rule definition invalidates the entire rule. invalid rules are ignored by the browser. note that css rule definitions are entirely (ascii) text-based, whereas dom-css / cssom (the rule management system) is object-based. ...
...be aware that any syntax error in a rule definition invalidates the entire rule. invalid rules are ignored by the browser. note that css rule definitions are entirely (ascii) text-based, whereas dom-css / cssom (the rule management system) is object-based. ...
...And 6 more matches
How CSS is structured - Learn web development
> </head> <body> <p>create your test html here</p> </body> </html> styles.css: /* create your test css here */ p { color: red; } when you find css that you want to experiment with, replace the html <body> contents with some html to style, and then add your test css code to your css file. as an altenative, you can also use the interactive editor below. ...
... <body> <p>create your test html here</p> </body> </html> styles.css: /* create your test css here */ p { color: red; } when you find css that you want to experiment with, replace the html <body> contents with some html to style, and then add your test css code to your css file. as an altenative, you can also use the interactive editor below. read on and have fun!
selectors a
selector targets html to apply styles to content. we have already discovered a variety of
selectors in the getting started with css tutorial. if css is not applying to content as-expected, your
selector may not match the way you think it should match. each css rule starts with a
selector—or a list of
selectors—in order to tell the browser which element or elements the rules should apply to. all the e...
...tyles to content. we have already discovered a variety of
selectors in the getting started with css tutorial. if css is not applying to content as-expected, your
selector may not match the way you think it should match. each css rule starts with a
selector—or a list of
selectors—in order to tell the browser which element or elements the rules should apply to. all the examples below are valid
selectors, or lists of
selectors. h1 a:link .manythings #onething * .box p .box p:first-child h1, h2, .intro try creating some css rules that use the
selectors above. add html to be styled by the
selectors. if any of the syntax above is not familiar, try searching mdn. note: you will learn more about
selectors in the next module: css
selectors. specificity you may encounter scenarios where two sele...
...And 5 more matches
Manipulating documents - Learn web development
ibling nodes: nodes that sit on the same level in the dom tree. for example, img and p are siblings in the above example. text node: a node containing a text string. it is useful to familiarize yourself with this terminology before working with the dom, as a number of the code terms you'll come across make use of them. you may have also come across them if you have studied css (e.g. descendant
selector, child
selector). active learning: basic dom manipulation to start learning about dom manipulation, let's begin with a practical example. take a local copy of the dom-example.html page and the image that goes along with it. add a <script></script> element just above the closing </body> tag. to manipulate an element inside the dom, you first need to select it and store a reference to it ins...
...tion, let's begin with a practical example. take a local copy of the dom-example.html page and the image that goes along with it. add a <script></script> element just above the closing </body> tag. to manipulate an element inside the dom, you first need to select it and store a reference to it inside a variable. inside your script element, add the following line: const link = document.query
selector('a'); now we have the element reference stored in a variable, we can start to manipulate it using properties and methods available to it (these are defined on interfaces like htmlanchorelement in the case of <a> element, its more general parent interface htmlelement, and node — which represents all nodes in a dom). first of all, let's change the text inside the link by updating the value of ...
...ntent = 'mozilla developer network'; we should also change the url the link is pointing to, so that it doesn't go to the wrong place when it is clicked on. add the following line, again at the bottom: link.href = 'https://developer.mozilla.org'; note that, as with many things in javascript, there are many ways to select an element and store a reference to it in a variable. ...
...And 5 more matches
The Firefox codebase: CSS Guidelines
ed values such as: vertical-align: -2px; . the reason you should avoid such "hardcoded" values is that, they don't necessarily work for all font-size configurations. avoid setting styles in javascript. it's generally better to set a class and then specify the styles in css. classlist is generally better than classname. there's less chance of overwriting an existing class. only use generic
selectors such as :last-child, when it is what you mean semantically. if not, using a semantic class name is more descriptive and usually better. boilerplate make sure each file starts with the standard copyright header (see license boilerplate). before adding more css it is good practice to check if the css that is being written is needed, it can be the case that a common component has been already ...
...space before !important. omit units on 0 values do this: margin: 0; not this: margin: 0px; use expanded syntax it is often harder to understand what the shorthand is doing and the shorthand can also hide some unwanted default values. it is good to privilege expanded syntax to make your intentions explicit. do this: border-color: red; not this: border: red; put multiple
selectors on different lines do this: h1, h2, h3 { font-family: sans-serif; text-align: center; } not this: h1, h2, h3 { font-family: sans-serif; text-align: center; } naming standards for class names lower-case-with-dashes is the most common. but camelcase is also used sometimes. try to follow the style of existing or related code. other tips assume ="true" in attribute
selectors. ...
...align: center; } not this: h1, h2, h3 { font-family: sans-serif; text-align: center; } naming standards for class names lower-case-with-dashes is the most common. but camelcase is also used sometimes. try to follow the style of existing or related code. other tips assume ="true" in attribute
selectors. example: use option[checked], not option[checked="true"]. ...
...And 5 more matches
Intersection Observer API - Web APIs
nt and its root is the intersection ratio. this is a representation of the percentage of the target element which is visible as a value between 0.0 and 1.0. creating an intersection observer create the intersection observer by calling its constructor and passing it a callback function to be run whenever a threshold is crossed in one direction or the other: let options = { root: document.query
selector('#scrollarea'), rootmargin: '0px', threshold: 1.0 } let observer = new intersectionobserver(callback, options); a threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked. intersection observer options the options object passed into the intersectionobserver() constructor let you control the circumstances under...
...nother 25%, you would specify the array [0, 0.25, 0.5, 0.75, 1]. the default is 0 (meaning as soon as even one pixel is visible, the callback will be run). a value of 1.0 means that the threshold isn't considered passed until every pixel is visible. targeting an element to be observed once you have created the observer, you need to give it a target element to watch: let target = document.query
selector('#listitem'); observer.observe(target); // the callback we setup for the observer will be executed now for the first time // it waits until we assign a target to our observer (even if the target is currently not visible) whenever the target meets a threshold specified for the intersectionobserver, the callback is invoked. the callback receives a list of intersectionobserverentry objects and th...
...the // first box's thresholds are set programmatically // since there will be so many of them (for each percentage // point). let thresholdsets = [ [], [0.5], [0.0, 0.1, 0.2, 0.3, 0.4, 0.5...
...And 5 more matches
SubtleCrypto.exportKey() - Web APIs
s example exports an aes key as an arraybuffer containing the bytes for the key. see the complete code on github. /* export the given key and write it into the "exported-key" space. ...
...the exported key is then pem-encoded. see the complete code on github. ...
...into the "exported-key" space. */ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "pkcs8", key ); const exportedasstring = ab2str(exported); const exportedasbase64 = window.btoa(exportedasstring); const pemexported = `-----begin private key-----\n${exportedasbase64}\n-----end private key-----`; const exportkeyoutput = document.query
selector(".exported-key"); exportkeyoutput.textcontent = pemexported; } /* generate a sign/verify key pair, then set up an event listener on the "export" button. */ window.crypto.subtle.generatekey( { name: "rsa-pss", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", }, ...
...And 5 more matches
SubtleCrypto.verify() - Web APIs
hod supports the same algorithms as the sign() method. examples note: you can try the working examples out on github. rsassa-pkcs1-v1_5 this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. ...
...uery
selector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set the "valid" class on the signature. * otherwise set the "invalid" class. */ async function verifymessage(publickey) { const signaturevalue = document.query
selector(".rsassa-pkcs1 .signature-value"); signaturevalue.classlist.remove("valid", "invalid"); let encoded = getmessageencoding(); let result = await window.crypto.subtle.verify( "rsassa-pkcs1-v1_5", publickey, signature, encoded ); signaturevalue.classlist.add(result ? "valid" : "invalid"); } rsa-pss this code uses a public key to verify a signature. see the complete code ...
...rsassa-pkcs1-v1_5", publickey, signature, encoded ); signaturevalue.classlist.add(result ? "valid" : "invalid"); } rsa-pss this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. ...
...And 5 more matches
<input type="button"> - HTML: Hypertext Markup Language
make buttons do anything, you have to write javascript code to do the work. ...
...ipt code to do the work. ...
...put> for which it makes sense — you use the accesskey global attribute. in this example, s is specified as the access key (you'll need to press s plus the particular modifier keys for your browser/os combination; see accesskey for a useful list of those). ...
...And 5 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
partydate=2017-06-01t08:30. note: also bear in mind that if such data is submitted via http get, the colon character will need to be escaped for inclusion in the url parameters, e.g. partydate=2017-06-01t08%3a30. see encodeuri() for one way to do this. you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var datecontrol = document.query
selector('input[type="datetime-local"]'); datecontrol.value = '2017-06-01t08:30'; there are several methods provided by javascript's date that can be used to convert numeric date information into a properly-formatted string, or you can do it manually. for example, the date.toisostring() method can be used for this purpose. additional attributes in addition to the attributes common to all <input> elemen...
...e a new <input> element, try setting its type to datetime-local, then immediately check what its type is set to. browsers that don't support datetime-local return text, since that's what datetime-local falls back to. if <input type="datetime-local"> is not supported, we hide the native picker and show the fallback picker ui (<select>) instead. ...
...immediately check what its type is set to. browsers that don't support datetime-local return text, since that's what datetime-local falls back to. if <input type="datetime-local"> is not supported, we hide the native picker and show the fallback picker ui (<select>) instead. ...
...And 5 more matches
Using the CSS Typed Object Model - Web APIs
raph with a link, as well as a definition list to which we will add all the css property / value pairs. <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add javascript to grab our unstyled link and return back a definition list of all the default css property values impacting the link using computedstylemap(). ...
...rty / value pairs. <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add javascript to grab our unstyled link and return back a definition list of all the default css property values impacting the link using computedstylemap(). ...
...d an inhertable property: p { font-weight: bold; } a { --color: red; color: var(--color); } instead of getting all the properties, we create an array of properties of interest and use the stylepropertymapreadonly.get() method to get each of their values: <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> // get the element const myelement = document.query
selector('a'); // get the <dl> we'll be populating const styleslist = document.query
selector('#regurgitation'); // retrieve all computed styles with computedstylemap() const allcomputedstyles = myelement.computedstylemap(); // array of properties we're interested in const ofinterest = ['font-weight', 'border-left-color', 'color', '--color']; // iterate through our properties of interest for ( let i = ...
...And 4 more matches
SpeechSynthesis - Web APIs
nt. inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), create a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
...stop the form submitting with preventdefault(), create a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
...reate a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
...And 4 more matches
:scope - CSS: Cascading Style Sheets
syntax :scope examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's called. ...
... syntax :scope examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's called. ...
... syntax :scope examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's called. ...
...And 4 more matches
<input type="date"> - HTML: Hypertext Markup Language
e so: <input type="date" value="2017-06-01"> the displayed date format will differ from the actual value — the displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd. you can get and set the date value in javascript with the input element's value and valueasnumber properties. for example: var datecontrol = document.query
selector('input[type="date"]'); datecontrol.value = '2017-06-01'; console.log(datecontrol.value); // prints "2017-06-01" console.log(datecontrol.valueasnumber); // prints 1496275200000, a unix timestamp this code finds the first <input> element whose type is date, and sets its value to 2017-06-01 (june 1st, 2017). it then reads that value back in string and number formats. additional attributes along w...
... the browser supports <input type="date">. we create a new <input> element, try setting its type to date, then immediately check what its type is — unsupporting browsers will return text, because the date type falls back to type text. if <input type="date"> isn't supported, we hide the native picker and show the fallback (<select>) instead. ...
...> element, try setting its type to date, then immediately check what its type is — unsupporting browsers will return text, because the date type falls back to type text. if <input type="date"> isn't supported, we hide the native picker and show the fallback (<select>) instead. ...
...And 4 more matches
Style System Overview - Archive of obsolete content
ylesheet describe in c++ what a css stylesheet can do nsistylerule describes in c++ what a css style rule can do main implementations are for css, but we have other implementations in c++ that: do what css can't do do things faster than css would css style sheets at basic level, sheet is collection of rules other special things: @import, @media, @namespace, etc. a rule is a
selector and a declaration block. a declaration block is a group of declarations. a declaration is a property and a value. p { color: green; font-size: 12em; }
selector { property: value; property: value; } css style rules what do style rules mean?
selector matches elements in the document. rule applies to matched elements. “cascaded” value for property + element: if ...
...nt: if 0 rules matching the element have the property: some properties inherit and some properties use initial value. inherited: 'font-size', 'color', etc. “reset”: 'border', 'background', etc. ...
... css style rule representation h1, h2 { color: g...
...And 3 more matches
Organizing your CSS - Learn web development
.main-nav { ... } .logo { ... } finally we will include css for specific things, broken down by the context, page or even component in which they are used. /* || store pages */ .product-listing { ... } .product-box { ... } by ordering things in this way, we at least have an idea in which part of the stylesheet we will be looking for something that we want to change. avoid overly-specific
selectors if you create very specific
selectors you will often find that you need to duplicate chunks of your css to apply the same rules to another element. for example, you might have something like the below
selector, which applies the rule to a <p> with a class of box inside an <article> with a class of main. article.main p.box { border: 1px solid #ccc; } if you then wanted to apply the same rule...
...f your css to apply the same rules to another element. for example, you might have something like the below
selector, which applies the rule to a <p> with a class of box inside an <article> with a class of main. article.main p.box { border: 1px solid #ccc; } if you then wanted to apply the same rules to something outside of main, or to something other than a <p>, you would have to add another
selector to these rules or create a whole new ruleset. instead, you could use the
selector .box to apply your rule to any element that has the class box: .box { border: 1px solid #ccc; } there will be times when making something more specific makes sense, however this will generally be an exception rather than usual practice. break large stylesheets into multiple smaller ones in particular in cases ...
... to come up with your own rules for writing css, you may benefit from adopting one of the approaches already designed by the community and tested across many projects. these methodologies are essentially css coding guides that take a very structured approach to writing and organising css. typically they tend to result in more verbose use of css than you might have if you wrote and optimised every
selector to a custom set of rules for that project. however, you do gain a lot of structure by adopting one and, as many of these systems are very widely used, other developers are more likely to understand the approach you are using and be able to write their css in the same way, rather than having to work out your own personal methodology from scratch. oocss most of the approaches that you will encou...
...And 3 more matches
Styling tables - Learn web development
a bit more predictably by default. normally, table columns tend to be sized according to how much content they contain, which produces some strange results. with table-layout: fixed, you can size your columns according to the width of their headings, and then deal with their content as appropriate. this is why we've selected the four different headings with the thead th:nth-child(n) (:nth-child)
selector ("select the nth child that is a <th> element in a sequence, inside a <thead> element") and given them set percentage widths. the entire column width follows the width of its heading, making for a nice way to size your table columns. chris coyier discusses this technique in more detail in fixed table layouts. we've coupled this with a width of 100%, meaning that the table will fill any conta...
...that make the different data rows in your table easier to parse and read. add the following css to the bottom of your style.css file: /* zebra striping */ tbody tr:nth-child(odd) { background-color: #ff33cc; } tbody tr:nth-child(even) { background-color: #e495e4; } tbody tr { background-image: url(noise.png); } table { background-color: #ff33cc; } earlier on you saw the :nth-child
selector being used to select specific child elements. it can also be given a formula as a parameter, so it will select a sequence of elements. the formula 2n-1 would select all the odd numbered children (1, 3, 5, etc.) and the formula 2n would select all the even numbered children (2, 4, 6, etc.) we've used the odd and even keywords in our code, which do exactly the same things as the aforementioned form...
...aforementioned formulae. in this case we are giving the odd and even rows different (lurid) colors. we've also added a repeating background tile to all the body rows, which is just a bit of noise (a semi-transparent .png with a bit of visual distortion on it) to provide some texture. lastly, we've given the entire table a solid background color so that browsers that don't support the :nth-child
selector still have a background for their body rows. this color explosion results in the following look: now, this may be a bit over the top and not to your taste, but the point we are trying to make here is that tables don't have to be boring and academic. styling the caption there is one last thing to do with our table — style the caption. to do this, add the following to the bottom of your st...
...And 3 more matches
CSS FAQ - Learn web development
or styling elements that must be semantically unique): using classes makes your styling extensible — even if you only have one element to style with a particular ruleset now, you might want to add more later. classes allow you to style multiple elements, therefore they can lead to shorter stylesheets, rather than having to write out the same styling information in multiple rules that use id
selectors. shorter stylesheets are more performant. class
selectors have lower specificity than id
selectors, so are easier to override if needed. note: see
selectors for more information. how do i restore the default value of a property? initially css didn't provide a "default" keyword and the only way to restore the default value of a property is to explicitly re-declare that property. for exampl...
...t: bold; } .stocksymbol { color: red; } /* other rules */ /* other rules */ /* other rules */ .stocksymbol { font-weight: normal; } <!-- most text is in bold, except "ge", which is red and not bold --> <div id="stockticker"> nys: <span class="stocksymbol">ge</span> +1.0 ... </div> to avoid this kind of error, try to define rules only once for a certain
selector, and group all rules belonging to that
selector. use of a shorthand property using shorthand properties for defining style rules is good because it uses a very compact syntax. using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values. this means that a previous rule for a single attribu...
...t: 14px arial; color: red; } <div id="stockticker"> nys: <span class="stocksymbol">ge</span> +1.0 ... </div> in the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important. ...
...And 3 more matches
A first splash into JavaScript - Learn web development
input type="text" id="guessfield" class="guessfield"> <input type="submit" value="submit guess" class="guesssubmit"> </div> <div class="resultparas"> <p class="guesses"></p> <p class="lastresult"></p> <p class="loworhi"></p> </div> <script> // your javascript goes here let randomnumber = math.floor(math.random() * 100) + 1; const guesses = document.query
selector('.guesses'); const lastresult = document.query
selector('.lastresult'); const loworhi = document.query
selector('.loworhi'); const guesssubmit = document.query
selector('.guesssubmit'); const guessfield = document.query
selector('.guessfield'); let guesscount = 1; let resetbutton; function checkguess() { let userguess = number(guessfield.value); if (guesscount...
...ss); function setgameover() { guessfield.disabled = true; guesssubmit.disabled = true; resetbutton = document.createelement('button'); resetbutton.textcontent = 'start new game'; document.body.append(resetbutton); resetbutton.addeventlistener('click', resetgame); } function resetgame() { guesscount = 1; const resetparas = document.query
selectorall('.resultparas p'); for(let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } resetbutton.parentnode.removechild(resetbutton); guessfield.disabled = false; guesssubmit.disabled = false; guessfield.value = ''; guessfield.focus(); lastresult.style.backgroundcolor = 'white'; randomnumber = math.floor(math.random(...
... won't currently do anything. the place where we'll be adding all our code is inside the <script> element at the bottom of the html: <script> // your javascript goes here </script> adding variables to store our data let's get started. first of all, add the following lines inside your <script> element: let randomnumber = math.floor(math.random() * 100) + 1; const guesses = document.query
selector('.guesses'); const lastresult = document.query
selector('.lastresult'); const loworhi = document.query
selector('.loworhi'); const guesssubmit = document.query
selector('.guesssubmit'); const guessfield = document.query
selector('.guessfield'); let guesscount = 1; let resetbutton; this section of the code sets up the variables and constants we need to store the data our program will use. variables...
...And 3 more matches
Arrays - Learn web development
concatenation, which should be familiar to you. ...
...able code <h2>live output</h2> <div class="output" style="min-height: 150px;"> <ul> </ul> <p></p> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="playable-code" style="height: 410px;width: 95%"> const list = document.query
selector('.output ul'); const totalbox = document.query
selector('.output p'); let total = 0; list.innerhtml = ''; totalbox.textcontent = ''; // number 1 'underpants:6.99' 'socks:5.99' 't-shirt:14.99' 'trousers:31.99' 'shoes:23.99'; for (let i = 0; i <= 0; i++) { // number 2 // number 3 // number 4 // number 5 let itemtext = 0; const listitem = document.createelement(...
...utionentry = jssolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 'show solution') { textarea.value = solutionentry; solution.value = 'hide solution'; } else { textarea.value = userentry; solution.value = 'show solution'; } updatecode(); }); const jssolution = 'const list = document.query
selector(\'.output ul\');\nconst totalbox = document.query
selector(\'.output p\');\nlet total = 0;\nlist.innerhtml = \'\';\ntotalbox.textcontent = \'\';\n\nlet products = [\'underpants:6.99\',\n \'socks:5.99\',\n \'t-shirt:14.99\',\n \'trousers:31.99\',\n \'shoes:23.99\'];\n\nfor(let i = 0; i < products.length; i++) {\n let subarray = products[i].split(\':\');\n let name = subarray[0];\n let price ...
...And 3 more matches
Useful string methods - Learn web development
whether the method call isn't equal to a certain result. ...
...utionentry = jssolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 'show solution') { textarea.value = solutionentry; solution.value = 'hide solution'; } else { textarea.value = userentry; solution.value = 'show solution'; } updatecode(); }); const jssolution = 'const list = document.query
selector(\'.output ul\');' + '\nlist.innerhtml = \'\';' + '\nlet greetings = [\'happy birthday!\',' + '\n \'merry christmas my love\',' + '\n \'a happy christmas to all the family\',' + '\n \'you\\\'re all i want for christmas\',' + '\n \'get well soon\'];' + '\n' + '\nfor (let i = 0; i < greetings.length; i++) {' + '\n let input = greetings...
...or even variables with a method being invoked on them. ...
...And 3 more matches
What is JavaScript? - Learn web development
javascript can do a lot more than that — let's explore what in more ...
...bs in a safe manner, but these are advanced techniques that we won't cover in this course. javascript running order when the browser encounters a block of javascript, it generally runs it in order, from top to bottom. this means that you need to be careful what order you put things in. for example, let's return to the block of javascript we saw in our first example: const para = document.query
selector('p'); para.addeventlistener('click', updatename); function updatename() { let name = prompt('enter a new name'); para.textcontent = 'player 1: ' + name; } here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updatename() code block (lines 5–8) is run. the updatename() code block (these types of reusabl...
... note: if your example doesn't seem to work, go through the steps again and check that you did everything right. did you save ...
...And 3 more matches
The JavaScript input interpreter - Firefox Developer Tools
ment. working with iframes if a page contains embedded iframes, you can use the cd() function to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. ...
...me1"; } </script> </head> <body> </body> </html> you can switch context to the iframe like this: cd("#frame1"); now you'll see that the global window's document is the iframe: and you can call the function defined in the iframe: helper commands the javascript command line provided by the web console offers a few built-in helper functions that make certain tasks easier. ...
... <body> </body> </html> you can switch context to the iframe like this: cd("#frame1"); now you'll see that the global window's document is the iframe: and you can call the function defined in the iframe: helper commands the javascript command line provided by the web console offers a few built-in helper functions that make certain tasks easier. $(
selector, element) looks up a css
selector string
selector , returning the first node descended from element that matches. if unspecified, element defaults to document. equivalent to document.query
selector() or calls the $ function in the page, if it exists. see the query
selector code snippet. $$(
selector, element) looks up a css
selector string
selector, returning an array of dom nodes descended from element that match. if unspecif...
...And 3 more matches
CSSStyleSheet.addRule() - Web APIs
the default is the string undefined. ...
...the default is the string undefined. ...
...the default is the string undefined. ...
...And 3 more matches
ARIA: grid role - Accessibility
apse: collapse; font-variant-numeric: tabular-nums; } tbody th, tbody td { padding: 5px; } tbody td { border: 1px solid #000; text-align: right; color: #767676; } tbody td[role="gridcell"] { color: #000; } tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; } } javascript var selectables = document.query
selectorall('table td[role="gridcell"]'); selectables[0].setattribute('tabindex', 0); var trs = document.query
selectorall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.query
selectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; c...
...ol = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.query
selectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.query
selector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.query
selectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.query
selector('table...
....row, 10), 0); } break; case "end": if (event.ctrlkey) { var i = maxrow; var result; do { var j = maxcol; do { result = moveto(i, j); j--; } while (result == false); i--; } while (result == false); } else { moveto(parseint(event.target.dataset.row, 10), document.query
selector('[data-row="' + event.target.dataset.row + '"]:last-of-type').dataset.col); } break; case "pageup": var i = 0; var result; do { result = moveto(i, event.target.dataset.col); i++; } while (result == false); break; case "pagedown": var i = maxrow; var result; do { result = moveto(i, event.target.dataset.col)...
...And 3 more matches
:host-context() - CSS: Cascading Style Sheets
the :host-context() css pseudo-class function selects the shadow host of the shadow dom containing the css it is used inside (so you can select a custom element from inside its shadow dom) — but only if the
selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the dom hierarchy. in other words, this allows a custom element, or anything within that custom element's shadow dom, to apply different styles based on its position within the outer dom or classes/attributes applied to ancestor elements. one typical use of this is with a descendant
selector expression — for example h1 — to select only instances of the custom element that are inside an <h1>. another typical use would be to allow inner elements to react to classes or attributes ...
... only instances of the custom element that are inside an <h1>. another typical use would be to allow inner elements to react to classes or attributes on any anscestor elements - for example, applying a different text color when a .dark-theme class is applied to <body>. note: this has no effect when used outside a shadow dom. ...
...ow root host, only if it is a descendant of the
selector argument given */ :host-context(h1) { font-weight: bold; } :host-context(main article) { font-weight: bold; } /* changes paragraph text color from black to white when a .dark-theme class is applied to the document body */ p { color: #000; } :host-context(body.dark-theme) p { color: #fff; } syntax :host-context( <compound-
selector-list> )where <compound-
selector-list> = <compound-
selector>#where <compound-
selector> = [ <type-
selector>? <subclass-
selector>* [ <pseudo-element-
selector> <pseudo-class-
selector>* ]* ]!where <type-
selector> = <wq-name> | <ns-prefix>? ...
...And 3 more matches
Border-radius generator - CSS: Cascading Style Sheets
ed) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } } var init = function init() { var elem = document.query
selectorall('.ui-input-slider'); var size = elem.length; for (var i = 0; i < size; i++) new inputslider(elem[i]); } return { init : init, setmax : setmax, setmin : setmin, setunit : setunit, getnode : getnode, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); /** * ui-buttonmanager */ var buttonmanager = (function checkboxmanager() { var subscr...
...] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); } var init = function init() { var elem = document.query
selectorall('.ui-checkbox'); var size = elem.length; for (var i = 0; i < size; i++) new checkbox(elem[i]); } return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); window.addeventlistener("load", function() { borderradius.init(); }); var borderradius = (function borderradius() { function getelembyid(id) { return document.getelementby...
...nction unsubscribe(callback) { var index = subscribers.indexof(callback); subscribers.splice(index, 1); } var notify = function notify(deltax, deltay) { for (var i in subscribers) subscribers[i](deltax, deltay); } return { init : init, subscribe : subscribe, unsubscribe : unsubscribe } })(); var subject; var units = ['px', '%']; var output = null; var unit
selector = function unit
selector(topic) { this.container = document.createelement("div"); this.select = document.createelement("select"); for (var i in units) { var option = document.createelement("option"); option.value = i; option.textcontent = units[i]; this.select.appendchild(option); } this.container.classname = 'dropdown ' + 'unit-' + topic; this.container.appendchild(this.
...And 3 more matches
<input type="month"> - HTML: Hypertext Markup Language
ormatted yyyy-mm. when the above value is submitted to the server, for example, it will look like bday-month=1978-06. ...
..."month">, we create a new <input> element, try setting its type to month, then immediately check what its type is set to. browsers that don't support type month will return text, since that's what month falls back to when not supported. if <input type="month"> is not supported, we hide the native picker and show the fallback picker ui instead. ...
... month, then immediately check what its type is set to. browsers that don't support type month will return text, since that's what month falls back to when not supported. if <input type="month"> is not supported, we hide the native picker and show the fallback picker ui instead. ...
...And 3 more matches
<input type="time"> - HTML: Hypertext Markup Language
if the time includes seconds (see using the step attribute), the format is always hh:mm:ss. you can learn more about the ...
...s <input type="time">, we create a new <input> element, try setting its type to time, then immediately check what its type is set to — non-supporting browsers will return text, because the time type falls back to type text. if <input type="time"> is not supported, we hide the native picker and show the fallback picker ui (<select>s) instead. ...
...g its type to time, then immediately check what its type is set to — non-supporting browsers will return text, because the time type falls back to type text. if <input type="time"> is not supported, we hide the native picker and show the fallback picker ui (<select>s) instead. ...
...And 3 more matches
<input type="week"> - HTML: Hypertext Markup Language
that the displayed format may differ from the actual value, which is always formatted yyyy-www. when the above value is submitted to the server, for example, browsers may display it as week 01, 2017, but the submitted value will always look like week=2017-w01. ...
...orts <input type="week">, we create a new <input> element, try setting its type to week, then immediately check what its type is set to. non-supporting browsers will return text, because the week type falls back to type text. if <input type="week"> is not supported, we hide the native picker and show the fallback picker ui (<select>s) instead. ...
...ting its type to week, then immediately check what its type is set to. non-supporting browsers will return text, because the week type falls back to type text. if <input type="week"> is not supported, we hide the native picker and show the fallback picker ui (<select>s) instead. ...
...And 3 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
ttons of the same name, even if the radio buttons are not grouped together in the source order. htmlformelement.elements when an input element is given a name, that name becomes a property of the owning form element's htmlformelement.elements property. if you have an input whose name is set to guest and another whose name is hat-size, the following code can be used: let form = document.query
selector("form"); let guestname = form.elements.guest; let hatsize = form.elements["hat-size"]; when this code has run, guestname will be the htmlinputelement for the guest field, and hatsize the object for the hat-size field. warning: avoid giving form elements a name that corresponds to a built-in property of the form, since you would then override the predefined property or method with this ref...
...input element. does nothing for inputs which aren't presented as text input fields. stepdown() decrements the value of a numeric input by one, by default, or by the specified number of units. stepup() increments the value of a numeric input by one or by the specified number of units. css inputs, being replaced elements, have a few features not applicable to non form elements. there are css
selectors that can specification target form controls based on their ui features, also known as ui pseudo-classes. the input element can also be targeted by type with attribute
selectors. there are some properties that are especially useful as well. ui pseudo-classes captions super relevant to the <input> element: pseudo-class description :enabled any currently enabled eleme...
... the checkbox is checked or not. in this example, we are styling the color and font-weight of the <label> that comes immediately after a checked input. we haven't applied any styles if the input is not checked. <input id="checkboxinput" type="checkbox"> <label for="checkboxinput">toggle the checkbox on and off</label> input:checked + label { color: red; font-weight: bold; } attribute
selectors it is possible to target different types of form controls based on their type using attribute
selectors. css attribute
selectors match elements based on either just the presence of a attribute or the value of a given attribute. /* matches a password input */ input[type="password"] {} /* matches a form control whose valid values are limited to a range of values*/ input[min][max] {} /* matches...
...And 3 more matches
CSS3 - Archive of obsolete content
y the completed modules, not necessary all with the same level number. at each point of time, a snapshot of the css standard can be defined, listing css2.1 and the mature modules. the w3 consortium periodically publishes such snapshots, like in 2007, 2010, 2015, 2017, and 2018. though today no module with a level greater than 3 is standardized, this will change in the future. some modules, like
selectors 4 or css borders and backgrounds level 4 already have an editor's draft, though they haven't yet reached the first published working draft status. css modules status completed modules a few css modules already became a standard as a w3c recommendation. these should be no more changes. css color module level 3 recommendation since june 7th, 2011 adds the opacity prop...
...lias for rgba(0,0,0,0.0). it deprecates the system-color keywords that shouldn't be used in a production environment anymore. css namespaces module recommendation since september 29th, 2011 adds the support for the xml namespaces by defining the notion of css qualified name, using the ' | ' syntax and adding the @namespace css at-rule.
selectors level 3 recommendation since september 29th, 2011 adds: substring matching attribute
selectors, e[attribute^="value"], e[attribute$="value"], e[attribute*="value"] . new pseudo-classes: :target, :enabled and :disabled, :checked, :indeterminate, :root, :nth-child and :nth-last-child, :nth-of-type and :nth-last-of-type, :last-child, :first-of-type and :last-of-type...
...t-of-type, :last-child, :first-of-type and :last-of-type, :only-child and :only-of-type,:empty, and :not. pseudo-elements are now characterized by two colons rather than one: :after becomes ::after, :before becomes ::before, :first-letter becomes ::first-letter, and :first-line becomes ::first-line. the new general sibling combinator ( h1~pre ). the next iteration of the
selectors specification is already in progress, though it still hasn't reached the first public working draft stage. media queries recommendation since june 19th, 2012 extends the former media type ( print, screen, … ) to a full language allowing queries on the device media capabilities like only screen and (color) . media queries are not only used in css document but als...
...And 2 more matches
Anonymous Content - Archive of obsolete content
they are found on the primary generating binding. explicit insertion points on other bindings are ignored. inherited insertion points are used to place the anonymous content generated by the next binding in the chain that contributes anonymous content. that binding can define inherited insertion points for its base binding as well. this pattern continues all the way up the binding chain. xpath
selectors specified using the includes attribute determine which insertion point a given child should be placed under. [actually, only tag names may be specified; see the includes attribute description in <children> element reference, bug 174614 and bug 51527.] if no attribute is specified, an insertion point is considered generic and will match on all content. the insertion point used for a given piece ...
...termine which insertion point a given child should be placed under. [actually, only tag names may be specified; see the includes attribute description in <children> element reference, bug 174614 and bug 51527.] if no attribute is specified, an insertion point is considered generic and will match on all content. the insertion point used for a given piece of content is the first encountered with a
selector whose node set matches the element when doing a depth-first walk of the content template. note that children elements are never cloned when content is generated from a template. handling dom changes insertion points continuing to be used as elements are inserted or removed from the dom. whenever an element is inserted or appended, all insertion points are checked following all the same rules t...
...or the textfield, followed by a mouseover of the button. since neither of these events constitutes a mouseover or mouseout of the file control itself, the events are not allowed to flow to the file control. if the user continues moving to the right and leaves the button, then the mouseout generated will be retargeted, since the file control will also have been exited. anonymous content and css
selectors and scopes bindings can interleave anonymous elements between the bound element and its explicit children. see insertion points for more information. in this situation, a new tree emerges that is different from the explicit content node tree. in addition to having a single explicit parent (the bound element) the explicit children also have an arbitrary set of anonymous parents (created by bindi...
...And 2 more matches
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
hus, although authors are used to thinking of these states as applying exclusively to hyperlinks, they are not so restricted by css2. any element can, in theory, be in any of the three states, and thus can be styled based on those states. this has not traditionally been the case. bare pseudo-classes the second piece of the problem comes when we consider the effects of a "bare" pseudo-class in a
selector. for example: :hover {color: red;} this is equivalent to the css2 rule: *:hover {color: red;} ..which translates as "any element that is being hovered should have its foreground colored red." thus, hovering over paragraphs, tables, headings, and any other element in a document will cause text to become red. a common variant is to use a bare class and hover pseudo-class together, like this: ...
...when they are hovered. gecko behavior in browsers based on netscape gecko builds later than 20020410 (netscape 6.1+), :hover styles can be applied to any element in a document. thus authors who have used bare pseudo-classes, or bare class-pseudo-class combinations, are at risk of seeing hover styles applied to more than just their links. the most reliable fix is to add the anchor element to the
selectors, like this: a:hover {color: red;} a.nav:hover {color: red;} in an attempt to avoid causing problems for legacy documents, browsers based on mozilla 1.0 and later (netscape 7+) include code that causes bare pseudo-classes to be restricted only to links if the document is rendered in "quirks" mode. in browsers based on the engine found in mozilla 1.3b and later, this quirk is extended to cover s...
...} a.nav:hover {color: red;} in an attempt to avoid causing problems for legacy documents, browsers based on mozilla 1.0 and later (netscape 7+) include code that causes bare pseudo-classes to be restricted only to links if the document is rendered in "quirks" mode. in browsers based on the engine found in mozilla 1.3b and later, this quirk is extended to cover
selectors that combine a bare class
selector with the :hover pseudo-class (see bug 169078 for details). named anchor problems in addition to the effects described previously, there are two other relatively common effects that authors may not expect. one is easily fixed by validation, but the other is a little more subtle. first, there is the problem of authors who open a named anchor but do not close it. for example: <a name="pagetop"> ...
...And 2 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
tack that impersonates a trusted user and sends a website unwanted commands. 55 css css, codingscripting, glossary, web, l10n:priority css (cascading style sheets) is a declarative language that controls how webpages look in the browser. 56 css object model (cssom) css, cssom, dom, glossary, web performance the css object model (cssom) is a map of all css
selectors and relevant properties for each
selector in the form of a tree, with a root node, sibling, descendant, child, and other relationship. the cssom is very similar to the document object model (dom). both of them are part of the critical rendering path which is a series of steps that must happen to properly render a website. 57 css pixel css, css pixel, glossary, height, length, pixe...
...navigating through different networks of the internet. they facilitate access to content on the world wide web. a proxy intercepts requests and serves back responses; it may forward the requests, or not (for example in the case of a cache), and it may modify it (for example changing its headers, at the boundary between two networks). ...
...of the internet. they facilitate access to content on the world wide web. a proxy intercepts requests and serves back responses; it may forward the requests, or not (for example in the case of a cache), and it may modify it (for example changing its headers, at the boundary between two networks). ...
...And 2 more matches
CSS building blocks - Learn web development
this module carries on where css first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. this module looks at the cascade and inheritance, all the
selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. the aim here is to provide you with a toolkit for writing competent css and help you understand all the essential theory, before moving on to more specific disciplines like text styling and css layout. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have: ba...
...the most essential parts of the css language. along the way you'll come across plenty of exercises to allow you to test your understanding. cascade and inheritance the aim of this lesson is to develop your understanding of some of the most fundamental concepts of css — the cascade, specificity, and inheritance — which control how css is applied to html and how conflicts are resolved. ...
...e. along the way you'll come across plenty of exercises to allow you to test your understanding. cascade and inheritance the aim of this lesson is to develop your understanding of some of the most fundamental concepts of css — the cascade, specificity, and inheritance — which control how css is applied to html and how conflicts are resolved. ...
...And 2 more matches
HTML text fundamentals - Learn web development
ue="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.query
selector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
...ue="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.query
selector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
...ue="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.query
selector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
...And 2 more matches
Client-side storage - Learn web development
. create an index.js file in the same directory as your html file. we'll start off by creating references to all the html features we need to manipulate in this example — we'll create them all as constants, as these references do not need to change in the lifecycle of the app. ...
... html file. we'll start off by creating references to all the html features we need to manipulate in this example — we'll create them all as constants, as these references do not need to change in the lifecycle of the app. ...
...eferences to all the html features we need to manipulate in this example — we'll create them all as constants, as these references do not need to change in the lifecycle of the app. ...
...And 2 more matches
Video and Audio APIs - Learn web development
tion: relative; content: attr(data-icon); color: #aaa; text-shadow: 1px 1px 0px black; } first of all, at the top of the css we use a @font-face block to import a custom web font. this is an icon font — all the characters of the alphabet equate to common icons you might want to use in an application. next we use generated content to display an icon on each button: we use the ::before
selector to display the content before each <button> element. we use the content property to set the content to be displayed in each case to be equal to the contents of the data-icon attribute. in the case of our play button, data-icon contains a capital "p". we apply the custom web font to our buttons using font-family. in this font, "p" is actually a "play" icon, so therefore the play button has a "pl...
...ne box is not obscuring another. implementing the javascript we've got a fairly complete html and css interface already; now we just need to wire up all the buttons to get the controls working. create a new javascript file in the same directory level as your index.html file. call it custom-player.js. ...
...e javascript we've got a fairly complete html and css interface already; now we just need to wire up all the buttons to get the controls working. create a new javascript file in the same directory level as your index.html file. call it custom-player.js. ...
...And 2 more matches
Handling common HTML and CSS problems - Learn web development
at html generated by some kind of third party api (generating ad banners, for example) includes a class name or id that you are already using for a different purpose. to ensure this doesn't happen, you need to research the tools you are using first and design your code around them. it is also worth "namespacing" css, e.g. if you have a widget, make sure it has a distinct class, and then start the
selectors that select elements inside the widget with this class, so conflicts are less likely. for example .audio-player ul a. validation for html, validation involves making sure all your tags are properly closed and nested, you are using a doctype, and you are using tags for their correct purpose. a good strategy is to validate your code regularly. one service that can do this is the w3c markup vali...
...pt, for them to be styleable; this is a strange quirk, and we won't bore you with the details here. for example: const asideelem = document.createelement('aside'); ... this sounds like a pain to deal with, but fortunately there is a polyfill available that does the necessary fixes for you, and more besides — see html5shiv for all the details (see manual installation for the simplest usage).
selector support of course, no css features will apply at all if you don't use the right
selectors to select the element you want to style! if you just write a
selector incorrectly so the styling isn't as expected in any browser, you'll just need to troubleshoot and work out what is wrong with your
selector. we find that it is helpful to inspect the element you are trying to style using your browser's de...
...he element you want to style! ...
...And 2 more matches
AudioParam.linearRampToValueAtTime() - Web APIs
to fade the gain value up to 1.0, and down to 0, respectively. this is pretty useful for fade in/fade out effects, although audioparam.exponentialramptovalueattime() is often said to be a bit more natural. ...
... to 0, respectively. this is pretty useful for fade in/fade out effects, although audioparam.exponentialramptovalueattime() is often said to be a bit more natural. ...
... fade in/fade out effects, although audioparam.exponentialramptovalueattime() is often said to be a bit more natural. ...
...And 2 more matches
AudioParam.setTargetAtTime() - Web APIs
ettargetattime() is used to fade the gain value up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeconstant. ...
...alue up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeconstant. ...
...ith the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeconstant. ...
...And 2 more matches
ImageCapture - Web APIs
, a mediastreamtrack extracted from a device's mediastream. the track is then used to create an imagecapture object so that takephoto() and grabframe() can be called. finally, it shows how to apply the results of these calls to a canvas object. ...
...avigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.query
selector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => console.log(error)); } function ongrabframebuttonclick() { imagecapture.grabframe() .then(imagebitmap => { const canvas = document.query
selector('#grabframecanvas'); drawcanvas(canvas, imagebitmap); }) .catch(error => console.log(error)); } function ontakephotobuttonclick() { imagecapture.takephoto() .then(blob => createimagebitmap(blob)) .then(imagebitmap => { const canvas = document.query
selector('#takephotocanvas'); drawcanvas(canvas, imagebitmap); }) .catch(error => console.log(error)); } /* utils */ funct...
... working draft initial definition. ...
...And 2 more matches
RTCPeerConnection.getStats() - Web APIs
the rtcpeerconnection method getstats() returns a promise which resolves with data providing statistics about either the overall connection or about the specified mediastreamtrack. syntax promise = rtcpeerconnection.getstats(
selector) parameters
selector optional a mediastreamtrack for which to gather statistics. if this is null (the default value), statistics will be gathered for the entire rtcpeerconnection. return value a promise which resolves with an rtcstatsreport object providing connection statistics. the contents of the report depend on the
selector as well as other details of the connection. exceptions this method does not throw exceptions; instead, it rejects the returned promise with one of the following errors: invalidaccesserror there is no rtcrtpsender or rtcrtp...
... obsolete syntax previously, getstats() used success and failure callbacks to report the results to you, instead of using a promise. ...
... obsolete syntax previously, getstats() used success and failure callbacks to report the results to you, instead of using a promise. ...
...And 2 more matches
ResizeObserver - Web APIs
der’s value is changed causing the containing <div> to change width. this shows that you can respond to changes in an element’s size, even if they have nothing to do with the viewport. we also provide a checkbox to turn the observer off and on. if it is turned off, the text will not change in response to the <div>'s width changing. ...
...ing <div> to change width. this shows that you can respond to changes in an element’s size, even if they have nothing to do with the viewport. we also provide a checkbox to turn the observer off and on. if it is turned off, the text will not change in response to the <div>'s width changing. ...
...u can respond to changes in an element’s size, even if they have nothing to do with the viewport. we also provide a checkbox to turn the observer off and on. if it is turned off, the text will not change in response to the <div>'s width changing. ...
...And 2 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
ation. the fragment shader returns the color of each vertex, interpolating as needed from the values found in the texture and applying the lighting effects. starting up and shutting down webxr upon initially loading the script, we install a handler for the load event, so that we can perform initialization. ...
...ture and applying the lighting effects. starting up and shutting down webxr upon initially loading the script, we install a handler for the load event, so that we can perform initialization. ...
...n webxr upon initially loading the script, we install a handler for the load event, so that we can perform initialization. ...
...And 2 more matches
Using the Web Speech API - Web APIs
the html element (so we can output diagnostic messages and update the app background color later on), we implement an onclick handler so that when the screen is tapped/clicked, the speech recognition service will start. this is achieved by calling speechrecognition.start(). the foreach() method is used to output colored indicators showing what colors to try saying. var diagnostic = document.query
selector('.output'); var bg = document.query
selector('html'); var hints = document.query
selector('.hints'); var colorhtml= ''; colors.foreach(function(v, i, a){ console.log(v, i); colorhtml += '<span style="background-color:' + v + ';"> ' + v + ' </span>'; }); hints.innerhtml = 'tap/click then say a color to change the background color of the app. try ' + colorhtml + '.'; document.body.onclick = fun...
... javascript that powers this app. setting variables first of all, we capture references to all the dom elements involved in the ui, but more interestingly, we capture a reference to window.speechsynthesis. this is api's entry point — it returns an instance of speechsynthesis, the controller interface for web speech synthesis. ...
...ables first of all, we capture references to all the dom elements involved in the ui, but more interestingly, we capture a reference to window.speechsynthesis. this is api's entry point — it returns an instance of speechsynthesis, the controller interface for web speech synthesis. ...
...And 2 more matches
@page - CSS: Cascading Style Sheets
an only change the margins, orphans, widows, and page breaks of the document. attempts to change any other css properties will be ignored. the @page at-rule can be accessed via the css object model interface csspagerule. note: the w3c is discussing how to handle viewport-related <length> units, vh, vw, vmin, and vmax. meanwhile do not use them within a @page at-rule. ...
... and page breaks of the document. attempts to change any other css properties will be ignored. the @page at-rule can be accessed via the css object model interface csspagerule. note: the w3c is discussing how to handle viewport-related <length> units, vh, vw, vmin, and vmax. meanwhile do not use them within a @page at-rule. ...
...ocument. attempts to change any other css properties will be ignored. the @page at-rule can be accessed via the css object model interface csspagerule. note: the w3c is discussing how to handle viewport-related <length> units, vh, vw, vmin, and vmax. meanwhile do not use them within a @page at-rule. ...
...And 2 more matches
Pseudo-classes - CSS: Cascading Style Sheets
for example, :hover can be used to change a button's color when the user's pointer hovers over it. /* any button over which the user's pointer is hovering */ button:hover { color: blue; } pseudo-classes let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator (:visited, for example), the status of its content (like :checked on certain form elements), or the position of the mouse (like :hover, which lets you know if the mouse is over an element or not). ...
...ment tree, but also in relation to external factors like the history of the navigator (:visited, for example), the status of its content (like :checked on certain form elements), or the position of the mouse (like :hover, which lets you know if the mouse is over an element or not). note: in contrast to pseudo-classes, pseudo-elements can be used to style a specific part of an element. syntax
selector:pseudo-class { property: value; } like regular classes, you can chain together as many pseudo-classes as you want in a
selector. index of standard pseudo-classes :active :any-link :blank :checked :current :default :defined :dir() :disabled :drop :empty :enabled :first :first-child :first-of-type :fullscreen :future :focus :focus-visible :focus-within :...
...:out-of-range :past :placeholder-shown :read-only :read-write :required :right :root :scope :state() :target :target-within :user-invalid :valid :visited :where() specifications specification status comment fullscreen api living standard defined :fullscreen. ...
...And 2 more matches
Syntax - CSS: Cascading Style Sheets
aces, can be put inside an html style attribute. css rulesets if style sheets could only apply a declaration to each element of a web page, they would be pretty useless. the real goal is to apply different declarations to different parts of the document. css allows this by associating conditions with declarations blocks. ...
...e sheets could only apply a declaration to each element of a web page, they would be pretty useless. the real goal is to apply different declarations to different parts of the document. css allows this by associating conditions with declarations blocks. each (valid) declaration block is preceded by one or more comma-separated
selectors, which are conditions selecting some elements of the page. ...
...ons with declarations blocks. each (valid) declaration block is preceded by one or more comma-separated
selectors, which are conditions selecting some elements of the page. a
selector group and an associated declarations block, together, are called a ruleset, or often simply a rule. a css ruleset (or rule) is visualized in the diagram below. as an element of the page may be matched by several
selectors, and therefore by several rules potentially containing a given property several times, with different values, the css standard defines which one has precedence over the other and must be applied: this is called the cascade algorithm. ...
...And 2 more matches
transition-delay - CSS: Cascading Style Sheets
ht background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:0.5s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:0.5s; transition-timing-function: linear; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-delay: 1s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; ba...
...height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:1s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:1s; transition-timing-function: linear; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-delay: 2s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; ba...
...height background-color font-size left top color; -webkit-transition-duration:2s; -webkit-transition-delay:2s; -webkit-transition-timing-function: linear; transition-property: width height background-color font-size left top color; transition-duration:2s; transition-delay:2s; transition-timing-function: linear; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-delay: 4s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; ba...
...And 2 more matches
transition-duration - CSS: Cascading Style Sheets
ound-color font-size left top transform -webkit-transform color; -webkit-transition-duration:0.5s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transformv color; transition-duration:0.5s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 1s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; ...
...ackground-color font-size left top -webkit-transform transform color; -webkit-transition-duration:1s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:1s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 2s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; ...
...ackground-color font-size left top transform -webkit-transform color; -webkit-transition-duration:2s; -webkit-transition-timing-function: ease-in-out; transition-property: width height background-color font-size left top transform -webkit-transform color; transition-duration:2s; transition-timing-function: ease-in-out; } function updatetransition() { var el = document.query
selector("div.box"); if (el) { el.classname = "box1"; } else { el = document.query
selector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); transition-duration: 4s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; ...
...And 2 more matches
Content states and the style system - Archive of obsolete content
escendants. this is an expensive operation, however, so the style system tries to minimize the number of style reresolves it does. to this end, when a <code>contentstateschanged</code> notification is dispatched for a content node the first thing that's done is to is to check whether the content state change something could affect any styles. this is done by walking the list of all css2.1 simple
selectors in all style sheets applied to the page that have a state-dependent pseudo-class as part of the
selector. this list is created during the parsing of the stylesheets involved. for each
selector in this list we check whether it might have stopped matching the node or started matching it. if that has happened, then the style could depend on the state that changed and we have to reresolve style. th...
...o the page that have a state-dependent pseudo-class as part of the
selector. this list is created during the parsing of the stylesheets involved. for each
selector in this list we check whether it might have stopped matching the node or started matching it. if that has happened, then the style could depend on the state that changed and we have to reresolve style. the way we determine whether the
selector might have stopped or started matching the node is by just checking whether it matches with the caveat that all the state-dependent pseudo-classes corresponding to the states that changed must be treated as matching (whether they actually do and whether they're negated or not). this is needed to catch both
selectors that now match and
selectors that no longer match. for example, say we have the ...
... might have stopped or started matching the node is by just checking whether it matches with the caveat that all the state-dependent pseudo-classes corresponding to the states that changed must be treated as matching (whether they actually do and whether they're negated or not). this is needed to catch both
selectors that now match and
selectors that no longer match. for example, say we have the
selectors: a:hover a:not(:hover) div:hover and the hover state on some node changes. ...
...do-classes corresponding to the states that changed must be treated as matching (whether they actually do and whether they're negated or not). this is needed to catch both
selectors that now match and
selectors that no longer match. for example, say we have the
selectors: a:hover a:not(:hover) div:hover and the hover state on some node changes. we then try matching the node against these
selectors, with the assumption that both :hover and :not(:hover) match the node. so the effect will be that of matching a node against the
selectors: a a div the code that implements this is in the
selectormatches method, which is passed the list of states that changed in the astatemask parameter. ...
Menu - Archive of obsolete content
target) remove(target) replace(target, newitems) reset() set(items) the following jetpack.menu properties can also be defined on a contextmenuset: beforehide beforeshow note that a jetpack.menu object is passed to beforehide and beforeshow, since they are called during a context menu's invocation. they may then modify the menu. individual menus are drawn from the set using on(): on(
selector) returns a new contextmenuset whose context menus are those that arise from nodes that match the given css
selector(s). the
selector must be a true css
selector, not a jquery or other type of pseudo-
selector. note:
selectors don't automatically include the children of nodes they match. for example, jetpack.menu.context.page.on("a[href]") does not match images contained in links. to match links...
...odes they match. for example, jetpack.menu.context.page.on("a[href]") does not match images contained in links. to match links and all elements contained in links, use jetpack.menu.context.page.on("a[href], a[href] *"). a future version of jetpack may change this behavior; see bug 527924. what do you think? leave a comment on that bug or send a message to the mailing list. parameters
selector one or more css
selectors. a string. examples: "a[href]", "a[href] > img", "a[href], img". return value a new contextmenuset object. jetpack.menu.context the feature's context menu. all of the feature's context menus are exposed through jetpack.menu.context, including slidebar, panel, toolbar, and status bar item context menus. a contextmenuset object. jetpack.menu.context.browser the c...
...toolbar's context menu. to work around this limitation, try using beforeshow and examining the node that the user clicked. for example, to add an item to the tabs' context menu, try: jetpack.menu.context.browser.beforeshow = function (menu, context) { menu.reset(); if (context.node.localname === "tab") menu.add("hey, a tab!"); }; (the reason this problem exists is because document.query
selectorall() does not match anonymous content in xul. many parts of firefox's interface are actually anonymous content. a future version of jetpack will hopefully provide a better solution.) jetpack.menu.context.page the content context menu. this is the context menu that appears when right-clicking on a web page. a contextmenuset object. context objects some callbacks passed into the api are called wi...
...em.label) }); add an item to the hyperlink context menu that tweets the link: jetpack.menu.context.page.on("a").add(function (context) { return { label: "tweet", command: function () jetpack.lib.twitter.statuses.update({ status: context.node.href }) }; )); add an item to the page's context menu depending on some complex criteria that can't be completely expressed via a css
selector: jetpack.menu.context.page.beforeshow = function (menu, context) { menu.reset(); if (matchesmycriteria(context)) menu.add("match!"); }; add an item to both the hyperlink context menu and the image context menu: jetpack.menu.context.page.on("a, img").set("a link or image"); add an item to the image context menu, but only for images contained in hyperlinks: jetpack.menu.context.page.on("a...
gestalt - Archive of obsolete content
description the gestalt method is a wrapper for the gestalt function of the macintosh toolbox. ...
...description the gestalt method is a wrapper for the gestalt function of the macintosh toolbox. ...
...description the gestalt method is a wrapper for the gestalt function of the macintosh toolbox. ...
...description the gestalt method is a wrapper for the gestalt function of the macintosh toolbox. ...
Skinning XUL Files by Hand - Archive of obsolete content
of the style attributes in these rules have to do with borders, font information, color, margin, native appearance. in general, these are the types of styles that should be defined only in the global skin of an application, since these are the styles that give an application a certain overall look, or skin. note that for any one class of element, there may be several pseudo-classes andattribute
selector styles defined. when you declare a button in your xul to be of a particular class, you take advantage of all of the styles defined for the various states of that button. for this reason, it can be very efficient to use button classes that appear in the global skin and to make new classes only when necessary. browse through the global skin to familiarize yourself with what's there. in the next fe...
... and used by a xul file: toolbar.nav-bar { background-image: url("chrome://navigator/skin/navbar-bg.gif"); padding: 0px; padding-bottom: 2px; } box#navbar { background-color: lightblue; } a:link { color: #fa8072; } this stylesheet exhibits three of the different types of style definitions described above. each type uses a different grouping of elements. in the first definition, the
selector "toolbar.nav-bar" is used to define style information for all xul toolbars of the class "nav-bar." unlike an id -- which is also often used as a
selector but must be unique -- a class attribute can be used on multiple xul elements you want to pick up the specified style information. a toolbar elements defined as: <toolbar class="nav-bar" id="nav3"> <toolbarbutton label="click me" /> <toolbar...
...sed as a
selector but must be unique -- a class attribute can be used on multiple xul elements you want to pick up the specified style information. a toolbar elements defined as: <toolbar class="nav-bar" id="nav3"> <toolbarbutton label="click me" /> <toolbarbutton label="don't click me" /> ... </toolbar> will be styled with the css rules that appear in the block after the toolbar.nav-bar
selector in the css example above. similarly, the next item uses the id
selector to apply style information to a single xul element. since id attribute must be unique in a document, there can only be a single element with the id "navbar", and it will pick up the style information in the block. ...
...the pseudo-class is connected to an element (or not: you can also define styles that apply to any element in the state specified by a pseudo-class) with the ":" character. ...
Accessible multimedia - Learn web development
> <div class="time">00:00</div> </div> </section> javascript basic setup we've inserted some simple control buttons below our video. these controls of course won't do anything by default; to add functionality, we will use javascript. ...
...> javascript basic setup we've inserted some simple control buttons below our video. these controls of course won't do anything by default; to add functionality, we will use javascript. ...
...imple control buttons below our video. these controls of course won't do anything by default; to add functionality, we will use javascript. ...
...ntrols of course won't do anything by default; to add functionality, we will use javascript. we will first need to store references to each of the controls — add the following to the top of your javascript file: const playpausebtn = document.query
selector('.playpause'); const stopbtn = document.query
selector('.stop'); const rwdbtn = document.query
selector('.rwd'); const fwdbtn = document.query
selector('.fwd'); const timelabel = document.query
selector('.time'); next, we need to grab a reference to the video/audio player itself — add this line below the previous lines: const player = document.query
selector('video'); this holds a reference to a htmlmediaelement object, which has several useful properties and methods available on it that can be used to wire up functionality to our buttons. b...
Images, media, and form elements - Learn web development
are quite easy to style and tend to behave just like other boxes on your page. the default styling of these elements will differ however based on the operating system and browser that your user visits the site with. in the example below we have styled some text inputs using css — you can see that things such as borders, margins and padding all apply as you would expect. we are using attribute
selectors to target the different input types. try changing how this form looks by adjusting the borders, adding background colors to the fields, and changing fonts and padding. important: you should take care when changing the styling of form elements to make sure it is still obvious to the user they are form elements. you could create a form input with no borders and background that is almost indist...
...— see test your skills: images and form elements. summary this lesson has highlighted some of the differences you will encounter when working with images, media, and other unusual elements in css. in the next article we'll look over a few tips you'll find useful when you have to style html tables. ...
...nd form elements. summary this lesson has highlighted some of the differences you will encounter when working with images, media, and other unusual elements in css. in the next article we'll look over a few tips you'll find useful when you have to style html tables. ...
...mary this lesson has highlighted some of the differences you will encounter when working with images, media, and other unusual elements in css. in the next article we'll look over a few tips you'll find useful when you have to style html tables. ...
The box model - Learn web development
u see this fairly frequently in navigation bars. the navigation below is displayed in a row using flexbox and we have added padding to the <a> element as we want to be able to change the background-color when the <a> is hovered. the padding appears to overlap the border on the <ul> element. this is because the <a> is an inline element. add display: inline-block to the rule with the .links-list a
selector, and you will see how it fixes this issue by causing the padding to be respected by other elements. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: the box model. summary that's most of what you need to un...
...you need to understand about the box model. you may want to return to this lesson in the future if you ever find yourself confused about how big boxes are in your layout. in the next lesson, we will take a look at how backgrounds and borders can be used to make your plain boxes look more interesting. ...
... model. you may want to return to this lesson in the future if you ever find yourself confused about how big boxes are in your layout. in the next lesson, we will take a look at how backgrounds and borders can be used to make your plain boxes look more interesting. ...
... return to this lesson in the future if you ever find yourself confused about how big boxes are in your layout. in the next lesson, we will take a look at how backgrounds and borders can be used to make your plain boxes look more interesting. ...
Practical positioning examples - Learn web development
tion menu, but instead of loading different web pages when they are clicked on like we've seen previously in the course, they cause different panels to be displayed on the same page. first, add the following rule at the bottom of your css to remove the default padding-left and margin-top from the unordered list: .info-box ul { padding-left: 0; margin-top: 0; } note: we are using descendant
selectors with .info-box at the start of the chain throughout this example — this is so that we can insert this feature into a page with other content already on it, without fear of interfering with the styles applied to other parts of the page. next, we'll style the horizontal tabs — the list items are all floated left to make them sit in a line together, their list-style-type is set to none to get...
...t: 0; height: 352px; padding: 10px; color: white; background-color: #a60000; } .info-box .active-panel { z-index: 1; } adding our javascript the final step to getting this feature working is to add some javascript. ...
...background-color: #a60000; } .info-box .active-panel { z-index: 1; } adding our javascript the final step to getting this feature working is to add some javascript. ...
...he checkbox is checked. (or to put it another way, when the question mark icon is clicked — remember, clicking the <label> will check the associated checkbox! we told you it was a hack.) you will learn a lot more about... setting the checked state there is one final bit of css to add — put the following at the bottom of your css: input[type=checkbox]:checked + aside { right: 0px; } the
selector is pretty complex here — we are selecting the <aside> element adjacent to the <input> element, but only when it is checked (note the use of the :checked pseudo-class to achieve this). when this is the case, we are setting the right property of the <aside> to 0px, which causes the panel to appear on the screen again (smoothly due to the transition). clicking the label again unchecks the checkbox...
How CSS works - Learn web development
memory. the dom is explained in a bit more detail in the next section. the browser then fetches most of the resources that are linked to by the html document, such as embedded images and videos ... and linked css! javascript is handled a bit later on in the process, and we won't talk about it here to keep things simpler. the browser parses the fetched css, and sorts the different rules by their
selector types into different "buckets", e.g. element, class, id, and so on. based on the
selectors it finds, it works out which rules should be applied to which nodes in the dom, and attaches style to them as required (this intermediate step is called a render tree). the render tree is laid out in the structure it should appear in after the rules have been applied to it. the visual display of the page ...
... css to our document, to style it. again, the html is as follows: <p> let's use: <span>cascading</span> <span>style</span> <span>sheets</span> </p> let's suppose we apply the following css to it: span { border: 1px solid black; background-color: lime; } the browser will parse the html and create a dom from it, then parse the css. since the only rule available in the css has a span
selector, the browser will be able to sort the css very quickly! it will apply that rule to each one of the three <span>s, then paint the final visual representation to the screen. the updated output is as follows: in our debugging css article in the next module we will be using browser devtools to debug css problems, and will learn more about how the browser interprets css. what happens if a browser...
...css. what happens if a browser encounters css it doesn't understand? in an earlier lesson i mentioned that browsers do not all implement new css at the same time. in addition, many people are not using the latest version of a browser. given that css is being developed all the time, and is therefore ahead of what browsers can recognise, you might wonder what happens if a browser encounters a css
selector or declaration it doesn't recognise. the answer is that it does nothing, and just moves on to the next bit of css! if a browser is parsing your rules, and encounters a property or value that it doesn't understand, it ignores it and moves on to the next declaration. it will do this if you have made an error and misspelled a property or value, or if the property or value is just too new and the b...
...hing, and just moves on to the next bit of css! if a browser is parsing your rules, and encounters a property or value that it doesn't understand, it ignores it and moves on to the next declaration. it will do this if you have made an error and misspelled a property or value, or if the property or value is just too new and the browser doesn't yet support it. similarly, if a browser encounters a
selector that it doesn't understand, it will just ignore the whole rule and move on to the next one. in the example below i have used the british english spelling for color, which makes that property invalid as it is not recognised. so my paragraph has not been colored blue. all of the other css have been applied however; only the invalid line is ignored. <p> i want this text to be large, bold and blue...
Example 4 - Learn web development
kground: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.query
selector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.query
selector('.optlist'); optlist.classlist.toggle('hidden'); } funct...
...remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.query
selector('.optlist'); optlist.classlist.toggle('hidden'); } function highlightoption(select, option) { var optionlist = select.query
selectorall('.option'); optionlist.foreach(function (other) { other.classlist.remove('highlight'); }); option.classlist.add('highlight'); }; function updatevalue(select, index) { var nativewidget = select.previouselementsibling; var value = select.query
selector('.value'); var optionlist = select.query
selectorall('.option'); nativewidget.selectedindex = index; value.innerhtml = opti...
...on'); nativewidget.selectedindex = index; value.innerhtml = optionlist[index].innerhtml; highlightoption(select, optionlist[index]); }; function getindex(select) { var nativewidget = select.previouselementsibling; return nativewidget.selectedindex; }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.query
selector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('load', function () { var selectlist = document.query
selectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.query
selectorall('.option'); optionlist.foreach(function (option) { option.addeventlistener('mouseover', function () { hig...
... }); }); select.addeventlistener('click', function (event) { toggleoptlist(select); }); select.addeventlistener('focus', function (event) { activeselect(select, selectlist); }); select.addeventlistener('blur', function (event) { deactivateselect(select); }); }); }); window.addeventlistener('load', function () { var selectlist = document.query
selectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.query
selectorall('.option'), selectedindex = getindex(select); select.tabindex = 0; select.previouselementsibling.tabindex = -1; updatevalue(select, selectedindex); optionlist.foreach(function (option, index) { option.addeventlistener('click', function (event) { updatevalu...
Advanced text formatting - Learn web development
solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.query
selector('.output'); const code = textarea.value; const userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value ==...
... solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.query
selector('.output'); const code = textarea.value; const userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value ==...
... solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.query
selector('.output'); const code = textarea.value; const userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value ==...
...you see it in your text editor. <var>: for specifically marking up variable names. <kbd>: for marking up keyboard (and other types of) input entered into the computer. <samp>: for marking up the output of a computer program. let's look at a few examples. ...
Build your own function - Learn web development
unction, which means we are defining a function. this is followed by the name we want to give to our function, a set of parentheses, and a set of curly braces. any parameters we want to give to our function go inside the parentheses, and the code that runs when we call the function goes inside the curly braces. ...
... msg.textcontent = 'this is a message box'; panel.appendchild(msg); const closebtn = document.createelement('button'); closebtn.textcontent = 'x'; panel.appendchild(closebtn); closebtn.onclick = function() { panel.parentnode.removechild(panel); } this is quite a lot of code to go through, so we'll walk you through it bit by bit. the first line uses a dom api function called document.query
selector() to select the <html> element and store a reference to it in a constant called html, so we can do things to it later on: const html = document.query
selector('html'); the next section uses another dom api function called document.createelement() to create a <div> element and store a reference to it in a constant called panel. this element will be the outer container of our message box. we then...
... a <div> element and store a reference to it in a constant called panel. this element will be the outer container of our message box. we then use yet another dom api function called element.setattribute() to set a class attribute on our panel with a value of msgbox. this is to make it easier to style the element — if you look at the css on the page, you'll see that we are using a .msgbox class
selector to style the message box and its contents. finally, we call a dom function called node.appendchild() on the html constant we stored earlier, which nests one element inside the other as a child of it. we specify the panel <div> as the child we want to append inside the <html> element. we need to do this as the element we created won't just appear on the page on its own — we need to specify wher...
...you sure about this?"), or the user adding a new contact and the operation completing successfully, etc. in this demo, we'll get the message box to appear when the user clicks the button. delete the previous line you added. next, we'll select the button and store a reference to it in a constant. add the following line to your code, above the function definition: const btn = document.query
selector('button'); finally, add the following line below the previous one: btn.onclick = displaymessage; in a similar way to our closebtn.onclick... line inside the function, here we are calling some code in response to a button being clicked. but in this case, instead of calling an anonymous function containing some code, we are calling our function name directly. try saving and refreshing the p...
inIDOMUtils
y, size_is(acount)] out wstring aprops); nsisupportsarray getcssstylerules(in nsidomelement aelement, [optional] in domstring apseudo); nsidomnode getparentfornode(in nsidomnode anode, in boolean ashowinganonymouscontent); unsigned long getruleline(in nsidomcssstylerule arule); unsigned long getrulecolumn(in nsidomcssstylerule arule); unsigned long get
selectorcount(in nsidomcssstylerule arule); astring get
selectortext(in nsidomcssstylerule arule, in unsigned long a
selectorindex); unsigned long long getspecificity(in nsidomcssstylerule arule, in unsigned long a
selectorindex); nsidomfontfacelist getusedfontfaces(in nsidomrange arange); bool haspseudoclasslock(in nsidomelement aelement, in domstring apseudoclass); ...
...s); boolean isignorablewhitespace(in nsidomcharacterdata adatanode); bool isinheritedproperty(in astring apropertyname); void parsestylesheet(in nsidomcssstylesheet asheet, in domstring ainput); void removepseudoclasslock(in nsidomelement aelement, in domstring apseudoclass); astring rgbtocolorname(in octet ar, in octet ag, in octet ab); bool
selectormatcheselement(in nsidomelement aelement, in nsidomcssstylerule arule, in unsigned long a
selectorindex, [optional] in domstring apseudo); void setcontentstate(in nsidomelement aelement, in unsigned long long astate); constants constant value description exclude_shorthands (1<<0) include_aliases (1<<1) content state flags the c...
...tcontentstate() sets the given element as the current owner of the specified state, and removes that state from the previous owner. void setcontentstate( in nsidomelement aelement, in unsigned long long astate ); parameters aelement the element to set the content state of. astate the content state to set. this must be one (and only one) of the values listed in content state flags. ...
...he current owner of the specified state, and removes that state from the previous owner. void setcontentstate( in nsidomelement aelement, in unsigned long long astate ); parameters aelement the element to set the content state of. astate the content state to set. this must be one (and only one) of the values listed in content state flags.
selectormatcheselement() checks if a given
selector from a style rule matches an element. bool
selectormatcheselement ( in nsidomelement aelement, in nsidomcssstylerule arule, in unsigned long a
selectorindex, in domstring apseudo optional ) parameters aelement the element to check the
selector against. arule the style rule containing the
selector. a
selectorindex the index of the
selector. apseudo optional a string specifying ...
Examine and edit CSS - Firefox Developer Tools
display based on print media rules. a warning icon appears next to unsupported css properties or rules that have invalid values. this can help you understand why certain styles are not being applied. in the following example, a spelling error, "background-colour" instead of "background-color" has made the rule invalid: rule display it displays each rule as in a stylesheet, with a list of
selectors followed by a list of property:value; declarations. highlight matched elements: next to the
selector is a target icon: click this to highlight all nodes in the page that match this
selector. overridden declaration: declarations that are overridden by later rules are crossed out. see overridden declarations. inactive rules (not shown): if a rule is inactive (e.g., padding on a :visited pse...
...erties with "font" in the name will be listed. you can also search for the values of properties: to find the rule responsible for setting the font to "lucida grande", type that in the search box. while in the computed view, you can press ctrl / cmd + f to focus the search field. once you've typed in a filter, you can press esc to remove it again. edit rules if you click on a declaration or a
selector in the rules view you can edit it and see the results immediately. you can also tab through the different existing properties and values, and start editing them by pressing enter or space. to add a new declaration to a rule, click on the last line of the rule (the line occupied by the closing brace). as you start typing a property name, you'll see a list of autocomplete suggestions. press tab to...
...e rules that describe your changes. for example, copying the changes in the preceding image, you get the following: .text-content p { box-sizing:border-box; max-width:24rem; text-decoration: underline; color: cadetblue; font-weight: bold; } add rules you can add new rules in the rules view. ...
...; } add rules you can add new rules in the rules view. just right-click to show the context menu and select "add rule". this will add a new css rule whose
selector matches the currently selected node. ...
Web Console Helpers - Firefox Developer Tools
the commands the javascript command line provided by the web console offers a few built-in helper functions that make certain tasks easier. $(
selector, element) looks up a css
selector string
selector , returning the first node descended from element that matches. if unspecified, element defaults to document. equivalent to document.query
selector() or calls the $ function in the page, if it exists. see the query
selector code snippet. $$(
selector, element) looks up a css
selector string
selector, returning an array of dom nodes descended from element that match. if unspecified, element defaults to document. this is like for document.query
selectorall(), but returns an array instead of a nodelist. $0 the currently-inspected element in the page. $_ stores the result of the last expres...
... unquoted string, blocks requests where the url contains that string. in the network monitor, the string now appears and is selected in the request blocking sidebar. unblock with :unblock. cd() switches javascript evaluation context to a different iframe in the page. this helper accepts multiple different ways of identifying the frame to switch to. you can supply any of the following: a
selector string to be passed to document.query
selector to locate the iframe element the iframe element itself the content window inside the iframe see working with iframes. clear() clears the console output area. clearhistory() just like a normal command line, the console command line remembers the commands you've typed. use this function to clear the console's command history. copy() copi...
... --filename string the name to use in saving the file. the file should have a ".png" extension. --fullpage boolean if included, the full webpage will be saved. with this parameter, even the parts of the webpage which are outside the current bounds of the window will be included in the screenshot. when used, "-fullpage" will be appended to the file name. --
selector string the css query
selector for a single element on the page. when supplied, only this element will be included in the screenshot. :unblock (starting in firefox 80) followed by an unquoted string, removes blocking for urls containing that string. in the network monitor, the string is removed from the request blocking sidebar. no error is given if the string was not previous...
...ode let's say you have a dom node with the id "title". in fact, this page you're reading right now has one, so you can open up the web console and try this right now. let's take a look at the contents of that node by using the $() and inspect() functions: inspect($("#title")) this automatically generates rich output for the object, showing you the contents of the dom node that matches the css
selector "#title", which is of course the element with id "title". you can use the up- and down-arrow keys to navigate through the output, the right-arrow key to expand an item, and the left-arrow key to collapse it. ...
AbstractRange - Web APIs
be used once, since it avoids the performance and resource impact of the more complex range interface. contents of elements when trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. in order to set a range endpoint within the text of an element, be sure to find the text node inside the element: let startelem = document.query
selector("p"); let endelem = startelem.query
selector("span"); let range = document.createrange(); range.setstart(startelem, 0); range.setend(endelem, endelem.childnodes[0].length/2); let contents = range.clonecontents(); document.body.appendchild(contents); this example creates a new range, rng, and sets its starting point to the third child node of the first element whose class is elementclass. the e...
...ed below it in the tree, potentially spawning a series of branches below as elements include other elements and text nodes. if you want to create a range that incorporates the contents of the <p> element whose contents are "a <em>very</em> interesting thing happened on the way to the forum...", you can do so like this: let prange = document.createrange(); prange.selectnodecontents(document.query
selector("#entry1 p")); since we wish to select the entire contents of the <p> element, including its descendants, this works perfectly. if we wish to instead copy the text "an interesting thing..." from the <section>'s heading (an <h2> element) through the end of the letters "ve" in the <em> within the paragraph below it, the following code would work: let r = document.createrange(); let startnode = ...
...; since we wish to select the entire contents of the <p> element, including its descendants, this works perfectly. if we wish to instead copy the text "an interesting thing..." from the <section>'s heading (an <h2> element) through the end of the letters "ve" in the <em> within the paragraph below it, the following code would work: let r = document.createrange(); let startnode = document.query
selector("section h2").childnodes[0]; r.setstart(startnode, 11); let endnode = document.query
selector("#entry1 p em").childnodes[0]; r.setend(endnode, 2); let fragment = r.clonecontents(); here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the dom hierarchy, and then only part of one of them. what should the result look like? as it turns o...
...l below the shared common parent of the topmost nodes within it. the parent <section> is not needed to replicate the cloned content, so it is isn't included. example consider this simple html fragment of html. <p><strong>this</strong> is a paragraph.</p> imagine using a range to extract the word "paragraph" from this. the code to do that looks like the following: let paranode = document.query
selector("p"); let paratextnode = paranode.childnodes[1]; let range = document.createrange(); range.setstart(paratextnode, 6); range.setend(paratextnode, paratextnode.length-1); let fragment = range.clonecontents(); document.body.appendchild(fragment); first we get references to the paragraph node itelf as well as to the second child node within the paragraph. the first child is the <strong> element. ...
AudioContext.createMediaStreamSource() - Web APIs
ed this source audio into a low pass biquadfilternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...filternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...ooster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...ge slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
AudioParam.exponentialRampToValueAtTime() - Web APIs
w the example live.) when these buttons are pressed, exponentialramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively. ...
... pressed, exponentialramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively. ...
...ed to fade the gain value up to 1.0, and down to 0, respectively. ...
...r fade in/fade out effects: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.query
selector('audio'); var pre = document.query
selector('pre'); var myscript = document.query
selector('script'); pre.innerhtml = myscript.innerhtml; var exprampplus = document.query
selector('.exp-ramp-plus'); var exprampminus = document.query
selector('.exp-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set its gain value to 0.5 var gainnode = audioctx.creategain(); // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination...
CSS.escape() - Web APIs
the css.escape() static method returns a cssomstring containing the escaped string passed as parameter, mostly for use as part of a css
selector. syntax escapedstr = css.escape(str); parameters str the cssomstring to be escaped. ...
... cssomstring to be escaped. ...
... ...
... working draft initial definition ...
Element.closest() - Web APIs
the closest() method traverses the element and its parents (heading toward the document root) until it finds a node that matches the provided
selector string. will return itself or the matching ancestor. if no such element exists, it returns null. syntax var closestelement = targetelement.closest(
selectors); parameters
selectors is a domstring containing a
selector list. ex: p:hover, .toto + q return value closestelement is the element which is the closest ancestor of the selected element. it may be null. exceptions syntaxerror is thrown if the
selectors is not a valid
selector list string. example html <article> <div id="div-01">here is div-01 <div id="div-02">here is div-02 <div id="div-03">here is div-03</div> </div> </div> </article> javascript var e...
...here it is the div-01 var r4 = el.closest(":not(div)"); // returns the closest ancestor which is not a div, here it is the outmost article polyfill for browsers that do not support element.closest(), but carry support for element.matches() (or a prefixed equivalent, meaning ie9+), a polyfill exists: if (!element.prototype.matches) { element.prototype.matches = element.prototype.msmatches
selector || element.prototype.webkitmatches
selector; } if (!element.prototype.closest) { element.prototype.closest = function(s) { var el = this; do { if (element.prototype.matches.call(el, s)) return el; el = el.parentelement || el.parentnode; } while (el !== null && el.nodetype === 1); return null; }; } however, if you really do require ie 8 support, then the follo...
...rototype.closest = function(s) { var el = this; do { if (element.prototype.matches.call(el, s)) return el; el = el.parentelement || el.parentnode; } while (el !== null && el.nodetype === 1); return null; }; } however, if you really do require ie 8 support, then the following polyfill will do the job very slowly, but eventually. ...
...; } however, if you really do require ie 8 support, then the following polyfill will do the job very slowly, but eventually. however, it will only support css 2.1
selectors in ie 8, and it can cause severe lag spikes in production websites. if (window.element && !element.prototype.closest) { element.prototype.closest = function(s) { var matches = (this.document || this.ownerdocument).query
selectorall(s), i, el = this; do { i = matches.length; while (--i >= 0 && matches.item(i) !== el) {}; } while ((i < 0) && (el = el.parentelement)); return el; }; } specifications specification status comment domthe definition of 'element.closest()' in that specification. living standard initial definition. ...
Using FormData Objects - Web APIs
ob you can invoke the blob() constructor. retrieving a formdata object from an html form to construct a formdata object that contains the data from an existing <form>, specify that form element when creating the formdata object: note: formdata will only use input fields that use the name attribute. ...
...me attribute. var formdata = new formdata(someformelement); for example: var formelement = document.query
selector("form"); var request = new xmlhttprequest(); request.open("post", "submitform.php"); request.send(new formdata(formelement)); you can also append additional data to the formdata object between retrieving it from a form and sending it, like this: var formelement = document.query
selector("form"); var formdata = new formdata(formelement); var request = new xmlhttprequest(); request.open("post", "submitform.php"); formdata.append("serialnumber", serialnumber++); request.send(formdata); this lets you augment the form's data before sending it along, to include additional information that's not necessarily user-editable. sending files using a formdata object you can also send files...
... <input type="text" name="filelabel" size="12" maxlength="32" /><br /> <label>file to stash:</label> <input type="file" name="file" required /> <input type="submit" value="stash the file!" /> </form> <div></div> then you can send it using code like the following: var form = document.forms.nameditem("fileinfo"); form.addeventlistener('submit', function(ev) { var ooutput = document.query
selector("div"), odata = new formdata(form); odata.append("customfield", "this is some extra data"); var oreq = new xmlhttprequest(); oreq.open("post", "stash.php", true); oreq.onload = function(oevent) { if (oreq.status == 200) { ooutput.innerhtml = "uploaded!"; } else { ooutput.innerhtml = "error " + oreq.status + " occurred when trying to upload your file.<br \/>"; ...
...this happens when the form is submitted, but can also be triggered by the invocation of a formdata() constructor. this allows a formdata object to be quickly obtained in response to a formdata event firing, rather than needing to put it together yourself. ...
HTMLElement: transitioncancel event - Web APIs
is canceled. see globaleventhandlers.ontransitioncancel for more information. ...
... examples this code gets an element that has a transition defined and adds a listener to the transitioncancel event: const transition = document.query
selector('.transition'); transition.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): const transition = document.query
selector('.transition'); transition.ontransitioncancel = () => { console.log('transition canceled'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform backgro...
...d: rgba(255,0,0,0); } to this, we'll add some javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend 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. ...
...javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend 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. ...
HTMLElement: transitionend event - Web APIs
ansitioned state. 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. ...
...l event is fired, the transitionend event will not fire. ...
...d: rgba(255,0,0,0); } to this, we'll add some javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend 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. ...
...javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend 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. ...
Timing element visibility with the Intersection Observer API - Web APIs
n between the ads and the <main> element's bounds. refreshintervalid used to store the interval id returned by setinterval(). this interval will be used to trigger our periodic refreshes of the ads' content. ...
...is makes sense because this function is only called if the ad is visible, even if it's just now become visible. drawing an ad's timer inside each ad, for demonstration purposes, we draw the current value of its totalviewtime, converted into minutes and seconds. this is handled by passing the ad's element into the drawadtimer() function: function drawadtimer(adbox) { let timerbox = adbox.query
selector(".timer"); let totalseconds = adbox.dataset.totalviewtime / 1000; let sec = math.floor(totalseconds % 60); let min = math.floor(totalseconds / 60); timerbox.innertext = min + ":" + sec.tostring().padstart(2, "0"); } this code finds the ad's timer using its id, "timer", and computes the number of seconds elapsed by dividing the ad's totalviewtime by 1000. then it calculates the number of...
... body: "love really does make the world go round..." }, { bgcolor: "#fee", title: "flexbox florist", body: "when life's layout gets complicated, send flowers." } ]; let adbox, title, body, timerelem; let ad = ads[math.floor(math.random()*ads.length)]; if (replacebox) { adobserver.unobserve(replacebox); adbox = replacebox; title = replacebox.query
selector(".title"); body = replacebox.query
selector(".body"); timerelem = replacebox.query
selector(".timer"); } else { adbox = document.createelement("div"); adbox.classname = "ad"; title = document.createelement("h2"); body = document.createelement("p"); timerelem = document.createelement("div"); adbox.appendchild(title); adbox.appendchild(body); adbox.appendchil...
...e out for ads which become 100% obscured and have a total visible time of at least one minute. when that happens, the replacead() function is called with that ad's element as an input, so that the old ad can be replaced with a new one. function replacead(adbox) { let visibletime; updateadtimer(adbox); visibletime = adbox.dataset.totalviewtime console.log(" replacing ad: " + adbox.query
selector("h2").innertext + " - visible for " + visibletime) loadrandomad(adbox); } replacead() begins by calling updateadtimer() on the existing ad, to ensure that its timer is up-to-date. this ensures that when we read its totalviewtime, we see the exact final value for how long the ad was visible to the user. we then report that data; in this case, by logging it to console, but in the real world, yo...
MediaStreamAudioSourceNode - Web APIs
ed this source audio into a low pass biquadfilternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...filternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...ooster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...ge slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
MediaStreamTrackAudioSourceNode - Web APIs
ed this source audio into a low pass biquadfilternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...filternode (which effectively serves as a bass booster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...ooster), then a audiodestinationnode. the range slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
...ge slider below the <video> element controls the amount of gain given to the lowpass filter — increase the value of the slider to make the audio sound more bass heavy! note: you can see this example running live, or view the source. ...
NodeList - Web APIs
although nodelist is not an array, it is possible to iterate over it with foreach(). it can also be converted to a real array using array.from(). however, some older browsers have not implemented nodelist.foreach() nor array.from(). this can be circumvented by using array.prototype.foreach() — see this document's example. live vs. static nodelists although they are both considered nodelists, there are 2 varieties of nodelist: live and static. ...
...t parent = document.getelementbyid('parent'); let child_nodes = parent.childnodes; console.log(child_nodes.length); // let's assume "2" parent.appendchild(document.createelement('div')); console.log(child_nodes.length); // outputs "3" static nodelists in other cases, the nodelist is static, where any changes in the dom does not affect the content of the collection. the ubiquitous document.query
selectorall() method returns a static nodelist. it's good to keep this distinction in mind when you choose how to iterate over the items in the nodelist, and whether you should cache the list's length. properties nodelist.length the number of nodes in the nodelist. methods nodelist.item() returns an item in the list by its index, or null if the index is out-of-bounds. an alternative to access...
... let item = mynodelist[i]; } don't use for...in to enumerate the items in nodelists, since they will also enumerate its length and item properties and cause errors if your script assumes it only has to deal with element objects. also, for..in is not guaranteed to visit the properties in any particular order. ...
...loops will loop over nodelist objects correctly: const list = document.query
selectorall('input[type=checkbox]'); for (let checkbox of list) { checkbox.checked = true; } recent browsers also support iterator methods (foreach()) as well as entries(), values(), and keys(). there is also an internet explorer-compatible way to use array.prototype.foreach for iteration: const list = document.query
selectorall('input[type=checkbox]'); array.prototype.foreach.call(list, function (checkbox) { checkbox.checked = true; }); specifications specification status comment domthe definition of 'nodelist' in that specification. living standard document object model (dom) level 3 core specificationthe definition of 'nodelist' in that specification. obsolete ...
ParentNode.replaceChildren() - Web APIs
st to transfer the options to, using the spread operator to pass in all the options contained in both constants. ...
...tions contained in both constants. ...
... living standard initial definition. ...
...st selectedtransferoptions = document.query
selectorall('#no option:checked'); const existingyesoptions = document.query
selectorall('#yes option'); yesselect.replacechildren(...selectedtransferoptions, ...existingyesoptions); }); nobtn.addeventlistener('click', () => { const selectedtransferoptions = document.query
selectorall('#yes option:checked'); const existingnooptions = document.query
selectorall('#no option'); noselect.replacechildren(...selectedtransferoptions, ...existingnooptions); }); the end result looks like this: specification specification status comment domthe definition of 'parentnode.replacechildren()' in that specification. living standard initial definition. ...
ParentNode - Web APIs
properties parentnode.childelementcount read only returns the number of children of this parentnode which are elements. ...
... properties parentnode.childelementcount read only returns the number of children of this parentnode which are elements. ...
... null if there is none. methods parentnode.append() inserts a set of node objects or domstring objects after the last child of the parentnode. domstring objects are inserted as equivalent text nodes. parentnode.prepend() inserts a set of node objects or domstring objects before the first child of the parentnode. domstring objects are inserted as equivalent text nodes. parentnode.query
selector() returns the first element with the current element as root that matches the specified group of
selectors. parentnode.query
selectorall() returns a nodelist representing a list of elements with the current element as root that matches the specified group of
selectors. parentnode.replacechildren() replaces the existing children of a node with a specified new set of children. specification ...
... specification status comment domthe definition of 'parentnode' in that specification. living standard split the elementtraversal interface into childnode and parentnode. the parentnode.firstelementchild, parentnode.lastelementchild, and parentnode.childelementcount properties are now defined on the latter. added the parentnode.children property, and the parentnode.query
selector(), parentnode.query
selectorall(), parentnode.append(), and parentnode.prepend() methods. element traversal specificationthe definition of 'elementtraversal' in that specification. obsolete added the initial definition of its properties to the elementtraversal pure interface and used it on element. ...
SubtleCrypto.encrypt() - Web APIs
enticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. examples note: you can try the working examples out on github. rsa-oaep this code fetches the contents of a text box, encodes it for encryption, and encrypts it with using rsa-oaep. see the complete code on github. ...
...n encryptmessage(publickey) { let encoded = getmessageencoding(); return window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode. see the complete code on github. ...
...dow.crypto.subtle.encrypt( { name: "aes-ctr", counter: iv, length: 128 }, key_encoded, data ); //uint8array console.log(encrypted_content); aes-cbc this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in cbc mode. see the complete code on github. ...
...yption iv = window.crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.encrypt( { name: "aes-cbc", iv }, key, encoded ); } aes-gcm this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in gcm mode. see the complete code on github. ...
SubtleCrypto.sign() - Web APIs
s note: you can try the working examples out on github. rsassa-pkcs1-v1_5 this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.query
selector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( "rsassa-pkcs1-v1_5", privatekey, encoded ); rsa-pss this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source c...
...ypto.subtle.sign( "rsassa-pkcs1-v1_5", privatekey, encoded ); rsa-pss this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.query
selector(".rsa-pss #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( { name: "rsa-pss", saltlength: 32, }, privatekey, encoded ); ecdsa this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see t...
... name: "rsa-pss", saltlength: 32, }, privatekey, encoded ); ecdsa this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.query
selector(".ecdsa #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( { name: "ecdsa", hash: {name: "sha-384"}, }, privatekey, encoded ); hmac this code fetches the contents of a text box, encodes it for signing, and signs it with a secret key. se...
...: "ecdsa", hash: {name: "sha-384"}, }, privatekey, encoded ); hmac this code fetches the contents of a text box, encodes it for signing, and signs it with a secret key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.query
selector(".hmac #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( "hmac", key, encoded ); specifications specification status comment web cryptography apithe definition of 'subtlecrypto.sign()' in that specification. recommendat...
Scissor animation - Web APIs
getrenderingcontext())) return; gl.enable(gl.scissor_test); gl.clearcolor(color[0], color[1], color[2], 1.0); // unlike the browser window, vertical position in webgl is // measured from bottom to top. in here we set the initial // position of the square to be at the top left corner of the // drawing buffer. ...
...o top. in here we set the initial // position of the square to be at the top left corner of the // drawing buffer. ...
...ener(evt.type, startanimation, false); button.addeventlistener("click", stopanimation, false); document.query
selector("strong").innerhtml = "stop"; timer = setinterval(drawanimation, 17); drawanimation(); } function stopanimation(evt) { button.removeeventlistener(evt.type, stopanimation, false); button.addeventlistener("click", startanimation, false); document.query
selector("strong").innerhtml = "start"; clearinterval(timer); } stopanimation({type: "click"}); } // variables to hold the size and velocity of the square. var size = [60, 60], velocity = 3.0; function drawanimation () { gl.scissor(position[0], position[1], size[0] , size[1]); gl.clear(gl.color_buffer_bit); // every frame the vertical position of the square is // decreased, to create th...
...m()*(gl.drawingbufferwidth - size[0]), gl.drawingbufferheight ]; // random velocity between 1.0 and 7.0 velocity = 1.0 + 6.0*math.random(); color = getrandomcolor(); gl.clearcolor(color[0], color[1], color[2], 1.0); } } function getrandomcolor() { return [math.random(), math.random(), math.random()]; } function getrenderingcontext() { var canvas = document.query
selector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { var paragraph = document.query
selector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.dr...
Using the Web Audio API - Web APIs
ossorigin attribute; see cross origin resource sharing (cors) for more information. to use all the nice things we get with the web audio api, we need to grab the source from this element and pipe it into the context we have created. lucky for us there's a method that allows us to do just that — audiocontext.createmediaelementsource: // get the audio element const audioelement = document.query
selector('audio'); // pass it into the audio context const track = audiocontext.createmediaelementsource(audioelement); note: the <audio> element above is represented in the dom by an object of type htmlmediaelement, which comes with its own set of functionality. all of this has stayed intact; we are merely allowing the sound to be available to the web audio api. controlling sound when playing soun...
... can just connect your other nodes to baseaudiocontext.destination, which handles the situation for you: track.connect(audiocontext.destination); a good way to visualise these nodes is by drawing an audio graph so you can visualize it. this is what our current audio graph looks like: now we can add the play and pause functionality. ...
...input type="range" id="volume" min="0" max="2" value="1" step="0.01"> note: range inputs are a really handy input type for updating values on audio nodes. you can specify a range's values and use them directly with the audio node's parameters. so let's grab this input's value and update the gain value when the input node has its value changed by the user: const volumecontrol = document.query
selector('#volume'); volumecontrol.addeventlistener('input', function() { gainnode.gain.value = this.value; }, false); note: the values of node objects (e.g. gainnode.gain) are not simple values; they are actually objects of type audioparam — these called parameters. this is why we have to set gainnode.gain's value property, rather than just setting the value on gain directly. this enables them ...
...ers at this time. the older factory methods are supported more widely. here our values range from -1 (far left) and 1 (far right). again let's use a range type input to vary this parameter: <input type="range" id="panner" min="-1" max="1" value="0" step="0.01"> we use the values from that input to adjust our panner values in the same way as we did before: const pannercontrol = document.query
selector('#panner'); pannercontrol.addeventlistener('input', function() { panner.pan.value = this.value; }, false); let's adjust our audio graph again, to connect all the nodes together: track.connect(gainnode).connect(panner).connect(audiocontext.destination); the only thing left to do is give the app a try: check out the final demo here on codepen. summary great! we have a boombox that plays...
Border-image generator - CSS: Cascading Style Sheets
this.topic][i](this.value); }; var createslider = function createslider(topic, label) { var slider = document.createelement('div'); slider.classname = 'ui-input-slider'; slider.setattribute('data-topic', topic); if (label !== undefined) slider.setattribute('data-info', label); new inputslider(slider); return slider; }; var init = function init() { var elem = document.query
selectorall('.ui-input-slider'); var size = elem.length; for (var i = 0; i < size; i++) new inputslider(elem[i]); }; return { init : init, setmax : setmax, setmin : setmin, setunit : setunit, setstep : setstep, getnode : getnode, getstep : getstep, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe, setprecision : setprecision, setsensivity : setsensivi...
...ibe = function unsubscribe(topic, callback) { var index = subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } }; var init = function init() { var elem, size; elem = document.query
selectorall('.ui-dropdown'); size = elem.length; for (var i = 0; i < size; i++) new dropdown(elem[i]); }; return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe, createdropdown : createdropdown }; })(); /** * ui-buttonmanager */ var buttonmanager = (function checkboxmanager() { var subscribers = []; var buttons = []; var checkbox = func...
...ubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); }; var init = function init() { var elem = document.query
selectorall('.ui-checkbox'); var size = elem.length; for (var i = 0; i < size; i++) new checkbox(elem[i]); }; return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe }; })(); window.addeventlistener("load", function() { borderimage.init(); }); var borderimage = (function borderimage() { var getelembyid = document.getelementbyid.bind(document); ...
...code['source'] = getelembyid("out-border-source"); css_code['slice'] = getelembyid("out-border-slice"); css_code['width'] = getelembyid("out-border-width"); css_code['outset'] = getelembyid("out-border-outset"); css_code['repeat'] = getelembyid("out-border-repeat"); initborderslicecontrols(); initborderwidthcontrols(); initborderoutsetcontrols(); var elem = document.query
selectorall('.guideline'); var size = elem.length; for (var i = 0; i < size; i++) new guideline(elem[i]); previewcontrol.init(); buttonmanager.subscribe('slice-fill',setborderfill); buttonmanager.subscribe('drag-subject', updatedragoption); buttonmanager.setvalue('drag-subject', false); dropdownmanager.subscribe('image-repeat-x', setborderrepeat); dropdownmanager.subscribe('...
Child combinator - CSS: Cascading Style Sheets
the child combinator (>) is placed between two css
selectors. it matches only those elements matched by the second
selector that are the direct children of elements matched by the first. /* list items that are children of the "my-things" list */ ul.my-things > li { margin: 2em; } elements matched by the second
selector must be the immediate children of the elements matched by the first
selector. this is stricter than the descendant combinator, which matches all elements matched by the second
selector for which there exists an ancestor element matched by the first
selector, regardless of the number of "hops" up the dom. ...
...ist */ ul.my-things > li { margin: 2em; } elements matched by the second
selector must be the immediate children of the elements matched by the first
selector. this is stricter than the descendant combinator, which matches all elements matched by the second
selector for which there exists an ancestor element matched by the first
selector, regardless of the number of "hops" up the dom. syntax
selector1 >
selector2 { style properties } examples css span { background-color: white; } div > span { background-color: dodgerblue; } html <div> <span>span #1, in the div. ...
... recommendation initial definition. ...
...iv > span { background-color: dodgerblue; } html <div> <span>span #1, in the div. <span>span #2, in the span that's in the div.</span> </span> </div> <span>span #3, not in the div at all.</span> result specifications specification status comment
selectors level 4the definition of 'child combinator' in that specification. working draft
selectors level 3the definition of 'child combinators' in that specification. recommendation no change. css level 2 (revision 1)the definition of 'child
selectors' in that specification. recommendation initial definition. ...
Column combinator - CSS: Cascading Style Sheets
the column combinator (||) is placed between two css
selectors. it matches only those elements matched by the second
selector that belong to the column elements matched by the first. ...
... the column combinator (||) is placed between two css
selectors. it matches only those elements matched by the second
selector that belong to the column elements matched by the first. ...
... the column combinator (||) is placed between two css
selectors. it matches only those elements matched by the second
selector that belong to the column elements matched by the first. ...
... working draft initial definition. ...
Descendant combinator - CSS: Cascading Style Sheets
the descendant combinator — typically represented by a single space ( ) character — combines two
selectors such that elements matched by the second
selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc) element matching the first
selector.
selectors that utilize a descendant combinator are called descendant
selectors. /* list items that are descendants of the "my-things" list */ ul.my-things li { margin: 2em; } the descendant combinator is technically one or more css white space characters — the space character and/or one of four control characters: carriage return, form feed, new line, and tab characters — between two
selectors in the absence of another combinator. additionally, the white space characters of which the combinator is com...
... 2em; } the descendant combinator is technically one or more css white space characters — the space character and/or one of four control characters: carriage return, form feed, new line, and tab characters — between two
selectors in the absence of another combinator. additionally, the white space characters of which the combinator is comprised may contain any number of css comments. ...
...he descendant combinator is technically one or more css white space characters — the space character and/or one of four control characters: carriage return, form feed, new line, and tab characters — between two
selectors in the absence of another combinator. additionally, the white space characters of which the combinator is comprised may contain any number of css comments. ...
...xamples css li { list-style-type: disc; } li li { list-style-type: circle; } html <ul> <li> <div>item 1</div> <ul> <li>subitem a</li> <li>subitem b</li> </ul> </li> <li> <div>item 2</div> <ul> <li>subitem a</li> <li>subitem b</li> </ul> </li> </ul> result specifications specification status comment
selectors level 4the definition of 'descendant combinator' in that specification. working draft
selectors level 3the definition of 'descendant combinator' in that specification. recommendation css level 2 (revision 1)the definition of 'descendant
selectors' in that specification. recommendation css level 1the definition of 'contextual
selectors' in that spec...
Linear-gradient Generator - CSS: Cascading Style Sheets
function unsubscribe(callback) { subscribers.indexof(callback); subscribers.splice(index, 1); }; var notify = function notify(topic, value) { if (subscribers[topic] === undefined || subscribers[topic].length === 0) return; var color = new color(value); for (var i in subscribers[topic]) subscribers[topic][i](color); }; var init = function init() { var elem = document.query
selectorall('.ui-color-picker'); var size = elem.length; for (var i = 0; i < size; i++) new colorpicker(elem[i]); }; return { init : init, color : color, rgbcolor : rgbcolor, rgbacolor : rgbacolor, hsvcolor : hsvcolor, hsvacolor : hsvacolor, hslcolor : hslcolor, hslacolor : hslacolor, setcolor : setcolor, getcolor : getcolor, subscribe : subscribe, unsubscribe : unsubscri...
...ibe = function unsubscribe(topic, callback) { var index = subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } }; var init = function init() { var elem, size; elem = document.query
selectorall('.ui-dropdown'); size = elem.length; for (var i = 0; i < size; i++) new dropdown(elem[i]); }; return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe, createdropdown : createdropdown }; })(); /** * ui-slidersmanager */ var inputslidermanager = (function inputslidermanager() { 'use strict'; var subscribers = {}; var sliders = []...
...this.topic][i](this.value); }; var createslider = function createslider(topic, label) { var slider = document.createelement('div'); slider.classname = 'ui-input-slider'; slider.setattribute('data-topic', topic); if (label !== undefined) slider.setattribute('data-info', label); new inputslider(slider); return slider; }; var init = function init() { var elem = document.query
selectorall('.ui-input-slider'); var size = elem.length; for (var i = 0; i < size; i++) new inputslider(elem[i]); }; return { init : init, setmax : setmax, setmin : setmin, setunit : setunit, setstep : setstep, getnode : getnode, getstep : getstep, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe, setprecision : setprecision, setsensivity : setsensivi...
...; var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.value); }; var init = function init() { var elem = document.query
selectorall('.ui-slider'); var size = elem.length; for (var i = 0; i < size; i++) new slider(elem[i]); }; return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe }; })(); window.addeventlistener("load", function() { lineargradienttool.init(); }); window.addeventlistener("load", function() { lineargradienttool.init(); }); var lineargradienttool =...
WebKit CSS extensions - CSS: Cascading Style Sheets
lasses :-webkit-animating-full-screen-transition :-webkit-any() :-webkit-any-link* :-webkit-autofill :-webkit-autofill-strong-password :-webkit-drag :-webkit-full-page-media :-webkit-full-screen* :-webkit-full-screen-ancestor :-webkit-full-screen-document :-webkit-full-screen-controls-hidden * now standard. note: if there is an invalid pseudo-class within in a chain or group of
selectors, the whole
selector list is invalid. pseudo-elements for web-compatibility reasons, blink, webkit, and gecko browsers treat all pseudo-elements starting with ::-webkit- as valid. ::-webkit-file-upload-button ::-webkit-inner-spin-button ::-webkit-input-placeholder ::-webkit-media-controls ::-webkit-media-controls-current-time-display ::-webkit-media-controls-enclosure ::-webkit-media...
... media features -webkit-animation -webkit-device-pixel-ratio -webkit-transform-2d -webkit-transform-3d -webkit-transition ...
... media features -webkit-animation -webkit-device-pixel-ratio -webkit-transform-2d -webkit-transform-3d -webkit-transition ...
... ::-webkit-search-results-button ::-webkit-slider-runnable-track ::-webkit-slider-thumb note: generally, if there is an invalid pseudo-element or pseudo-class within in a chain or group of
selectors, the whole
selector list is invalid. if a pseudo-element (but not pseudo-class) has a -webkit- prefix, as of firefox 63, blink, webkit and gecko browsers assume it is valid, not invalidating the
selector list. media features -webkit-animation -webkit-device-pixel-ratio -webkit-transform-2d -webkit-transform-3d -webkit-transition ...
<col> - HTML: Hypertext Markup Language
ing spaces into the textual content so that the content is justified in the cell if this attribute is not set, its value is inherited from the align of the <colgroup> element this <col> element belongs too. if there are none, the left value is assumed. note: to achieve the same effect as the left, center, right or justify values: do not try to set the text-align property on a
selector giving a <col> element. because <td> elements are not descendant of the <col> element, they won't inherit it. if the table doesn't use a colspan attribute, use the td:nth-child(an+b) css
selector. set a to zero and b to the position of the column in the table, e.g. td:nth-child(2) { text-align: right; } to right-align the second column. if the table does use a colspan attribute, the effec...
... bgcolor the background color of the table. it is a 6-digit hexadecimal rgb code, prefixed by a '#'. one of the predefined color kewords can also be used. ...
...racters instead of the bottom of them. if characters are all of the size, this has the same effect as bottom. bottom, which will put the text as close to the bottom of the cell as it is possible; middle, which will center the text in the cell; and top, which will put the text as close to the top of the cell as it is possible. note: do not try to set the vertical-align property on a
selector giving a <col> element. because <td> elements are not descendant of the <col> element, they won't inherit it. if the table doesn't use a colspan attribute, use the td:nth-child(an+b) css
selector where a is the total number of the columns in the table and b is the ordinal position of the column in the table. only after this
selector the vertical-align property can be used. if the table does u...
... width this attribute specifies a default width for each column in the current column group. ...
<colgroup> - HTML: Hypertext Markup Language
he textual content so that the content is justified in the cell char, aligning the textual content on a special character with a minimal offset, defined by the char and charoff attributes. if this attribute is not set, the left value is assumed. the descendant <col> elements may override this value using their own align attribute. note: do not try to set the text-align property on a
selector giving a <colgroup> element. because <td> elements are not descendant of the <colgroup> element, they won't inherit it. if the table doesn't use a colspan attribute, use one td:nth-child(an+b) css
selector per column, where a is the total number of the columns in the table and b is the ordinal position of this column in the table. only after this
selector the text-align property can be used. ...
... bgcolor the background color of the table. it is a 6-digit hexadecimal rgb code, prefixed by a '#'. one of the predefined color kewords can also be used. to achieve a similar effect, use the css background-color property. ...
...acters instead of the bottom of them. if characters are all of the size, this has the same effect as bottom. bottom, which will put the text as close to the bottom of the cell as it is possible; middle, which will center the text in the cell; and top, which will put the text as close to the top of the cell as it is possible. ...
...hich will center the text in the cell; and top, which will put the text as close to the top of the cell as it is possible. note: do not try to set the vertical-align property on a
selector giving a <colgroup> element. because <td> elements are not descendant of the <colgroup> element, they won't inherit it. if the table doesn't use a colspan attribute, use the td:nth-child(an+b) css
selector per column, where a is the total number of the columns in the table and b is the ordinal position of the column in the table. only after this
selector the vertical-align property can be used. if the table does use a colspan attribute, the effect can be achieved by combining adequate css attribute
selectors like [colspan=n], though this is not trivial. examples please see the <table> pa...
<template>: The Content Template element - HTML: Hypertext Markup Language
the table, with each row being constructed using the template as its basis. // test to see if the browser supports the html template element by checking // for the presence of the template element's content attribute. ...
... template as its basis. // test to see if the browser supports the html template element by checking // for the presence of the template element's content attribute. ...
...t attribute. ...
...lector('#productrow'); // clone the new row and insert it into the table var clone = template.content.clonenode(true); var td = clone.query
selectorall("td"); td[0].textcontent = "1235646565"; td[1].textcontent = "stuff"; tbody.appendchild(clone); // clone the new row and insert it into the table var clone2 = template.content.clonenode(true); td = clone2.query
selectorall("td"); td[0].textcontent = "0384928528"; td[1].textcontent = "acme kidney beans 2"; tbody.appendchild(clone2); } else { // find another way to add the rows to the table because // the html template element is not supported. } the result is the original html table, with two new rows appended to it via javascript: table { background: #000; } table td { background: #fff;...
Media - Progressive web apps (PWAs)
n mind that you can't completely control the printed format. it is impossible to anticipate every user's browser choice and settings at the time of printing. user interfaces css has some special properties for devices that support a user interface, like computer displays. these properties dynamically change the appearance of content as the user works with the interface. ...
... completely control the printed format. it is impossible to anticipate every user's browser choice and settings at the time of printing. user interfaces css has some special properties for devices that support a user interface, like computer displays. these properties dynamically change the appearance of content as the user works with the interface. ...
... e:focus any e element that has keyboard focus e:active the e element that is involved in the current user action e:link any e element that is a hyperlink to a url that the user has not visited recently e:visited any e element that is a hyperlink to a url that the user has visited recently note: the information that can be obtained from the :visited
selector is restricted in gecko 2.0. see privacy and the : visited
selector for more details. the cursor property specifies the shape of the pointer: some of the common shapes are as follows. place your mouse over the items in this list to see the actual pointer shapes in your browser:
selector selects pointer indicating a link wait indicating that the program ca...
...an arrow) an outline property creates an outline that is often used to indicate keyboard focus. its values are similar to the border property, except that you cannot specify individual sides. some other features of user interfaces are implemented using attributes, in the normal way. for example, an element that is disabled or read-only has the disabled attribute or the readonly attribute.
selectors can specify these attributes like any other attributes, by using square brackets: [disabled] or [readonly]. example these rules specify styles for a button that changes dynamically as the user interacts with it: .green-button { background-color:#cec; color:#black; border:2px outset #cec; padding: 5px 10px; } .green-button[disabled] { background-color:#cdc; color:#777; } .gr...
<feDisplacementMap> - SVG: Scalable Vector Graphics
lacementmap> svg filter primitive uses the pixel values from the image from in2 to spatially displace the image from in. the formula for the transformation looks like this: p'(x,y) ← p( x + scale * (xc(x,y) - 0.5), y + scale * (yc(x,y) - 0.5)) where p(x,y) is the input image, in, and p'(x,y) is the destination. ...
...er primitive uses the pixel values from the image from in2 to spatially displace the image from in. the formula for the transformation looks like this: p'(x,y) ← p( x + scale * (xc(x,y) - 0.5), y + scale * (yc(x,y) - 0.5)) where p(x,y) is the input image, in, and p'(x,y) is the destination. xc(x,y) and yc(x,y) are the component values of the channel designated by xchannel
selector and ychannel
selector. ...
...x,y) are the component values of the channel designated by xchannel
selector and ychannel
selector. usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in in2 scale xchannel
selector ychannel
selector dom interface this element implements the svgfedisplacementmapelement interface. example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="2" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic...
...rface this element implements the svgfedisplacementmapelement interface. example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="2" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannel
selector="r" ychannel
selector="g"/> </filter> <circle cx="100" cy="100" r="100" style="filter: url(#displacementfilter)"/> </svg> specifications specification status comment filter effects module level 1the definition of '<fedisplacementmap>' in that specification. working draft no changes scalable vector graphics (svg) 1.1 (second edition)the defi...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
in one go. there is also a performance gain from using a single file. to get the region that corresponds to a specific state of an icon, the -moz-image-region css property is used. here are some examples of how the css for a toolbarbutton would look like on the 3 major platforms. this assumes that you've set the class xs-hw-toolbarbutton to all of your buttons. windows: /* the second and third
selectors at the bottom are necessary to prevent conflicts with installed themes. */ toolbarbutton.xulschoolhello-toolbarbutton, window:not([active="true"]) toolbarbutton.xulschoolhello-toolbarbutton, toolbar[iconsize="small"] toolbarbutton.xulschoolhello-toolbarbutton { list-style-image: url("chrome://xulschoolhello-os/skin/toolbar.png"); } #xulschoolhello-hello-world-button { -moz-image-region: ...
... themes. */ toolbarbutton.xulschoolhello-toolbarbutton, window:not([active="true"]) toolbarbutton.xulschoolhello-toolbarbutton, toolbar[iconsize="small"] toolbarbutton.xulschoolhello-toolbarbutton { list-style-image: url("chrome://xulschoolhello-os/skin/toolbar.png"); } #xulschoolhello-hello-world-button { -moz-image-region: rect(0px, 16px, 16px, 0px); } mac os x: /* the second and third
selectors at the bottom are necessary to prevent conflicts with installed themes. */ toolbarbutton.xulschoolhello-toolbarbutton, window:not([active="true"]) toolbarbutton.xulschoolhello-toolbarbutton, toolbar[iconsize="small"] toolbarbutton.xulschoolhello-toolbarbutton { list-style-image: url("chrome://xulschoolhello-os/skin/toolbar.png"); } #xulschoolhello-hello-world-button { -moz-image-region: ...
...lled themes. */ toolbarbutton.xulschoolhello-toolbarbutton, window:not([active="true"]) toolbarbutton.xulschoolhello-toolbarbutton, toolbar[iconsize="small"] toolbarbutton.xulschoolhello-toolbarbutton { list-style-image: url("chrome://xulschoolhello-os/skin/toolbar.png"); } #xulschoolhello-hello-world-button { -moz-image-region: rect(0px, 16px, 16px, 0px); } linux: /* the second and third
selectors at the bottom are necessary to prevent conflicts with installed themes. */ toolbarbutton.xulschoolhello-toolbarbutton, window:not([active="true"]) toolbarbutton.xulschoolhello-toolbarbutton { list-style-image: url("chrome://xulschoolhello-os/skin/toolbar-large.png"); } #xulschoolhello-hello-world-button { -moz-image-region: rect(0px, 24px, 24px, 0px); } toolbar[iconsize="small"] #xulsch...
Styling a Tree - Archive of obsolete content
with a custom view. let's say we want a particular row to have a blue background color. this would be used to implement mozilla mail's labels feature. we'll use a property called 'makeitblue'. you can use whatever name you want. you can set multiple properties by separating them with spaces. set the property on a row or cell, as in the following example: <treerow properties="makeitblue"> css
selectors for the tree the style sheet can take this property and use it to change the appearance of the row for unread messages or labels. you can think of the properties as functioning much like style classes, although they require a somewhat more complex syntax to use in a style sheet. this is because you can specify the style for a number of parts of the cell individually. you can style not only the ...
...lthough they require a somewhat more complex syntax to use in a style sheet. this is because you can specify the style for a number of parts of the cell individually. you can style not only the cell and its text, but the twisty and indentation. ...
...the style sets style rules for particular parts of what it displays. this style rule means, inside a treechildren element, set the background color to blue for all tree rows that have the 'makeitblue' property. ...
Backgrounds and borders - Learn web development
re about any of the features we have discussed. each page on mdn has more examples of usage for you to play with and enhance your knowledge. in the next lesson, we will find out how the writing mode of your document interacts with your css. ...
... discussed. each page on mdn has more examples of usage for you to play with and enhance your knowledge. in the next lesson, we will find out how the writing mode of your document interacts with your css. ...
...n mdn has more examples of usage for you to play with and enhance your knowledge. in the next lesson, we will find out how the writing mode of your document interacts with your css. ...
Fundamental CSS comprehension - Learn web development
hanics. starting point to get this assessment started, you should: go and grab the html file for the exercise, and the associated image file, and save them in a new directory on your local computer. if you want to use your own image file and fill your own name in, you are welcome to — just make sure the image is square. grab the css resources text file — this contains a set of raw
selectors and rulesets that you'll need to study and combine to answer part of this assessment. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html and fill in the css into one of these online editors, and use this url to point the <img> element to the image file. if the online editor you are using doesn't have a separate css panel, feel free to put i...
...les for the overall page. "general page styles" would do. also add three more comments at the bottom of the css file to indicate styles specific to the setup of the card container, styles specific to the header and footer, and styles specific to the main business card contents. from now on, subsequent styles added to the stylesheet should be organized in an appropriate place. taking care of the
selectors and rulesets provided in the css resource file: next up, we'd like you to look at the four
selectors, and calculate the specificity for each one. write these down somewhere where they can be found later on, such as in a comment at the top of your css. now it's time to put the right
selector on the right rule set! you've got four pairs of
selector and ruleset to match in your css resources. d...
...ve any ancestors sitting in between them and <html> in the hierarchy that have a different font-size set on them. this could affect the values you need, although in this simple example this is not an issue.) other things to think about: you'll get bonus marks if you write your css for maximum readability, with a separate declaration on each line. you should include .card at the start of the
selector chain in all your rules, so that these rules wouldn't interfere with the styling of any other elements if the business card were to be put on a page with a load of other content. hints and tips you don't need to edit the html in any way, except to apply the css to your html. when trying to work out the em value you need to represent a certain pixel length, think about what base font size th...
Handling different text directions - Learn web development
of the block and inline direction — and how text flow changes with a change in writing mode — will be very useful going forward. it will help you in understanding css even if you never use a writing mode other than a horizontal one. in the next module we will take a good look at overflow in css. ...
......
...anges with a change in writing mode — will be very useful going forward. it will help you in understanding css even if you never use a writing mode other than a horizontal one. in the next module we will take a good look at overflow in css. ...
Overflowing content - Learn web development
summary this lesson introduced the concept of overflow. you should understand that default css avoids making overflowing content invisible. you have discovered that you can manage potential overflow, and also, that you should test work to make sure it does not accidentally cause problematic overflow. ...
...concept of overflow. you should understand that default css avoids making overflowing content invisible. you have discovered that you can manage potential overflow, and also, that you should test work to make sure it does not accidentally cause problematic overflow. ...
...u should understand that default css avoids making overflowing content invisible. you have discovered that you can manage potential overflow, and also, that you should test work to make sure it does not accidentally cause problematic overflow. ...
Sizing items in CSS - Learn web development
: sizing. summary this lesson has given you a rundown of some key issues that you might run into when sizing things on the web. when you move onto css layout, sizing will become very important in mastering the different layout methods, so it is worth understanding the concepts here before moving on. ...
...given you a rundown of some key issues that you might run into when sizing things on the web. when you move onto css layout, sizing will become very important in mastering the different layout methods, so it is worth understanding the concepts here before moving on. ...
...some key issues that you might run into when sizing things on the web. when you move onto css layout, sizing will become very important in mastering the different layout methods, so it is worth understanding the concepts here before moving on. ...
CSS values and units - Learn web development
ch property has a defined list of allowed values, and each value has a definition explaining what the sub-values are. you can then look up the specifics here on mdn. ...
...lowed values, and each value has a definition explaining what the sub-values are. you can then look up the specifics here on mdn. ...
...value has a definition explaining what the sub-values are. you can then look up the specifics here on mdn. ...
Styling links - Learn web development
illa firefox</a>, <a href="#">google chrome</a>, and <a href="#">microsoft edge</a>.</p> putting the two together gives us this result: so what did we do here? this certainly looks different to the default styling, but it still provides a familiar enough experience for users to know what's going on: the first two rules are not that interesting to this discussion. the third rule uses the a
selector to get rid of the default text underline and focus outline (which varies across browsers anyway), and adds a tiny amount of padding to each link — all of this will become clear later on. next, we use the a:link and a:visited
selectors to set a couple of color variations on unvisited and visited links, so they are distinct. the next two rules use a:focus and a:hover to set focused and hovered ...
...{ } a:active { }</textarea> <h2>output</h2> <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div> <div class="controls"> <input id="reset" type="button" value="reset" style="margin: 10px 10px 0 0;"> <input id="solution" type="button" value="show solution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlinput = document.query
selector(".html-input"); var cssinput = document.query
selector(".css-input"); var reset = document.getelementbyid("reset"); var htmlcode = htmlinput.value; var csscode = cssinput.value; var output = document.query
selector(".output"); var solution = document.getelementbyid("solution"); var styleelem = document.createelement('style'); var headelem = document.query
selector('head'); headelem.appendchild(styl...
... how did we select just external links? well, if you are writing your html links properly, you should only be using absolute urls for external links — it is more efficient to use relative links to link to other parts of your own site (as with the first link). the text "http" should therefore only appear in external links (like the second and third ones), and we can select this with an attribute
selector: a[href*="http"] selects <a> elements, but only if they have an href attribute with a value that contains "http" somewhere inside it. so that's it — try revisiting the active learning section above and trying this new technique out! note: the href values look strange — we've used dummy links here that don't really go anywhere. the reason for this is that if we used real links, you would be...
What are browser developer tools? - Learn web development
tml (sometimes add attribute/edit text). lets you change the html and see the results on the fly. very useful for debugging and testing. :hover/:active/:focus. forces element states to be toggled on, so you can see what their styling would look like. copy/copy as html. copy the currently selected html. some browsers also have copy css path and copy xpath available, to allow you to copy the css
selector or xpath expression that would select the current html element. try editing some of your dom now. double-click an element, or right-click it and choose edit as html from the context menu. you can make any changes you'd like, but you cannot save your changes. exploring the css editor by default, the css editor displays the css rules applied to the currently selected element: these features ...
... using the menu command: menu ➤ web developer ➤ web console, or tools ➤ web developer ➤ web console. on other browser, open the developer tools and then click the console tab. this will give you a window like the following: to see what happens, try entering the following snippets of code into the console one by one (and then pressing enter): alert('hello!'); document.query
selector('html').style.backgroundcolor = 'purple'; const mywordmark = document.createelement('img'); mywordmark.setattribute('src','https://blog.mozilla.org/press/wp-content/themes/onemozilla/img/mozilla-wordmark.png'); document.query
selector('h1').appendchild(mywordmark); now try entering the following incorrect versions of the code and see what you get. alert('hello!); document.che...
...tml').style.backgroundcolor = 'purple'; const mywordmark = document.createelement('img'); mywordmark.setattribute('src','https://blog.mozilla.org/press/wp-content/themes/onemozilla/img/mozilla-wordmark.png'); document.query
selector('h1').appendchild(mywordmark); now try entering the following incorrect versions of the code and see what you get. alert('hello!); document.cheese
selector('html').style.backgroundcolor = 'purple'; const mywordmark = document.createelement('img'); mybanana.setattribute('src','https://blog.mozilla.org/press/wp-content/themes/onemozilla/img/mozilla-wordmark.png'); document.query
selector('h1').appendchild(mywordmark); you'll start to see the kind of errors that the browser returns. often these errors are fairly cryptic, but it should be prett...
Example 3 - Learn web development
kground: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.query
selector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.query
selector('.optlist'); optlist.classlist.toggle('hidden'); } funct...
...remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.query
selector('.optlist'); optlist.classlist.toggle('hidden'); } function highlightoption(select, option) { var optionlist = select.query
selectorall('.option'); optionlist.foreach(function (other) { other.classlist.remove('highlight'); }); option.classlist.add('highlight'); }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.query
selector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('l...
...) { other.classlist.remove('highlight'); }); option.classlist.add('highlight'); }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.query
selector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('load', function () { var selectlist = document.query
selectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.query
selectorall('.option'); optionlist.foreach(function (option) { option.addeventlistener('mouseover', function () { highlightoption(select, option); }); }); select.addeventlistener('click', function (event) { toggleoptlist(select); }, false); select.addeventlis...
Example 5 - Learn web development
kground: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.query
selector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.query
selector('.optlist'); optlist.classlist.toggle('hidden'); } funct...
...remove('active'); } function activeselect(select, selectlist) { if (select.classlist.contains('active')) return; selectlist.foreach(deactivateselect); select.classlist.add('active'); }; function toggleoptlist(select, show) { var optlist = select.query
selector('.optlist'); optlist.classlist.toggle('hidden'); } function highlightoption(select, option) { var optionlist = select.query
selectorall('.option'); optionlist.foreach(function (other) { other.classlist.remove('highlight'); }); option.classlist.add('highlight'); }; function updatevalue(select, index) { var nativewidget = select.previouselementsibling; var value = select.query
selector('.value'); var optionlist = select.query
selectorall('.option'); optionlist.foreach(function (other) { other.setattribute...
...ue'); nativewidget.selectedindex = index; value.innerhtml = optionlist[index].innerhtml; highlightoption(select, optionlist[index]); }; function getindex(select) { var nativewidget = select.previouselementsibling; return nativewidget.selectedindex; }; // ------------- // // event binding // // ------------- // window.addeventlistener("load", function () { var form = document.query
selector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); window.addeventlistener('load', function () { var selectlist = document.query
selectorall('.select'); selectlist.foreach(function (select) { var optionlist = select.query
selectorall('.option'), selectedindex = getindex(select); select.tabindex = 0; select.previouselementsibling.tabindex =...
Using data attributes - Learn web development
s out in javascript is also very simple. you could use getattribute() with their full html name to read them, but the standard defines a simpler way: a domstringmap you can read out via a dataset property. to get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelcase). const article = document.query
selector('#electric-cars'); article.dataset.columns // "3" article.dataset.indexnumber // "12314" article.dataset.parent // "cars" each property is a string and can be read and written. in the above case setting article.dataset.columns = 5 would change that attribute to "5". css access note that, as data attributes are plain html attributes, you can even access them from css. for example to show the p...
...ritten. in the above case setting article.dataset.columns = 5 would change that attribute to "5". css access note that, as data attributes are plain html attributes, you can even access them from css. ...
... content: attr(data-parent); } you can also use the attribute
selectors in css to change styles according to the data: article[data-columns='3'] { width: 400px; } article[data-columns='4'] { width: 600px; } you can see all this working together in this jsbin example. data attributes can also be stored to contain information that is constantly changing, like scores in a game. using the css
selectors and javascript access here this allows you to build some nifty effects without having to write your own display routines. see this screencast for an example using generated content and css transitions (jsbin example). data values are strings. number values must be quoted in the
selector for the styling to take effect. issues do not store content that should be visible and accessible in data a...
Getting started with HTML - Learn web development
font-family: 'open sans light',helvetica,arial,sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.query
selector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
...ue="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.query
selector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
...sans-serif; } h1 { color: blue; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } img { max-width: 100%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.query
selector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
Introduction to web APIs - Learn web development
indow.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); next, we create constants that store references to our <audio>, <button>, and <input> elements, and use the audiocontext.createmediaelementsource() method to create a mediaelementaudiosourcenode representing the source of our audio — the <audio> element will be played from: const audioelement = document.query
selector('audio'); const playbtn = document.query
selector('button'); const volumeslider = document.query
selector('.volume'); const audiosource = audioctx.createmediaelementsource(audioelement); next up we include a couple of event handlers that serve to toggle between play and pause when the button is pressed and reset the display back to the beginning when the song has finished playing: // play/pause ...
... audiocontext object, which needs to be used to do any audio manipulation whatsoever. the document object model (dom) api also has a simple entry point — its features tend to be found hanging off the document object, or an instance of an html element that you want to affect in some way, for example: const em = document.createelement('em'); // create a new em element const para = document.query
selector('p'); // reference an existing p element em.textcontent = 'hello there!'; // give em some text content para.appendchild(em); // embed em inside para the canvas api also relies on getting a context object to use to manipulate things, although in this case, it's a graphical context rather than an audio context. its context object is created by getting a reference to the <canvas> element you want t...
...nt para.appendchild(em); // embed em inside para the canvas api also relies on getting a context object to use to manipulate things, although in this case, it's a graphical context rather than an audio context. ...
Implementing feature detection - Learn web development
he second <link> element, but let's instead implement some javascript to automatically swap them as needed. first, remove the contents of the second <link> element's href attribute. we will fill this in dynamically later on. next, add a <script></script> element at the bottom of your body (just before the closing </body> tag). give it the following contents: const conditional = document.query
selector('.conditional'); const testelem = document.createelement('div'); if (testelem.style.flex !== undefined && testelem.style.flexflow !== undefined) { conditional.setattribute('href', 'flex-layout.css'); } else { conditional.setattribute('href', 'float-layout.css'); } here we are grabbing a reference to the second <link> element, and creating a <div> element as part of our test. in our condit...
...n a single css file, cutting down on http requests. the problem here is browser support — @supports is not supported at all in ie, and only supported in very recent versions of safari/ios webkit (9+/9.2+), whereas the javascript version should work in much older browsers (probably back to ie8 or 9, although older versions of ie will have additional problems, such as not supporting document.query
selector, and having a messed up box model). javascript we already saw an example of a javascript feature detection test earlier on. generally, such tests are done via one of the following common patterns: summary of javascript feature detection techniques feature detection type explanation example if member in object check whether a certain method or property (typically...
...so here we're applying the top set of rules only to browsers that do support flexbox, and the bottom set of rules only to browsers that don't (no-flexbox). note: bear in mind that all of modernizr's html and javascript feature tests are also reported in these class names, so you can quite happily apply css selectively based on whether the browser supports html or javascript features, if neede...
Mozilla Quirks Mode Behavior
has been adopted in standards mode. the scrollleft, scrolltop, scrollwidth, and scrollheight properties are relative to body in quirks mode (instead of html) (bug 211030). html (1-7) and css (xx-small - xx-large) font sizes are calculated slightly differently (see bug 18136). the :hover and :active pseudo-classes will only be applied to links, and only if there is no other pseudo-class in the
selector. to match other elements, the
selector must include a tag name, id, class or attribute. prior to gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3), there was no class check, so the :hover pseudoclass was not applied to class
selectors; for example, .someclass:hover did not work. prior to gecko 36, it also applied to images, and form controls but the quirk has been adapted to match the...
... quirks mode has document.all support (undetected). images (img elements) without alt attributes sometimes display placeholder icons in quirks mode. ...
... quirks mode has document.all support (undetected). images (img elements) without alt attributes sometimes display placeholder icons in quirks mode. ...
Migrating from Firebug - Firefox Developer Tools
les view provides an auto-completion for the css property names and their values. a few property values are not auto-completed yet, which is tracked in bug 1337918. copy & paste css firebug's style side panel as well as the devtools' rules side panel provide options within their context menus to copy the css rule or the style declarations. the devtools additionally provide an option to copy the
selector of a rule and copy disabled property declarations as commented out. they are missing the option to copy the whole style declaration, though this can be achieved by selecting them within the panel and copying the selection by pressing ctrl+c or via the context menu. the rules side panel of the devtools is smarter when it comes to pasting css into it. you can paste whole style declarations into an...
... enabled via the break on mutate button, or individually for each element and for different types of changes like attribute changes, content changes or element removal. unfortunately, the devtools do not have this feature yet (see bug 1004678). to stop the script execution there, you need to set a breakpoint on the line with the modification within the debugger panel. search for elements via css
selectors or xpaths firebug allows to search for elements within the html panel via css
selectors or xpaths. also the devtools' inspector panel allows to search for css
selectors. it even displays a list with matching ids or classes. searching by xpaths is not supported though (see bug 963933. debugger what's the script panel in firebug, is the debugger panel in the devtools. both allow you to debug ja...
...irebug's css panel offers three different ways for editing style sheets. the default one is to edit them inline like within the style side panel. furthermore it has a source and a live edit mode, which allow to edit the selected style sheet like within a text editor. the style editor of the devtools only has one way to edit style sheets, which corresponds to firebug's live edit mode. try out css
selectors firebug's
selectors side panel provides a way to validate a css
selector. it lists all elements matching the entered
selector. the devtools don't have this feature yet, but it's requested in bug 1323746. searching within the style sheets firebug allows to search within the style sheets via the search field. the style editor in the devtools also provides a way to search within a style sheet, t...
Examine and edit HTML - Firefox Developer Tools
he page. the breadcrumbs bar has its own keyboard shortcuts. searching the page inspector's search box matches all markup in the current document and in any frames. to start searching the markup, click in the search box to expand it or press ctrl + f , or cmd + f on a mac. there are three types of searches that are performed automatically depending on what you enter, a full text search, a css
selector search, and an xpath search. full text search the full text search will always be executed, independently of what you enter. that allows you to find css
selectors and xpath expressions occurring within the text. css
selector search you can search elements by entering a css
selector. as you type, an autocomplete popup shows any class or id attributes that match the current search term: pre...
...add attribute copy attribute value edit attribute remove attribute break on ... ...
...itor" option only appears when you context-click over the top of a link to a css file. context menu reference edit as html edit the element's html. (copy) inner html copy the inner html for the element. (copy) outer html copy the outer html for the element. pressing ctrl + c (or cmd + c on a mac) also performs this action. (copy) unique
selector/css
selector copy a css
selector that uniquely selects the element. (copy) css path copy a css
selector that represents the full path to the element. (copy) image data-url copy image as a data:// url, if the selected element is an image. (copy) attribute copy the attribute of the element. show dom properties open the split console and enter the c...
AudioBuffer.getChannelData() - Web APIs
on will be thrown. return value a float32array. example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. ...
...array. example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. ...
...e create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. ...
AudioContext.createMediaElementSource() - Web APIs
is invoked, which calculates the current gain as a ratio of mouse y position divided by overall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view the source. ...
...in as a ratio of mouse y position divided by overall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view the source. ...
...verall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view the source. ...
AudioProcessingEvent - Web APIs
udioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...oprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...h channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
AudioTrackList: change event - Web APIs
the change event is fired when an audio track is enabled or disabled, for example by changing the track's enabled property. ...
... no interface event event handler property onchange examples using addeventlistener(): const videoelement = document.query
selector('video'); videoelement.audiotracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `enabled` will trigger the `change` event const toggletrackbutton = document.query
selector('.toggle-track'); toggletrackbutton.addeventlistener('click', () => { const track = videoelement.audiotracks[0]; track.enabled = !track.enabled; }); using the onchange event handler property: const videoelement = document.query
selector('video'); videoelement.audiotracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; // changing the value of `enabled` will trigg...
... living standard ...
BaseAudioContext.createBufferSource() - Web APIs
ebuffersource(); returns an audiobuffersourcenode. example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. note: you can also run the code live, or view the source. ...
...rcenode. example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. note: you can also run the code live, or view the source. ...
...a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. note: you can also run the code live, or view the source. ...
BaseAudioContext.createScriptProcessor() - Web APIs
udioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...oprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...h channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
BaseAudioContext.createStereoPanner() - Web APIs
we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
... value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
... pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
BatteryManager.onlevelchange - Web APIs
yntax navigator.battery.onlevelchange = funcref where battery is a batterymanager object, and funcref is a function to be called when the levelchange event occurs. ...
...funcref is a function to be called when the levelchange event occurs. ...
... id="statebaterry">(charging state unknown)</div> javascript navigator.getbattery().then(function(battery) { battery.onlevelchange = function(){ document.query
selector('#level').textcontent = battery.level; if(battery.charging) { document.query
selector('#statebaterry').textcontent = "charging time: " + (battery.chargingtime / 60); } else { document.query
selector('#statebaterry').textcontent = "discharging time: " + (battery.dischargingtime / 60); } }; }); specifications specification status comment battery status api candidate recommendation initial definition ...
CSSStyleDeclaration.setProperty() - Web APIs
ive example at the end of this section). we know that the rule we want to alter to do this is contained inside the second stylesheet applied to the page, so we grab a reference to it using document.stylesheets[1]. we then loop through the different rules contained inside the stylesheet, which are contained in the array found at stylesheet.cssrules; for each one, we check whether its cssstylerule.
selectortext property is equal to the
selector .box p, which indicates it is the one we want. if so, we store a reference to this cssstylerule object in a variable. we then use three functions to generate random values for the properties in question, and update the rule with these values. in each case, this is done with the setproperty() method, for example boxpararule.style.setproperty('border', newbord...
...height: 30px; line-height: 30px; } .box { display: flex; justify-content: center; align-items: center; height: calc(100% - 70px); } .box p { width: 50%; text-align: center; font-weight: bold; font-size: 40px; height: 150px; line-height: 150px; background: red; border: 5px solid purple; color: white; transition: all 1s; } javascript const borderbtn = document.query
selector('.border'); const bgcolorbtn = document.query
selector('.bgcolor'); const colorbtn = document.query
selector('.color'); const box = document.query
selector('.box'); function random(min,max) { const num = math.floor(math.random()*(max-min)) + min; return num; } function randomcolor() { return 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + random(0,255) + ')'; } const stylesheet = do...
...t box = document.query
selector('.box'); function random(min,max) { const num = math.floor(math.random()*(max-min)) + min; return num; } function randomcolor() { return 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + random(0,255) + ')'; } const stylesheet = document.stylesheets[1]; let boxpararule; for(let i = 0; i < stylesheet.cssrules.length; i++) { if(stylesheet.cssrules[i].
selectortext === '.box p') { boxpararule = stylesheet.cssrules[i]; } } function setrandomborder() { const newborder = random(1, 50) + 'px solid ' + randomcolor(); boxpararule.style.setproperty('border', newborder); } function setrandombgcolor() { const newbgcolor = randomcolor(); boxpararule.style.setproperty('background-color', newbgcolor); } function setrandomcolor() { const newcolor ...
Using channel messaging - Web APIs
the channel in the main page of the demo, we have a simple form with a text input for entering messages to be sent to an <iframe>. we also have a paragraph which we will use later on to display confirmation messages that we will receive back from the <iframe>. ...
...ave a simple form with a text input for entering messages to be sent to an <iframe>. we also have a paragraph which we will use later on to display confirmation messages that we will receive back from the <iframe>. ...
...we are transferring messagechannel.port2 to the iframe, so it can be used to communicate with the main page. when our button is clicked, we prevent the form from submitting as normal and then send the value entered in our text input to the iframe via the messagechannel. ...
Document.getElementsByClassName() - Web APIs
only elements with all of the classnames specified are selected. html <span class="orange fruit">orange fruit</span> <span class="orange juice">orange juice</span> <span class="apple juice">apple juice</span> <span class="foo bar">something random</span> <textarea id="resultarea" style="width:98%;height:7em"></textarea> javascript // getelementsbyclassname only ...
...not* the element itself console.log(test); //htmlcollection[1] var testtarget = parentdom.getelementsbyclassname("test")[0]; // the first element, as we wanted console.log(testtarget); //<p class="test">hello world 2</p> </script> </body> </html> multiple classes example document.getelementsbyclassname works very similarly to document.query
selector and document.query
selectorall. only elements with all of the classnames specified are selected. html <span class="orange fruit">orange fruit</span> <span class="orange juice">orange juice</span> <span class="apple juice">apple juice</span> <span class="foo bar">something random</span> <textarea id="resultarea" style="width:98%;height:7em"></textarea> javascript // getelementsbyclassname only selects elements that have ...
...98%;height:7em"></textarea> javascript // getelementsbyclassname only selects elements that have both given classes var allorangejuicebyclass = document.getelementsbyclassname('orange juice'); var result = "document.getelementsbyclassname('orange juice')"; for (var i=0, len=allorangejuicebyclass.length|0; i<len; i=i+1|0) { result += "\n " + allorangejuicebyclass[i].textcontent; } // query
selector only selects full complete matches var allorangejuicequery = document.query
selectorall('.orange.juice'); result += "\n\ndocument.query
selectorall('.orange.juice')"; for (var i=0, len=allorangejuicequery.length|0; i<len; i=i+1|0) { result += "\n " + allorangejuicequery[i].textcontent; } document.getelementbyid("resultarea").value = result; result specifications specification ...
DocumentFragment - Web APIs
telementchild read only returns the element that is the last child of the documentfragment object, or null if there is none. parentnode.childelementcount read only returns an unsigned long giving the amount of children that the documentfragment has. methods this interface inherits the methods of its parent, node, and implements those of the parentnode interface. documentfragment.query
selector() returns the first element node within the documentfragment, in document order, that matches the specified
selectors. documentfragment.query
selectorall() returns a nodelist of all the element nodes within the documentfragment that match the specified
selectors. documentfragment.getelementbyid() returns the first element node within the documentfragment, in document order, that matches the s...
...ne for each node inserted if they were inserted separately. this interface is also of great use with web components: <template> elements contain a documentfragment in their htmltemplateelement.content property. an empty documentfragment can be created using the document.createdocumentfragment() method or the constructor. ...
...nt() fruits.foreach(function (fruit) { var li = document.createelement('li') li.innerhtml = fruit fragment.appendchild(li) }) list.appendchild(fragment) result specifications specification status comment domthe definition of 'documentfragment' in that specification. living standard added the constructor and the implementation of parentnode.
selectors api level 1the definition of 'documentfragment' in that specification. obsolete added the query
selector() and query
selectorall() methods. document object model (dom) level 3 core specificationthe definition of 'documentfragment' in that specification. obsolete no change from document object model (dom) level 2 core specification document object model (dom) level 2 c...
Element - Web APIs
. element.attachshadow() attaches a shadow dom tree to the specified element and returns a reference to its shadowroot. element.animate() a shortcut method to create and run an animation on an element. returns the created animation object instance. element.closest() returns the element which is the closest ancestor of the current element (or the current element itself) which matches the
selectors given in parameter. element.createshadowroot() creates a shadow dom on on the element, turning it into a shadow host. returns a shadowroot. element.computedstylemap() returns a stylepropertymapreadonly interface which provides a read-only representation of a css declaration block that is an alternative to cssstyledeclaration. eventtarget.dispatchevent() dispatches an event to this no...
...to the element it is invoked upon. element.insertadjacenthtml() parses the text as html or xml and inserts the resulting nodes into the tree in the position given. element.insertadjacenttext() inserts a given text node at a given position relative to the element it is invoked upon. element.matches() returns a boolean indicating whether or not the element would be selected by the specified
selector string. element.pseudo() returns a csspseudoelement representing the child pseudo-element matched by the specified pseudo-element
selector. element.query
selector() returns the first node which matches the specified
selector string relative to the element. element.query
selectorall() returns a nodelist of nodes which match the specified
selector string relative to the element. element.rele...
...handlers: ongotpointercapture and onlostpointercapture. added the following methods: setpointercapture() and releasepointercapture(). pointer eventsthe definition of 'element' in that specification. obsolete added the following event handlers: ongotpointercapture and onlostpointercapture. added the following methods: setpointercapture() and releasepointercapture().
selectors api level 1the definition of 'element' in that specification. obsolete added the following methods: query
selector() and query
selectorall(). pointer lockthe definition of 'element' in that specification. candidate recommendation added the requestpointerlock() method. fullscreen apithe definition of 'element' in that specification. living standard added the requ...
FileList - Web APIs
rough files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } here is a complete example. ...
...h; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } here is a complete example. ...
... working draft html living standardthe definition of 'selected files' in that specification. ...
FileReader.readAsDataURL() - Web APIs
encoded data. to retrieve only the base64 encoded string, first remove data:*/*;base64, from the result. syntax instanceoffilereader.readasdataurl(blob); parameters blob the blob or file from which to read. ...
...ded string, first remove data:*/*;base64, from the result. syntax instanceoffilereader.readasdataurl(blob); parameters blob the blob or file from which to read. ...
...er.addeventlistener("load", function () { // convert image file to base64 string preview.src = reader.result; }, false); if (file) { reader.readasdataurl(file); } } live result example reading multiple files html <input id="browse" type="file" onchange="previewfiles()" multiple> <div id="preview"></div> javascript function previewfiles() { var preview = document.query
selector('#preview'); var files = document.query
selector('input[type=file]').files; function readandpreview(file) { // make sure `file.name` matches our extensions criteria if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader = new filereader(); reader.addeventlistener("load", function () { var image = new image(); image.height = 100; image.title =...
Using the Geolocation API - Web APIs
gitude. if sucessful, the available hyperlink is populated with an openstreetmap.org url that will show their location. ...
...lated with an openstreetmap.org url that will show their location. ...
...extcontent = `latitude: ${latitude} °, longitude: ${longitude} °`; } function error() { status.textcontent = 'unable to retrieve your location'; } if(!navigator.geolocation) { status.textcontent = 'geolocation is not supported by your browser'; } else { status.textcontent = 'locating…'; navigator.geolocation.getcurrentposition(success, error); } } document.query
selector('#find-me').addeventlistener('click', geofindme); result ...
Geolocation API - Web APIs
gitude. if sucessful, the available hyperlink is populated with an openstreetmap.org url that will show their location. ...
...lated with an openstreetmap.org url that will show their location. ...
...extcontent = `latitude: ${latitude} °, longitude: ${longitude} °`; } function error() { status.textcontent = 'unable to retrieve your location'; } if(!navigator.geolocation) { status.textcontent = 'geolocation is not supported by your browser'; } else { status.textcontent = 'locating…'; navigator.geolocation.getcurrentposition(success, error); } } document.query
selector('#find-me').addeventlistener('click', geofindme); result specifications specification status comment geolocation api recommendation ...
HTMLElement: animationcancel event - Web APIs
). bubbles yes cancelable no interface animationevent event handler property onanimationcancel examples this code gets an element that's currently being animated and adds a listener to the animationcancel event. it then sets the element's display property to none, which will trigger the animationcancel event. ...
.... it then sets the element's display property to none, which will trigger the animationcancel event. ...
...t: 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); } } js const animation = document.query
selector('p.animation'); const animationeventlog = document.query
selector('.animation-example>.event-log'); const applyanimation = document.query
selector('.animation-example>button.activate'); let iterationcount = 0; animation.addeventlistener('animationstart', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation started' `; }); animation.addeventlistener('animationitera...
HTMLElement: animationend event - Web APIs
if the element is removed from the dom or the animation is removed from the element, the animationend event is not fired. ...
...t event handler property onanimationend examples this example gets an element that's being animated and listens for the animationend event: const animated = document.query
selector('.animated'); animated.addeventlistener('animationend', () => { console.log('animation ended'); }); the same, but using the onanimationend event handler property: const animated = document.query
selector('.animated'); animated.onanimationend = () => { console.log('animation ended'); }; live example 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 .container { height: 3r...
... height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } js const animation = document.query
selector('p.animation'); const animationeventlog = document.query
selector('.animation-example>.event-log'); const applyanimation = document.query
selector('.animation-example>button.activate'); let iterationcount = 0; animation.addeventlistener('animationstart', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation started' `; }); animation.addeventlistener('animationitera...
HTMLElement: animationiteration event - Web APIs
mationend event, and therefore does not occur for animations with an animation-iteration-count of one. ...
...ion to keep track of the number of iterations an animation has completed: const animated = document.query
selector('.animated'); let iterationcount = 0; animated.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: const animated = document.query
selector('.animated'); let iterationcount = 0; animated.onanimationiteration = () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }; live example 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</b...
...t: 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); } } js const animation = document.query
selector('p.animation'); const animationeventlog = document.query
selector('.animation-example>.event-log'); const applyanimation = document.query
selector('.animation-example>button.activate'); let iterationcount = 0; animation.addeventlistener('animationstart', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation started' `; }); animation.addeventlistener('animationitera...
HTMLElement: animationstart event - Web APIs
l to the absolute value of the delay (and, correspondingly, the animation will begin playing at that time index into the sequence). ...
... interface animationevent event handler property onanimationstart examples this listens for the animationstart event and logs a message when it is fired: const animated = document.query
selector('.animated'); animated.addeventlistener('animationstart', () => { console.log('animation started'); }); the same, but using onanimationstart: const animated = document.query
selector('.animated'); animated.onanimationstart = () => { console.log('animation started'); }; live example 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 .container { heigh...
...t: 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); } } js const animation = document.query
selector('p.animation'); const animationeventlog = document.query
selector('.animation-example>.event-log'); const applyanimation = document.query
selector('.animation-example>button.activate'); let iterationcount = 0; animation.addeventlistener('animationstart', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation started' `; }); animation.addeventlistener('animationitera...
HTMLElement: change event - Web APIs
try entering something into the field below, and then click somewhere el...
...try entering something into the field below, and then click somewhere else to trigger the event. html <input placeholder="enter some text" name="name"/> <p id="log"></p> javascrip...
...nt = `you like ${event.target.value}`; }); result text input element for some elements, including <input type="text">, the change event doesn't fire until the control loses focus. try entering something into the field below, and then click somewhere else to trigger the event. html <input placeholder="enter some text" name="name"/> <p id="log"></p> javascript const input = document.query
selector('input'); const log = document.getelementbyid('log'); input.addeventlistener('change', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification status html living standardthe definition of 'change' in that specification. living standard ...
HTMLImageElement.complete - Web APIs
and wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. so the fixredeyecommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. this is demonstrated in the code below. ...
... for improved reliability you want to check to ensure this is the case. so the fixredeyecommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. this is demonstrated in the code below. ...
...the case. so the fixredeyecommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. this is demonstrated in the code below. let lightboxelem = document.query
selector("#lightbox"); let lightboximgelem = lightboxelem.query
selector("img"); let lightboxcontrolselem = lightboxelem.query
selector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { lightboxelem.style.display = "block"; await loadimage("https://somesite.net/huge-image.jpg", lightboximgelem); lightboxcontrolselem.disabled = false; } /* ... */ functio...
HTMLImageElement.x - Web APIs
/colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. ...
...ripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. let logbox = document.query
selector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.query
selector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <table>'s rows property to get a list of the rows in the table, from which it looks up row 1 (which, being a zero-based index, means the second row from the top). then it looks at that <tr> (table row) element's cells property to get a list of the cells in that row. the third cell is taken from that ...
... of the rows in the table, from which it looks up row 1 (which, being a zero-based index, means the second row from the top). then it looks at that <tr> (table row) element's cells property to get a list of the cells in that row. the third cell is taken from that row (once again, specifying 2 as the zero-based offset). from there, we can get the <img> element itself from the cell by calling query
selector() on the htmltablecellelement representing that cell. finally, we can look up and display the values of the htmlimageelement's x and y properties. css the css defining the appearance of the table: .group1 { background-color: #d7d9f2; } table { border-collapse: collapse; border: 2px solid rgb(100, 100, 100); font-family: sans-serif; } td, th { border: 1px solid rgb(100, 100, 100); ...
HTMLImageElement.y - Web APIs
/colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. ...
...ripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. let logbox = document.query
selector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.query
selector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <table>'s rows property to get a list of the rows in the table, from which it looks up row 1 (which, being a zero-based index, means the second row from the top). then it looks at that <tr> (table row) element's cells property to get a list of the cells in that row. the third cell is taken from that ...
... of the rows in the table, from which it looks up row 1 (which, being a zero-based index, means the second row from the top). then it looks at that <tr> (table row) element's cells property to get a list of the cells in that row. the third cell is taken from that row (once again, specifying 2 as the zero-based offset). from there, we can get the <img> element itself from the cell by calling query
selector() on the htmltablecellelement representing that cell. finally, we can look up and display the values of the htmlimageelement's x and y properties. css the css defining the appearance of the table: .group1 { background-color: #d7d9f2; } table { border-collapse: collapse; border: 2px solid rgb(100, 100, 100); font-family: sans-serif; } td, th { border: 1px solid rgb(100, 100, 100); ...
MediaElementAudioSourceNode - Web APIs
is invoked, which calculates the current gain as a ratio of mouse y position divided by overall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view the source. ...
...in as a ratio of mouse y position divided by overall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view the source. ...
...verall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view the source. ...
Using the MediaStream Recording API - Web APIs
app setup to grab the media stream we want to capture, we use getusermedia(). we then use the mediarecorder api to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back. ...
...capture, we use getusermedia(). we then use the mediarecorder api to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back. ...
...arecorder api to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back. ...
Node.getRootNode() - Web APIs
shows the difference between returning a normal root, and a root incuding the shadow root. ...
..., and a root incuding the shadow root. ...
...rce code): <!-- source: https://github.com/jserz/js_piece/blob/master/dom/node/getrootnode()/demo/getrootnode.html --> <div class="js-parent"> <div class="js-child"></div> </div> <div class="js-shadowhost"></div> <script> // works on chrome 54+,opera 41+ var parent = document.query
selector('.js-parent'), child = document.query
selector('.js-child'), shadowhost = document.query
selector('.js-shadowhost'); console.log(parent.getrootnode().nodename); // #document console.log(child.getrootnode().nodename); // #document // create a shadowroot var shadowroot = shadowhost.attachshadow({mode:'open'}); shadowroot.innerhtml = '<style>div{background:#2bb8aa;}</style>' + '<div class="js-shadowchild">content</div>'; var shadowchild = shadowroot.query
selector('.js-shadowc...
ScriptProcessorNode.bufferSize - Web APIs
udioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...oprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...h channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
ScriptProcessorNode.onaudioprocess - Web APIs
udioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...oprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...h channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
ScriptProcessorNode - Web APIs
udioprocess function takes the associated audioprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...oprocessingevent and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
...h channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. ...
ServiceWorker.onstatechange - Web APIs
on(statechangeevent) { ... } serviceworker.addeventlistener('statechange', function(statechangeevent) { ... } ) examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. ...
...pet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. ...
...d returns its value. var serviceworker; if (registration.installing) { serviceworker = registration.installing; document.query
selector('#kind').textcontent = 'installing'; } else if (registration.waiting) { serviceworker = registration.waiting; document.query
selector('#kind').textcontent = 'waiting'; } else if (registration.active) { serviceworker = registration.active; document.query
selector('#kind').textcontent = 'active'; } if (serviceworker) { logstate(serviceworker.state); serviceworker.addeventlistener('statechange', function(e) { logstate(e.target.state); }); } note that when statechange fires, the service worker's references may have changed. for example: navigator.serviceworker.register(..).then(function(swr) { swr.installing.state == "installing" swr.installin...
ServiceWorker.state - Web APIs
, or redundant. syntax someurl = serviceworker.state value a serviceworkerstate definition (see the spec.) examples this code snippet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. ...
...pet is from the service worker registration-events sample (live demo). the code listens for any change in the serviceworker.state and returns its value. ...
...d returns its value. var serviceworker; if (registration.installing) { serviceworker = registration.installing; document.query
selector('#kind').textcontent = 'installing'; } else if (registration.waiting) { serviceworker = registration.waiting; document.query
selector('#kind').textcontent = 'waiting'; } else if (registration.active) { serviceworker = registration.active; document.query
selector('#kind').textcontent = 'active'; } if (serviceworker) { logstate(serviceworker.state); serviceworker.addeventlistener('statechange', function(e) { logstate(e.target.state); }); } specifications specification status comment service workersthe definition of 'state' in that specification. working draft initial definition ...
SpeechSynthesisUtterance - Web APIs
ler, we stop the form submitting with preventdefault(), use the constructor to create a new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
...fault(), use the constructor to create a new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
...nce instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
StereoPannerNode.pan - Web APIs
we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
... value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
... pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
StereoPannerNode - Web APIs
we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
... value of the stereopannernode.pan parameter and update the pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
... pan value display when the slider is moved. moving the slider left and right while the music is playing pans the music across to the left and right speakers of the output, respectively. ...
SubtleCrypto.deriveBits() - Web APIs
blic key to derive a shared secret. see the complete code on github. ...
... // bob could generate the same secret using his private key and alice's public key. derivesharedsecret(aliceskeypair.privatekey, bobskeypair.publickey); }); }); pbkdf2 in this example we ask the user for a password, then us...
...{ const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const derivedbits = await window.crypto.subtle.derivebits( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, 256 ); const buffer = new uint8array(derivedbits, 0, 5); const derivedbitsvalue = document.query
selector(".pbkdf2 .derived-bits-value"); derivedbitsvalue.classlist.add("fade-in"); derivedbitsvalue.addeventlistener("animationend", () => { derivedbitsvalue.classlist.remove("fade-in"); }); derivedbitsvalue.textcontent = `${buffer}...[${derivedbits.bytelength} bytes total]`; } const derivebitsbutton = document.query
selector(".pbkdf2 .derive-bits-button"); derivebitsbutton.addeventlistener("...
VideoTrackList: change event - Web APIs
the change event is fired when a video track is made active or inactive, for example by changing the track's selected property. ...
... no interface event event handler property onchange examples using addeventlistener(): const videoelement = document.query
selector('video'); videoelement.videotracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `selected` will trigger the `change` event const toggletrackbutton = document.query
selector('.toggle-track'); toggletrackbutton.addeventlistener('click', () => { const track = videoelement.videotracks[0]; track.selected = !track.selected; }); using the onchange event handler property: const videoelement = document.query
selector('video'); videoelement.videotracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; // changing the value of `selected` will tr...
... living standard ...
Hello GLSL - Web APIs
="x-shader/x-fragment" id="fragment-shader"> #version 100 void main() { gl_fragcolor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.query
selector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.query
selector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader); program = gl.createprogram(); gl.a...
..." + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.vertexattribpointe...
... var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingcontext() { var canvas = document.query
selector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { var paragraph = document.query
selector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.dr...
Hello vertex attributes - Web APIs
="fragment-shader"> #version 100 precision mediump float; void main() { gl_fragcolor = vec4(0.18, 0.54, 0.34, 1.0); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.query
selector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.query
selector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader); program = gl.createprogram(); gl.a...
...hshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.detachshader(program, vertexshader); gl.detachshader(program, fragmentshader); gl.deleteshader(vertexshader); gl.deleteshader(fragmentshader); if (!gl.getprogramparameter(program, gl.link_status)) { var linkerrlog = gl.getprograminfolog(program); cleanup(); document.query
selector("p").innerhtml = "shader program did not link successfully. " + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); document.query
selector("canvas").addeventlistener("click", function (evt) { var clickxrelativtocanvas = evt.pagex - evt.target.offsetleft; var clickxinwebglcoords ...
..., buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0]), gl.static_draw); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } window.addeventlistener("beforeunload", cleanup, true); function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingcontext() { var canvas = document.query
selector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { var paragraph = document.query
selector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.dr...
Textures from code - Web APIs
istancesqrd = distance * distance; gl_fragcolor = vec4( 0.2/distancesqrd, 0.1/distancesqrd, 0.0, 1.0 ); } </script> ;(function(){ "use strict" window.addeventlistener("load", setupwebgl, false); var gl, program; function setupwebgl (evt) { window.removeeventlistener(evt.type, setupwebgl, false); if (!(gl = getrenderingcontext())) return; var source = document.query
selector("#vertex-shader").innerhtml; var vertexshader = gl.createshader(gl.vertex_shader); gl.shadersource(vertexshader,source); gl.compileshader(vertexshader); source = document.query
selector("#fragment-shader").innerhtml var fragmentshader = gl.createshader(gl.fragment_shader); gl.shadersource(fragmentshader,source); gl.compileshader(fragmentshader); program = gl.createprogram(); gl.a...
..." + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_b...
... buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0, 0.0]), gl.static_draw); gl.vertexattribpointer(0, 2, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingcontext() { var canvas = document.query
selector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { var paragraph = document.query
selector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.dr...
Web audio spatialization basics - Web APIs
mbox is rotated 180 degrees and facing away from us. we need to set up a few things for the interface. first, we'll get references to the elements we want to move, then we'll store references to the values we'll change when we set up css transforms to actually do the movement. ...
...facing away from us. we need to set up a few things for the interface. first, we'll get references to the elements we want to move, then we'll store references to the values we'll change when we set up css transforms to actually do the movement. ...
...for the interface. first, we'll get references to the elements we want to move, then we'll store references to the values we'll change when we set up css transforms to actually do the movement. ...
Window.getComputedStyle() - Web APIs
element the element for which to get the computed style. pseudoeltoptional a string specifying the pseudo-element to match. omitted (or null) for real elements. the returned style is a live cssstyledeclaration object, which updates automatically when the element's styles are changed. throws typeerror if the passed object is not an element or the pseudoelt is not a valid pseudo-element
selector or is ::part() or ::slotted(). note: valid pseudo-element
selector refers to syntactic validity, e.g. ::unsupported is considered valid, even though the pseudo-element itself is not supported. examples in this example we style a <p> element, then retrieve those styles using getcomputedstyle(), and print them into the text content of the <p>. html <p>hello</p> css p { width: 400p...
...-element itself is not supported. examples in this example we style a <p> element, then retrieve those styles using getcomputedstyle(), and print them into the text content of the <p>. html <p>hello</p> css p { width: 400px; margin: 0 auto; padding: 20px; font: 2rem/2 sans-serif; text-align: center; background: purple; color: white; } javascript let para = document.query
selector('p'); let compstyles = window.getcomputedstyle(para); para.textcontent = 'my computed font-size is ' + compstyles.getpropertyvalue('font-size') + ',\nand my computed line-height is ' + compstyles.getpropertyvalue('line-height') + '.'; result description the returned object is the same cssstyledeclaration type as the object returned from the element's style property. however, ...
...n of folks not wanting to write a testing spec for window and making an api that was also usable in java. use with pseudo-elements getcomputedstyle can pull style info from pseudo-elements (such as ::after, ::before, ::marker, ::line-marker — see the pseudo-element spec). <style> h3::after { content: ' rocks!'; } </style> <h3>generated content</h3> <script> var h3 = document.query
selector('h3'); var result = getcomputedstyle(h3, ':after').content; console.log('the generated content is: ', result); // returns ' rocks!' </script> notes the returned cssstyledeclaration object contains active values for css property longhand names. for example, border-bottom-width instead of the border-width and border shorthand property names. it is safest to query values with only longhand...
Window.speechSynthesis - Web APIs
nt. inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), create a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
...stop the form submitting with preventdefault(), create a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
...eate a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method. ...
ARIA live regions - Accessibility
nd the only object in the universe known to harbor life.' }, mars: { title: "mars", description: 'mars is the fourth planet from the sun and the second-smallest planet in the solar system after mercury. ...
...rs: { title: "mars", description: 'mars is the fourth planet from the sun and the second-smallest planet in the solar system after mercury. ...
...ocument.query
selector('#planetdescription'); if (planet in planets_info) { planettitle.textcontent = planets_info[planet].title; planetdescription.textcontent = planets_info[planet].description; } else { planettitle.textcontent = 'no planet selected'; planetdescription.textcontent = 'select a planet to view its description'; } } const renderplanetinfobutton = document.query
selector('#renderplanetinfobutton'); renderplanetinfobutton.addeventlistener('click', event => { const planetsselect = document.query
selector('#planetsselect'); const selectedplanet = planetsselect.options[planetsselect.selectedindex].value; renderplanetinfo(selectedplanet); }); as the user selects a new planet, the information in the live region will be announced. because the live region has ...
ARIA: tab role - Accessibility
ement and sets it to false, then sets the triggering element's aria-selected to true. after that, we find all tabpanel elements in the grandparent element, make them all hidden, and finally select the element whose id is equal to the triggering tab's aria-controls and removes the hidden attribute, making it visible. ...
...s aria-selected to true. after that, we find all tabpanel elements in the grandparent element, make them all hidden, and finally select the element whose id is equal to the triggering tab's aria-controls and removes the hidden attribute, making it visible. ...
... at the start, move to the end if (tabfocus < 0) { tabfocus = tabs.length - 1; } } tabs[tabfocus].setattribute("tabindex", 0); tabs[tabfocus].focus(); } }); }); function changetabs(e) { const target = e.target; const parent = target.parentnode; const grandparent = parent.parentnode; // remove all current selected tabs parent .query
selectorall('[aria-selected="true"]') .foreach(t => t.setattribute("aria-selected", false)); // set this tab as selected target.setattribute("aria-selected", true); // hide all tab panels grandparent .query
selectorall('[role="tabpanel"]') .foreach(p => p.setattribute("hidden", true)); // show the selected panel grandparent.parentnode .query
selector(`#${target.getattribute("a...
:first-child - CSS: Cascading Style Sheets
the :first-child css pseudo-class represents the first element among a group of sibling elements. /* selects any <p> that is the first element among its siblings */ p:first-child { color: lime; } note: as originally defined, the selected element had to have a parent. beginning with
selectors level 4, this is no longer required. syntax :first-child examples basic example html <div> <p>this text is selected!</p> <p>this text isn't selected.</p> </div> <div> <h2>this text isn't selected: it's not a `p`.</h2> <p>this text isn't selected.</p> </div> css p:first-child { color: lime; background-color: black; padding: 5px; } result styling a list html <ul> <li>item 1</li> <li>item 2</li> <li>item 3 <ul> <li>item 3.1</li> <li>item 3.2</li> ...
... recommendation no change. css level 2 (revision 1)the definition of ':first-child' in that specification. recommendation initial definition. ...
... <li>item 3.2</li> <li>item 3.3</li> </ul> </li> </ul> css ul li { color: blue; } ul li:first-child { color: red; font-weight: bold; } result specifications specification status comment
selectors level 4the definition of ':first-child' in that specification. working draft matching elements are not required to have a parent.
selectors level 3the definition of ':first-child' in that specification. recommendation no change. css level 2 (revision 1)the definition of ':first-child' in that specification. recommendation initial definition. ...
:first-of-type - CSS: Cascading Style Sheets
the :first-of-type css pseudo-class represents the first element of its type among a group of sibling elements. /* selects any <p> that is the first element of its type among its siblings */ p:first-of-type { color: red; } note: as originally defined, the selected element had to have a parent. beginning with
selectors level 4, this is no longer required. syntax :first-of-type examples styling the first paragraph html <h2>heading</h2> <p>paragraph 1</p> <p>paragraph 2</p> css p:first-of-type { color: red; font-style: italic; } result nested elements this example shows how nested elements can also be targeted. note that the universal
selector (*) is implied when no simple
selector is written. html <article> <div>this `div` is first!</div> <div>this <span>nested `spa...
... recommendation initial definition. ...
... recommendation initial definition. ...
:last-child - CSS: Cascading Style Sheets
the :last-child css pseudo-class represents the last element among a group of sibling elements. /* selects any <p> that is the last element among its siblings */ p:last-child { color: lime; } note: as originally defined, the selected element had to have a parent. beginning with
selectors level 4, this is no longer required. syntax :last-child examples basic example html <div> <p>this text isn't selected.</p> <p>this text is selected!</p> </div> <div> <p>this text isn't selected.</p> <h2>this text isn't selected: it's not a `p`.</h2> </div> css p:last-child { color: lime; background-color: black; padding: 5px; } result styling a list html <ul> <li>item 1</li> <li>item 2</li> <li>item 3 <ul> <li>item 3.1</li> <li>item 3.2</li> <li>...
... recommendation initial definition. ...
... recommendation initial definition. ...
:last-of-type - CSS: Cascading Style Sheets
the :last-of-type css pseudo-class represents the last element of its type among a group of sibling elements. /* selects any <p> that is the last element of its type among its siblings */ p:last-of-type { color: lime; } note: as originally defined, the selected element had to have a parent. beginning with
selectors level 4, this is no longer required. syntax :last-of-type examples styling the last paragraph html <h2>heading</h2> <p>paragraph 1</p> <p>paragraph 2</p> css p:last-of-type { color: red; font-style: italic; } result nested elements this example shows how nested elements can also be targeted. note that the universal
selector (*) is implied when no simple
selector is written. html <article> <div>this `div` is first.</div> <div>this <span>nested `span` is ...
... recommendation initial definition. ...
... recommendation initial definition. ...
:only-child - CSS: Cascading Style Sheets
the :only-child css pseudo-class represents an element without any siblings. this is the same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity. /* selects each <p>, but only if it is the */ /* only child of its parent */ p:only-child { background-color: lime; } note: as originally defined, the selected element had to have a parent. beginning with
selectors level 4, this is no longer required. syntax :only-child examples basic example html <div> <div>i am an only child.</div> </div> <div> <div>i am the 1st sibling.</div> <div>i am the 2nd sibling.</div> <div>i am the 3rd sibling, <div>but this is an only child.</div></div> </div> css div:only-child { color: red; } div { display: inline-block; margin: 6px; outline: 1px sol...
... recommendation initial definition. ...
... recommendation initial definition. ...
:target - CSS: Cascading Style Sheets
unique element (the target element) with an id matching the url's fragment. /* selects an element with an id matching the current url's fragment */ :target { border: 2px solid black; } for example, the following url has a fragment (denoted by the # sign) that points to an element called section2: http://www.example.com/index.html#section2 the following element would be selected by a :target
selector when the current url is equal to the above: <section id="section2">example</section> syntax :target examples a table of contents the :target pseudo-class can be used to highlight the portion of a page that has been linked to from a table of contents. html <h3>table of contents</h3> <ol> <li><a href="#p1">jump to the first paragraph!</a></li> <li><a href="#p2">jump to the second paragrap...
... recommendation initial definition. ...
... background-color: rgba(0,0,0,.7); content: ""; cursor: default; } result specifications specification status comment html living standardthe definition of ':target' in that specification. living standard defines html-specific semantics.
selectors level 4the definition of ':target' in that specification. working draft no changes.
selectors level 3the definition of ':target' in that specification. recommendation initial definition. ...
:visited - CSS: Cascading Style Sheets
/* selects any <a> that has been visited */ a:visited { color: green; } styles defined by the :visited pseudo-class will be overridden by any subsequent link-related pseudo-class (:link, :hover, or :active) that has at least equal specificity. to style links appropriately, put the :visited rule after the :link rule but before the :hover and :active rules, as defined by the lvha-order: :link — :visited — :hover — :active. ...
...used instead, except when that component is 0, in which case the style set in :visited will be ignored entirely. although these styles can be change the appearance of colors to the end user, the window.getcomputedstyle method will lie and always return the value of the non-:visited color. note: for more information on these limitations and the reasons behind them, see privacy and the :visited
selector. syntax :visited examples properties that would otherwise have no color or be transparent cannot be modified with :visited. of the properties that can be set with this pseudo-class, your browser probably has a default value for color and column-rule-color only. thus, if you want to modify the other properties, you'll need to give them a base value outside the :visited
selector. html <a hre...
...roperties, allowing them to be styled with the :visited state */ background-color: white; border: 1px solid white; } a:visited { background-color: yellow; border-color: hotpink; color: hotpink; } result specifications specification status comment html living standardthe definition of ':visited' in that specification. living standard
selectors level 4the definition of ':visited' in that specification. working draft no change.
selectors level 3the definition of ':visited' in that specification. recommendation no change. css level 2 (revision 1)the definition of ':visited' in that specification. recommendation lifts the restriction to only apply :visited to the <a> element. lets browsers restrict its ...
@keyframes - CSS: Cascading Style Sheets
rough the animation sequence at which the specified keyframe should occur. description javascript can access the @keyframes at-rule with the css object model interface csskeyframesrule. to use keyframes, create a @keyframes rule with a name that is then used by the animation-name property to match an animation to its keyframe declaration. each @keyframes rule contains a style list of keyframe
selectors, which specify percentages along the animation when the keyframe occurs, and a block containing the styles for that keyframe. you can list the keyframe percentages in any order; they will be handled in the order they should occur. valid keyframe lists if a keyframe rule doesn't specify the start or end states of the animation (that is, 0%/from and 100%/to), browsers will use the element's exi...
... specifications specification status comment css animationsthe definition of '@keyframes' in that specification. working draft ...
... specifications specification status comment css animationsthe definition of '@keyframes' in that specification. working draft ...
@namespace - CSS: Cascading Style Sheets
@namespace is an at-rule that defines xml namespaces to be used in a css style sheet. syntax /* default namespace */ @namespace url(xml-namespace-url); @namespace "xml-namespace-url"; /* prefixed namespace */ @namespace prefix url(xml-namespace-url); @namespace prefix "xml-namespace-url"; description the defined namespaces can be used to restrict the universal, type, and attribute
selectors to only select elements within that namespace. the @namespace rule is generally only useful when dealing with documents containing multiple namespaces—such as html5 with inline svg or mathml, or xml that mixes multiple vocabularies. any @namespace rules must follow all @charset and @import rules, and precede all other at-rules and style declarations in a style sheet. @namespace can be used to define t...
...documents containing multiple namespaces—such as html5 with inline svg or mathml, or xml that mixes multiple vocabularies. any @namespace rules must follow all @charset and @import rules, and precede all other at-rules and style declarations in a style sheet. @namespace can be used to define the default namespace for the style sheet. when a default namespace is defined, all universal and type
selectors (but not attribute
selectors, see note below) apply only to elements in that namespace. the @namespace rule can also be used to define a namespace prefix. when a universal, type, or attribute
selector is prefixed with a namespace prefix, then that
selector only matches if the namespace and name of the element or attribute matches. in html5, known foreign elements will automatically be assigned...
...nts will be assigned their proper namespaces (http://www.w3.org/2000/svg and http://www.w3.org/1998/math/mathml). note: in xml, unless a prefix is defined directly on an attribute (e.g., xlink:href), that attribute has no namespace. in other words, attributes do not inherit the namespace of the element they're on. to match this behaviour, the default namespace in css does not apply to attribute
selectors. formal syntax @namespace <namespace-prefix>? [ <string> | <url> ];where <namespace-prefix> = <ident> examples specifying default and prefixed namespaces @namespace url(http://www.w3.org/1999/xhtml); @namespace svg url(http://www.w3.org/2000/svg); /* this matches all xhtml <a> elements, as xhtml is the default unprefixed namespace */ a {} /* this matches all svg <a> elements */ svg|a {} ...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
hould be used over the course of two seconds to animate the box. note that because of this, the box doesn't start with any animation effects in place, so it won't be animating. javascript content next we'll look at the javascript that does the work. the meat of this technique is in the play() function, which is called when the user clicks on the "run" button. ...
... it won't be animating. javascript content next we'll look at the javascript that does the work. the meat of this technique is in the play() function, which is called when the user clicks on the "run" button. function play() { document.query
selector(".box").classname = "box"; window.requestanimationframe(function(time) { window.requestanimationframe(function(time) { document.query
selector(".box").classname = "box changing"; }); }); } this looks weird, doesn't it? that's because the only way to play an animation again is to remove the animation effect, let the document recompute styles so that it knows you've done that, then add the animation effect back to the element. to make that happen, we have to be creative. here's what happens when the play() function gets called: ...
...ack cleverly calls requestanimationframe() a second time! this time, the callback is run before the next repaint, which is after the style recomputation has occurred. this callback adds the "changing" class back onto the box, so that the repaint will start the animation once again. of course, we also need to add an event handler to our "run" button so it'll actually do something: document.query
selector(".runbutton").addeventlistener("click", play, false); result stopping an animation simply removing the animation-name applied to an element will make it jump or cut to its next state. if instead you'd like the animation to complete and then come to a stop you have to try a different approach. the main tricks are: make your animation as self-contained as possible. this means you should not...
Color picker tool - CSS: Cascading Style Sheets
function unsubscribe(callback) { subscribers.indexof(callback); subscribers.splice(index, 1); }; var notify = function notify(topic, value) { if (subscribers[topic] === undefined || subscribers[topic].length === 0) return; var color = new color(value); for (var i in subscribers[topic]) subscribers[topic][i](color); }; var init = function init() { var elem = document.query
selectorall('.ui-color-picker'); var size = elem.length; for (var i = 0; i < size; i++) new colorpicker(elem[i]); }; return { init : init, color : color, rgbcolor : rgbcolor, rgbacolor : rgbacolor, hsvcolor : hsvcolor, hsvacolor : hsvacolor, hslcolor : hslcolor, hslacolor : hslacolor, setcolor : setcolor, getcolor : getcolor, subscribe : subscribe, unsubscribe : unsubscri...
...this.topic][i](this.value); }; var createslider = function createslider(topic, label) { var slider = document.createelement('div'); slider.classname = 'ui-input-slider'; slider.setattribute('data-topic', topic); if (label !== undefined) slider.setattribute('data-info', label); new inputslider(slider); return slider; }; var init = function init() { var elem = document.query
selectorall('.ui-input-slider'); var size = elem.length; for (var i = 0; i < size; i++) new inputslider(elem[i]); }; return { init : init, setmax : setmax, setmin : setmin, setunit : setunit, setstep : setstep, getnode : getnode, getstep : getstep, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe, setprecision : setprecision, setsensivity : setsensivi...
...witchpickingmodeto(hsl); else switchpickingmodeto(hsv); }); hsv.addeventlistener('click', function() { switchpickingmodeto(hsv); }); hsl.addeventlistener('click', function() { switchpickingmodeto(hsl); }); parent.appendchild(icon); parent.appendchild(button); }; var setpickerdraganddrop = function setpickerdraganddrop() { var preview = document.query
selector('#picker .preview-color'); var picking_area = document.query
selector('#picker .picking-area'); preview.setattribute('draggable', 'true'); preview.addeventlistener('drop', drop); preview.addeventlistener('dragstart', dragstart); preview.addeventlistener('dragover', allowdropevent); picking_area.addeventlistener('drop', drop); picking_area.addeventlistener('dragover', allowdr...
Pseudo-elements - CSS: Cascading Style Sheets
note: as a rule, double colons (::) should be used instead of a single colon (:). this distinguishes pseudo-classes from pseudo-elements. ...
... note: as a rule, double colons (::) should be used instead of a single colon (:). this distinguishes pseudo-classes from pseudo-elements. ...
...example, ::first-line can be used to change the font of the first line of a paragraph. /* the first line of every <p> element. */ p::first-line { color: blue; text-transform: uppercase; } note: in contrast to pseudo-elements, pseudo-classes can be used to style an element based on its state. syntax
selector::pseudo-element { property: value; } you can use only one pseudo-element in a
selector. it must appear after the simple
selectors in the statement. note: as a rule, double colons (::) should be used instead of a single colon (:). this distinguishes pseudo-classes from pseudo-elements. however, since this distinction was not present in older versions of the w3c spec, most browsers support both syntaxes for the original pseudo-elements. index of standard pseudo-elements ::aft...
Audio and Video Delivery - Developer guides
ore information, see creating your own custom audio player. other tips for audio/video stopping the download of media while stopping the playback of media is as easy as calling the element's pause() method, the browser keeps downloading the media until the media element is disposed of through garbage collection. here's a trick that stops the download at once: var mediaelement = document.query
selector("#mymediaelementid"); mediaelement.removeattribute("src"); mediaelement.load(); by removing the media element's src attribute and invoking the load() method, you release the resources associated with the video, which stops the network download. you must call load() after removing the attribute, because just removing the src attribute does not invoke the load algorithm. if the <video> element al...
...see htmlmediaelement for further details on the element's properties. simply set the value to the time, in seconds, at which you want playback to continue. you can use the element's seekable property to determine the ranges of the media that are currently available for seeking to. this returns a timeranges object listing the ranges of times that you can seek to. ...
...s to add an error handler on the last source element. then you can replace the video with its fallback content: <video controls> <source src="dynamicsearch.mp4" type="video/mp4"></source> <a href="dynamicsearch.mp4"> <img src="dynamicsearch.jpg" alt="dynamic app search in firefox os"> </a> <p>click image to play a video demo of dynamic app search</p> </video> var v = document.query
selector('video'), sources = v.query
selectorall('source'), lastsource = sources[sources.length-1]; lastsource.addeventlistener('error', function(ev) { var d = document.createelement('div'); d.innerhtml = v.innerhtml; v.parentnode.replacechild(d, v); }, false); audio/video javascript libraries a number of audio and video javascript libaries exist. the most popular libraries allow you to ch...
Challenge solutions - Developer guides
ce inherited styles challenge change your stylesheet so that only the red letters are underlined. solution move the declaration for underlining from the rule for <p> to the one for <strong>. the resulting file looks like this: p {color: blue; } strong {color: orange; text-decoration: underline;} later sections of this tutorial describe style rules and declarations in greater detail. ...
...; text-decoration: underline;} later sections of this tutorial describe style rules and declarations in greater detail.
selectors second paragraph blue challenge without changing your html file, add a single rule to your css file that keeps all the initial letters the same color as they are now, but makes all the other text in the second paragraph blue. solution add a rule with an id
selector of #second and a declaration color: blue;, as shown below: #second { color: blue; } a more specific
selector, p#second also works. ...
...kes all the other text in the second paragraph blue. solution add a rule with an id
selector of #second and a declaration color: blue;, as shown below: #second { color: blue; } a more specific
selector, p#second also works. both paragraphs blue challenge now change the rule you have just added (without changing anything else), to make the first paragraph blue too. solution change the
selector of the new rule to be a tag
selector using p: p { color: blue; } the rules for the other colors all have more specific
selectors, so they override the blue of the paragraph. readable css commenting out a rule challenge comment out part of your stylesheet, without changing anything else, to make the very first letter of your document red. solution one way to do this is to put comment...
Creating and triggering events - Developer guides
ue); // listen for the event. elem.addeventlistener('build', function (e) { // e.target matches elem }, false); // target can be any element or other eventtarget. ...
...ner('build', function (e) { // e.target matches elem }, false); // target can be any element or other eventtarget. ...
...ail.text())); // as the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.addeventlistener('input', e => e.target.dispatchevent(eventawesome)); creating and dispatching events dynamically elements can listen for events that haven't been created yet: <form> <textarea></textarea> </form> const form = document.query
selector('form'); const textarea = document.query
selector('textarea'); form.addeventlistener('awesome', e => console.log(e.detail.text())); textarea.addeventlistener('input', function() { // create and dispatch/trigger an event on the fly // note: optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element this.dispat...
DOM onevent handlers - Developer guides
etting focus the onevent handler is usually named with the event it reacts to, like onclick, onkeypress, onfocus, etc. you can specify an on<…> event handler for a particular event (such as click) for a given object in different ways: adding an html attribute named on<eventtype>: <button onclick="handleclick()">, or by setting the corresponding property from javascript: document.query
selector("button").onclick = function(event) { … }. an onevent event handler property serves as a placeholder of sorts, to which a single event handler can be assigned. in order to allow multiple handlers to be installed for the same event on a given object, you can call its addeventlistener() method, which manages a list of handlers for the given event on the object. a handler can then be removed fro...
...javascript property will have no effect. html given this html document: <p>demonstrating quirks of <code>on<em>event</em></code> html attributes on <a onclick="log('click!')">these three words</a>. </p> <div></div> javascript then this javascript demonstrates that the value of the html attribute is unaffected by changes to the javascript object's property. ...
... html given this html document: <p>demonstrating quirks of <code>on<em>event</em></code> html attributes on <a onclick="log('click!')">these three words</a>. </p> <div></div> javascript then this javascript demonstrates that the value of the html attribute is unaffected by changes to the javascript object's property. ...
<input type="checkbox"> - HTML: Hypertext Markup Language
ts: if none are checked, the recipe name's checkbox is set to unchecked. if one or two are checked, the recipe name's checkbox is set to indeterminate. if all three are checked, the recipe name's checkbox is set to checked. so in this case the indeterminate state is used to state that collecting the ingredients has started, but the recipe is not yet complete. ...
...checked. if one or two are checked, the recipe name's checkbox is set to indeterminate. if all three are checked, the recipe name's checkbox is set to checked. so in this case the indeterminate state is used to state that collecting the ingredients has started, but the recipe is not yet complete. ...
...ther"> </div> <div> <button type="submit">submit form</button> </div> </fieldset> </form> css html { font-family: sans-serif; } form { width: 600px; margin: 0 auto; } div { margin-bottom: 10px; } fieldset { background: cyan; border: 5px solid blue; } legend { padding: 10px; background: blue; color: cyan; } javascript var othercheckbox = document.query
selector('input[value="other"]'); var othertext = document.query
selector('input[id="othervalue"]'); othertext.style.visibility = 'hidden'; othercheckbox.addeventlistener('change', () => { if(othercheckbox.checked) { othertext.style.visibility = 'visible'; othertext.value = ''; } else { othertext.style.visibility = 'hidden'; } }); specifications specification status co...
<input type="color"> - HTML: Hypertext Markup Language
e change event is fired when the user dismisses the color picker. in both cases, you can determine the new value of the element by looking at its value. here's an example that watches changes over time to the color value: colorpicker.addeventlistener("input", updatefirst, false); colorpicker.addeventlistener("change", watchcolorpicker, false); function watchcolorpicker(event) { document.query
selectorall("p").foreach(function(p) { p.style.color = event.target.value; }); } selecting the value if the <input> element's implementation of the color type on the user's browser doesn't support a color well, but is instead a text field for entering the color string directly, you can use the select() method to select the text currently in the edit field. if the browser instead uses a color well...
... contains the color we'll set the color well to when we first load up, and then setting up a load handler to do the main startup work once the page is fully loaded. var colorwell; var defaultcolor = "#0000ff"; window.addeventlistener("load", startup, false); initialization once the page is loaded, our load event handler, startup(), is called: function startup() { colorwell = document.query
selector("#colorwell"); colorwell.value = defaultcolor; colorwell.addeventlistener("input", updatefirst, false); colorwell.addeventlistener("change", updateall, false); colorwell.select(); } this gets a reference to the color <input> element in a variable called colorwell, then sets the color input's value to the value in defaultcolor. then the color input's input event is set up to call our upd...
...s called in response to the input event. it changes the color of the first paragraph element in the document to match the new value of the color input. since input events are fired every time an adjustment is made to the value (for example, if the brightness of the color is increased), these will happen repeatedly as the color picker is used. function updatefirst(event) { var p = document.query
selector("p"); if (p) { p.style.color = event.target.value; } } when the color picker is dismissed, indicating that the value will not be changing again (unless the user re-opens the color picker), a change event is sent to the element. we handle that event using the updateall() function, using event.target.value to obtain the final selected color: function updateall(event) { document.queryse...
<input type="number"> - HTML: Hypertext Markup Language
each option's value is the corresponding suggested value for the number entry bo...
...markable here. ...
... } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } and finally, the javascript: let metersinputgroup = document.query
selector('.metersinputgroup'); let feetinputgroup = document.query
selector('.feetinputgroup'); let metersinput = document.query
selector('#meters'); let feetinput = document.query
selector('#feet'); let inchesinput = document.query
selector('#inches'); let switchbtn = document.query
selector('input[type="button"]'); switchbtn.addeventlistener('click', function() { if(switchbtn.getattribute('class') === 'meters') { switchbtn.setattribute('class', 'feet'); switchbt...
visibility - SVG: Scalable Vector Graphics
recommendation css ...
... recommendation css definition of the property scalable vector graphics (svg) 2the de...
... recommendation css definition of the property scalable vector graphics (svg) 2the definition of 'visibility' in that specification. candidate recommendation ma...
ui/frame - Archive of obsolete content
inting to an html document supplied under your add-ons "data" directory. ...
...message("ping", "*"); if the frame script has received a message from the add-on already, it can use the origin property of the event object passed to the message hander: // listen for messages from the add-on, and send a reply window.addeventlistener("message", function(event) { event.source.postmessage("pong", event.origin) }, false); this frame script listens to change events on the "city-
selector" <select> element, and sends a message to the add-on containing the value for the newly selected element. // city-info.js var city
selector = window.document.getelementbyid("city-
selector"); city
selector.addeventlistener("change", citychanged); function citychanged() { window.parent.postmessage(city
selector.value, "*"); } to listen for these messages in the main add-on code, you can assign a ...
XML in Mozilla - Archive of obsolete content
ays test our xml support. ...
...at can be run automatically (this would require knowledge of web development; document.load() and/or xml extras might be needed), but probably most of the bugs we get have just been found by normal people trying to do something that works in some other browser and does not work in mozilla. see also e4x xquery code snippets for query
selector - useful techniques for navigating dom using css
selectors on xml dom documents (firefox 3.5 only) identifying xml elements and documents parsing and serializing xml ...
Writing Skinnable XUL and CSS - Archive of obsolete content
to all of you!!! derived skin files should not attempt to change the default look for a widget. for example, there should never be any css rules of the form tagname {...}; in a derived skin file. in doing so, you have redefined the default look for the widget, which will make the ui in your window different from others that properly inherit from the same base skin file you do. the descendant
selector is forbidden. never use the descendant
selector without first getting usage of the rule approved. the matching for these rules (unless you're very careful) will be inefficient, and when only using generic tag names, can be positively grotesque. i'll show you the evil rule i put into the global skin a few months back that was making trees slow. treehead treerow treecell { bad! evil! yuck! ..
...d treerow treecell { bad! evil! yuck! ... } this evil rule caused the style system, for every treecell that wasn't in a treehead (which is practically every treecell in a typical tree), to crawl up the whole parent chain to the root of the document in order to determine that the style rule wasn't a match. i'm usually seeing this rule misused by people who really wanted to use the child
selector instead. that was my mistake with the above rule. i should have used treehead > treerow > treecell. after all, that's what i meant anyway. never use an attribute
selector rule for the class attribute. this is inefficient and you should just use the class notation (the dot notation) instead. writing skinnable xul a xul file that describes a window always imports the master skin file for it...
description - Archive of obsolete content
typically, this will cause the text to appear bold. indent this class causes the text to be indented on its le...
...typically, this will cause the text to appear bold. indent this class causes the text to be indented on its left side. monos...
image - Archive of obsolete content
this typically looks like an exclamation mark. this and the other icon classes may be used by ...
...this typically looks like an exclamation mark. this and the other icon classes may be used by image elements or...
treecol - Archive of obsolete content
this class should be used instead of changing the style of the element directly since it will fit...
...this class should be used instead of changing the style of the element directly since it will fit more naturally w...
Building a Theme - Archive of obsolete content
going to be a steep learning curve, and you may want to try some html-based tutorials to start with. the browser ui has absolutely no styling on its own - if you try to start up with an empty theme, firefox will be unusable, as the button elements will be drawn as plain text. this is why we copied the default styles in the setup step. when writing a theme, the easiest way to determine what css
selectors you need to write is to use the dom inspector which you should have installed in the setup step. you can use this to inspect any element in a web page or an xul document, which makes it invaluable for themes. updating the toolbar's styling note in firefox 4.0 and up, the highlight feature of dom inspector is broken. to workaround this, disable hardware acceleration in firefox' options. open...
...ect a node of type "xul:toolbar" in the dom inspector. from here, you can play around with various different stylings for the toolbar and associated elements. by default, the right pane should show the dom node, which has useful styling information like the css class and node id. the element itself is of id navigator-toolbox, with no idea. to change its style within our theme, we need to write a
selector rule to select this class. open up the file chrome/browser/browser.css in your theme. search this file for the #navigator-toolbox
selector, and add a background: orange; rule to it. save the file. chrome uris next, we have to tell firefox where to find the theme files for your theme. css, xul, and other files are part of "chrome packages" - bundles of user interface components which are loa...
Using Firebug and jQuery (Screencast) - Archive of obsolete content
ht-click this link and select save as... in order to download a copy of your own. (59mb) bookmarklets: in the presentation, i refer to a bookmarklet that you can use to introduce jquery into a web page. drag these bookmarklets found on this page into the bookmarks toolbar of your browser, in order to use them. related links: firebug firefox extension jquery javascript library jquery
selector documentation digg learning jquery: jquerify bookmarklet if you wish to use greasemonkey instead of a bookmarklet, then by all means, please do so. you can use the ability to quickly analyze and inspect a page that firebug and jquery affords you, using the results to build a greasemonkey script, instead of a simple bookmarklet. i only really intended this to be a quick introduction to the sub...
...monkey instead of a bookmarklet, then by all means, please do so. you can use the ability to quickly analyze and inspect a page that firebug and jquery affords you, using the results to build a greasemonkey script, instead of a simple bookmarklet. i only really intended this to be a quick introduction to the subject, so please feel free to explore it more! more tips: here are some more jquery
selectors that you can use on a digg post: $("li.c-bury > div").remove(); - remove all buried comments, but none of the direct replies. $("div.c-body").show(); - show all comments, even ones that've been buried. ...
Audio for Web games - Game development
might be playing at, so they sync up. let's create our audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); now let's select all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button. ...
...{ tracksource.start(); offset = audioctx.currenttime; } else { tracksource.start(0, audioctx.currenttime - offset); } return tracksource; } finally, let's loop over our <li> elements, grab the correct file for each one and then allow playback by hiding the "loading" text and displaying the play button: trackels.foreach((el, i) => { // get children const anchor = el.query
selector('a'); const loadtext = el.query
selector('p'); const playbutton = el.query
selector('button'); // load file loadfile(anchor.href).then((track) => { // set loading to false el.dataset.loading = 'false'; // hide loading text loadtext.style.display = 'none'; // show button playbutton.style.display = 'inline-block'; // allow play on click playbutton.addevent...
CSS - MDN Web Docs Glossary: Definitions of Web-related terms
s style declarations to selected elements to display them properly. a style declaration contains the properties and their values, which determine how a webpage looks. css is one of the three core web technologies, along with html and javascript. css usually styles html elements, but can be also used with other markup languages like svg or xml. a css rule is a set of properties associated with a
selector. here is an example that makes every html paragraph yellow against a black background: /* the
selector "p" indicates that all paragraphs in the document will be affected by that rule */ p { /* the "color" property defines the text color, in this case yellow. */ color: yellow; /* the "background-color" property defines the background color, in this case black. */ background-color: black ...
...this is a very important feature, since a complex website can have thousands of css rules. ...
Legacy layout methods - Learn web development
gutter width: 20 / 960 = 0.02083333333 so we need to replace the 20 pixel margin-left on our .col rule and the 20 pixel padding-right on .wrapper with 2.08333333%. updating our grid to get started in this section, make a new copy of your previous example page, or make a local copy of our simple-grid-finished.html code to use as a starting point. ...
...hed.html code to use as a starting point. update the second css rule (with the .wrapper
selector) as follows: body { width: 90%; max-width: 980px; margin: 0 auto; } .wrapper { padding-right: 2.08333333%; } not only have we given it a percentage width, we have also added a max-width property in order to stop the layout becoming too wide. next, update the fourth css rule (with the .col
selector) like so: .col { float: left; margin-left: 2.08333333%; width: 6.25%; background: rgb(255, 150, 150); } now comes the slightly more laborious part — we need to update all our .col.span rules to use percentages rather than pixel widths. this takes a bit of time with a calculator; to save you some effort, we've done it for you below. update the bottom block of css rules with the follow...
Client-side form validation - Learn web development
ng: 0.3em; } now lets look at the javascript that implements the custom error validation. // there are many ways to pick a dom node; here we get the form itself and the email // input box, as well as the span element into which we will place the error message. const form = document.getelementsbytagname('form')[0]; const email = document.getelementbyid('mail'); const emailerror = document.query
selector('#mail + span.error'); email.addeventlistener('input', function (event) { // each time the user types something, we check if the // form fields are valid. if (email.validity.valid) { // in case there is an error message visible, if the field // is valid, we remove the error message. emailerror.innerhtml = ''; // reset the content of the message emailerror.classname = 'erro...
... body { font: 1em sans-serif; width: 200px; padding: 0; margin : 0 auto; } form { max-width: 200px; } p * { display: block; } input.mail { -webkit-appearance: none; width: 100%; border: 1px solid #333; margin: 0; font-family: inherit; font-size: 90%; box-sizing: border-box; } /* this is our style for the invalid fields */ ...
Sending forms through JavaScript - Learn web development
bound to a <form> element. let's look at them in detail. building an xmlhttprequest manually xmlhttprequest is the safest and most reliable way to make http requests. to send form data with xmlhttprequest, prepare the data by url-encoding it, and obey the specifics of form data requests. let's look at an example: <button>click me!</button> and now the javascript: const btn = document.query
selector('button'); function senddata( data ) { console.log( 'sending data' ); const xhr = new xmlhttprequest(); let urlencodeddata = "", urlencodeddatapairs = [], name; // turn the data object into an array of url-encoded key/value pairs. for( name in data ) { urlencodeddatapairs.push( encodeuricomponent( name ) + '=' + encodeuricomponent( data[name] ) ); } // combine t...
...n a form element to manage how it's sent. note that formdata objects are "write only", which means you can change them, but not retrieve their contents. using this object is detailed in using formdata objects, but here are two examples: using a standalone formdata object <button>click me!</button> you should be familiar with that html sample. ...
UI pseudo-classes - Learn web development
hovered over by a mouse pointer. :focus: selects an element only when it is focused (i.e. by being tabbed to via the keyboard). :active: selects an element only when it is being activated (i.e. while it is being clicked on, or when the return/enter key is being pressed down in the case of a keyboard activation). these basic pseudo-classes should be familiar to you now. more recently, the css
selector level 3 and css basic ui level 3 added more pseudo-classes related to html forms that provide several other useful targetting conditions that you can take advantage of. we'll discuss these in more detail in the sections below, but briefly, the main ones we'll be looking at are: :required and :optional: targets required or optional form controls. :valid and :invalid, and :in-range and :out-of-...
...toggle the disabling of the billing address fields: // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').addeventlistener('change', togglebilling); }, false); function togglebilling() { // select the billing text fields let billingitems = document.query
selectorall('#billing input[type="text"]'); // select the billing text labels let billinglabels = document.query
selectorall('.billing-label'); // toggle the billing text fields and labels for (let i = 0; i < billingitems.length; i++) { billingitems[i].disabled = !billingitems[i].disabled; if(billinglabels[i].getattribute('class') === 'billing-label disabled-label') { billinglabels[...
Images in HTML - Learn web development
ue="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.query
selector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
...ue="show solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var solution = document.getelementbyid('solution'); var output = document.query
selector('.output'); var code = textarea.value; var userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
your <script> element. here, you're storing a reference to the <div> inside a constant, setting a rotatecount variable to 0, setting an uninitialized variable that will later be used to contain a reference to the requestanimationframe() call, and setting a starttime variable to null, which will later be used to store the start time of the requestanimationframe(). const spinner = document.query
selector('div'); let rotatecount = 0; let starttime = null; let raf; below the previous code, insert a draw() function that will be used to contain our animation code, which includes the timestamp parameter: function draw(timestamp) { } inside draw(), add the following lines. they will define the start time if it is not defined already (this will only happen on the first loop iteration), ...
... a game board that shows the two players' information (as seen above), but with the spinner and results paragraph displayed on top of one another. you just have to write the javascript code. inside the empty <script> element on your page, start by adding the following lines of code that define some constants and variables you'll need in the rest of the code: const spinner = document.query
selector('.spinner p'); const spinnercontainer = document.query
selector('.spinner'); let rotatecount = 0; let starttime = null; let raf; const btn = document.query
selector('button'); const result = document.query
selector('.result'); in order, these are: a reference to the spinner, so you can animate it. a reference to the <div> element that contains the spinner, used for showing and hiding it...
Basic math in JavaScript — numbers and operators - Learn web development
essage if the game has been won display the correct seasonal greeting depending what holiday season it is zoom a map in or out depending on what zoom level is selected we'll look at how to code such logic when we look at conditional statements in a future article. ...
...orrect seasonal greeting depending what holiday season it is zoom a map in or out depending on what zoom level is selected we'll look at how to code such logic when we look at conditional statements in a future article. ...
What went wrong? Troubleshooting JavaScript - Learn web development
.textcontent = 'last guess was too high!'; this line is trying to set the textcontent property of the loworhi constant to a text string, but it's not working because loworhi does not contain what it's supposed to. let's see why this is — try searching for other instances of loworhi in the code. the earliest instance you'll find in the javascript is on line 48: const loworhi = document.query
selector('loworhi'); at this point we are trying to make the variable contain a reference to an element in the document's html. let's check whether the value is null after this line has been run. add the following code on line 49: console.log(loworhi); note: console.log() is a really useful debugging function that prints a value to the console. so it will print the value of loworhi to the conso...
...t prints a value to the console. so it will print the value of loworhi to the console as soon as we have tried to set it in line 48. save and refesh, and you should now see the console.log() result in your console. sure enough, loworhi's value is null at this point, so there is definitely a problem with line 48. let's think about what the problem could be. line 48 is using a document.query
selector() method to get a reference to an element by selecting it with a css
selector. looking further up our file, we can find the paragraph in question: <p class="loworhi"></p> so we need a class
selector here, which begins with a dot (.), but the
selector being passed into the query
selector() method in line 48 has no dot. this could be the problem! try changing loworhi to .loworhi in line 48. tr...
Handling common JavaScript problems - Learn web development
when writing future projects, and decided to release them into the wild because other people might find them useful too. javascript libraries tend to come in a few main varieties (some libraries will serve more than one of these purposes): utility libraries: provide a bunch of functions to make mundane tasks easier and less boring to manage. jquery for example provides its own fully-featured
selectors and dom manipuation libraries, to allow css-
selector type selecting of elements in javascript and easier dom building. it is not so important now we have modern features like document.query
selector()/document.query
selectorall()/node methods available across browsers, but it can still be useful when older browsers need supporting. convenience libraries: make difficult things easier to do. for ex...
...l in the same directory as the html. ...
Setting up your own test automation environment - Learn web development
in many ways in webdriver, including by id, class, element name, etc. the actual selection is done by the findelement() method, which accepts as a parameter a selection method. for example, to select an element by id: const element = driver.findelement(by.id('myelementid')); one of the most useful ways to find an element by css — the by.css method allows you to select an element using a css
selector enter the following at the bottom of your quick_test.js code now: const button = driver.findelement(by.css('button:nth-of-type(1)')); testing your element there are many ways to interact with your web documents and elements on them. you can see useful common examples starting at getting text values on the webdriver docs. if we wanted to get the text inside our button, we could do this: butt...
...test design considerations. in general, you should make sure that your tests are: using good locator strategies: when you are interacting with the document, make sure that you use locators and page objects that are unlikely to change — if you have a testable element that you want to perform a test on, make sure that it has a stable id, or position on the page that can be selected using a css
selector, which isn't going to just change with the next site iteration. you want to make your tests as non-brittle as possible, i.e. they won't just break when something changes. write atomic tests: each test should test one thing only, making it easy to keep track of what test file is testing which criterion. as an example, the google_test.js test we looked at above is pretty good, as it just tests a s...
Performance
ript or jsm instead load frame scripts on demand bad: // addon.js services.mm.loadframescript("framescript.js", /*delayed:*/ true) // stuff communicating with the framescript // framescript.js function onlyonceinabluemoon() { // we only need this during a total solar eclipse while goat blood rains from the sky sendasyncmessage('my-addon:paragraph-count', {num: content.document.query
selectorall('p').length}) } addmessagelistener("my-addon:request-from-parent", onlyonceinabluemoon) better: // addon.js function ontoolbarbutton(event) { let tabmm = gbrowser.mcurrentbrowser.frameloader.messagemanager; let button = event.target; let callback = (message) => { tabmm.removemessagelistener("my-addon:paragraph-count", callback) decoratebutton(button, message.data.num) } ta...
... as long as it the action does not happen frequently the memory and startup savings should outstrip the added cost of script evaluation. delaying the script regist...
HTMLIFrameElement.getMuted()
success case, and an onerror handler to handle the failure case. the muted value is available in the request.result property, and is a boolean value — true means muted, and false means unmuted. promise version: a promise that resolves with the muted value — a boolean where true means muted, and false means unmuted. parameters none. ...
... a boolean where true means muted, and false means unmuted. parameters none. example callback version: var browser = document.query
selector('iframe'); var request = browser.getmuted(); request.onsuccess = function() { if(request.result) { console.log('the browser is muted.'); } else { console.log('the browser is unmuted.'); } } promise version: var browser = document.query
selector('iframe'); browser.getmuted().then(function(muted) { if(muted) { console.log('the browser is muted.'); } else { console.log('the browser is unmuted.'); } }); specification not part of any specification. ...
HTMLIFrameElement.purgeHistory()
fhtmliframeelement.purgehistory(); instanceofhtmliframeelement.purgehistory().then(function() { ... }); returns either a domrequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not. a promise that resolves, with no parameters, if the history is deleted, or rejects if not. parameters none. ...
...a promise that resolves, with no parameters, if the history is deleted, or rejects if not. parameters none. examples domrequest: var browser = document.query
selector('iframe'); var request = browser.purgehistory(); request.onsuccess = function() { console.log('history deleted!'); } request.onerror = function() { console.error(this.error.name); } promise: var browser = document.query
selector('iframe'); browser.purgehistory().then(function() { console.log('history deleted!'); }, function(error) { console.error(this.error.name); }); specification not part of any specification. ...
Mozilla Web Developer FAQ
is the server sending the proper content-type header for css style sheets? the correct type is text/css. in the standards mode and the almost standards mode only style sheets with the correct type are applied. you can see the http headers sent by the server by using the livehttpheaders extension or by using the web sniffer. class names and ids are case-sensitive. the element
selectors are case-sensitive with xml. style sheet processing instructions are only allowed in the prolog of xml documents. also, they only work in xml documents—not in documents served as text/html. width and height do not apply to non-replaced inline elements such as (by default) <span>. text-align: center; centers inline content within a block. it does not (and should not) center the block box its...
... to the dom. this affects data round tripping using hidden form inputs. in versions prior to gecko 1.9/firefox 3, the document is not loaded and rendered incrementally. the layout mode is the (full) standards mode regardless of doctype. css works according to the xml+css rules. html-specific css exceptions do not apply. for example, the body element gets no special treatment. css
selectors are case-sensitive. the dom is in the xml mode. namespace-aware variants of methods need to be used when working with elements (eg. createelementns() instead of createelement()). element and attribute names are not normalized to upper case. other namespaces are supported. mathml svg (in svg-enabled builds only) xul (please note that xul is mozilla-specific and, t...
Mozilla Style System Documentation
ent node or content node + pseudo-element pair. (the "non-element" style contexts are defined never to match any rules.) these interfaces nsistylesheet and nsistylerule correspond to the css concepts of style sheets and style rules, except they are more general, and are used by other code that needs to add style information to the document. for the css stylesheets, this process corresponds to css
selector matching. the output of css
selector matching as defined by the css specification is an ordered list of rules, where the order determines which declarations override other declarations. (in css,declarations are the property-value pairs within style rules. in mozilla, nscssdeclaration objects correspond to css declaration-blocks.) due to the high similarity of these lists between elements in the c...
... as defined by the css specification is an ordered list of rules, where the order determines which declarations override other declarations. (in css,declarations are the property-value pairs within style rules. in mozilla, nscssdeclaration objects correspond to css declaration-blocks.) due to the high similarity of these lists between elements in the content tree, mozilla stores the output of the
selector matching process in a lexicographic tree, the rule tree. this double tree (style context tree and rule tree) allows for sharing of style data, which allows the data to take up less memory and allows the data computation to take less time. for example, suppose we had the css stylesheet: /* rule 1 */ doc { display: block; text-indent: 1em; } /* rule 2 */ title { display: block; font-size: 3em; }...
L20n Javascript API
ady event (emitted by the context instance when all the resources have been compiled) and use ctx.getsync and ctx.getentitysync to get translations synchronously. alternatively, you can register callbacks to execute when the context is ready (or when globals change and translations need to be updated) with ctx.localize. ctx.localize(['hello', 'new'], function(l10n) { var node = document.query
selector('[data-l10n-id=hello]'); node.textcontent = l10n.entities.hello.value; node.classlist.remove('hidden'); }); ctx.registerlocales(defaultlocale: string?, availablelocales: array<string>?) register the default locale of the context instance, as well as all other locales available to the context instance before the language negotiation. locales are referenced by their bcp 47 language codes. ...
... language the entity is in; it can be different than the first locale in the current fallback chain if the entity couldn't be evaluated and a fallback translation had to be used. ctx.localize(ids: array<string>, callback: function) registers a callback which fires when all entities listed in ids have been retrieved. ctx.localize(['hello', 'about'], function(l10n) { var node = document.query
selector('[data-l10n-id=hello]'); node.textcontent = l10n.entities.hello.value; node.classlist.remove('hidden'); }); the callback becomes bound to the entities on the ids list. it will be called when the entities become available (asynchronously) or whenever the translation of any of the entities changes. localize should be the preferred way of localizing the ui. the callback function is passed a...
Parser API
pr] form), then computed is true and the right property is an expression. interface xmlfunctionqualifiedidentifier <: expression { type: "xmlfunctionqualifiedidentifier"; right: identifier | expression; computed: boolean; } an e4x identifier qualified by the function keyword, e.g., function::id. note: function-qualified identifiers are spidermonkey-specific. interface xmlattribute
selector <: expression { type: "xmlattribute
selector"; attribute: expression; } an e4x attribute
selector expression, i.e., an @ expression. interface xmlfilterexpression <: expression { type: "xmlfilterexpression"; left: expression; right: expression; } an e4x list filter expression, i.e., an expression of the form expr.(expr). interface xmlelement <: xml, expression { type:...
...t property initializer node. e4x declarations xmldefaultdeclaration(ns[, loc]) loc: sourcelocation returns: customdeclaration callback to produce a custom xml default namespace declaration node. expressions xmlanyname([loc]) loc: sourcelocation returns: customxmlanyname/customxml/customexpression callback to produce a custom xml node for the wildcard pseudo-identifier *. xmlattribute
selector(expr[, loc]) expr: customexpression loc: sourcelocation returns: customxml/customexpression callback to produce a custom xml attribute
selector node. xmlfilterexpression(left, right[, loc]) left: customexpression right: customexpression loc: sourcelocation returns: customxml/customexpression callback to produce a custom xml filter expression node. xmlqualifiedidentifier(left, right, isc...
Standard OS Libraries
modules are auto-generated from the os x header files githubgists :: noitidart / search · corefoundation - corefoundation js-ctypes snippets that can be copied and pasted to scratchpad cocoa see using objective-c from js-ctypes for more info. ...
...mouselocation]; // pseudo c code nsevent loc = (nspoint)objc_msgsend(objc_getclass("nsevent"), sel_registername("mouselocation")); example: [nsevent mouselocation] components.utils.import("resource://gre/modules/ctypes.jsm"); let objc = ctypes.open(ctypes.libraryname("objc")); let id = ctypes.structtype("objc_object").ptr; let sel = ctypes.structtype("objc_
selector").ptr; let objc_getclass = objc.declare("objc_getclass", ctypes.default_abi, id, ctypes.char.ptr); let sel_registername = objc.declare("sel_registername", ctypes.default_abi, sel, ctypes.char.
Work with animations - Firefox Developer Tools
you more detailed information about the animation or transition, including: the type of animation: css transition, css animation, or web animations api the duration of the animation the animation's start and end delay the animation's easing (or timing function). the animation's fill the playback rate of the animation information about the animated element to the left of each bar is a
selector for the element that the animation applies to. if you hover over this
selector, the element is highlighted in the page. click the
selector to select the element in the inspector. to the left of the
selector is a "target" icon (). clicking this icon locks the highlighter on the element. animation details if you click one of the bars, you'll see details of all the properties that were changed in...
... }, { filter: 'grayscale(100%)', offset: 0.333 }, { transform: 'scale(1.5)', offset: 0.666 }, { transform: 'scale(1.5)', filter: 'grayscale(0%)' } ]; application to the example applying all this to our example, we can see that: the animation involved two elements, span#note and img#icon. hovering over these
selectors, we can see that those elements are, respectively, the browser name "firefox developer edition" and the browser icon. the img#icon animation: animated the filter and transform properties, to scale the icon and color it lasted 750ms, had an enddelay of 100ms used the compositor thread was given an easing value of ease-in: you can see this by the concave shape of the green bar. ...
Tips - Firefox Developer Tools
as right-click a node and click "scroll into view"). right-click a node and click "use in console" to command line as tempn variable. when selecting elements: shift + click to select an element but keep selecting (picker mode doesn't disengage). use ←/→ to navigate to parents/children elements (if they're hard to select). in the rules view: click the inspector icon () next to any
selector to highlight all elements that match it. click the inspector icon () next to the element{} rule to lock the highlighter on the current element. right-click any property and select "show mdn docs" to view the mdn docs for this property. click on the filter icon () next to an overridden property to find which other property overrides it. right-click on a name, value, or rule to copy anything fr...
...en property to find which other property overrides it. right-click on a name, value, or rule to copy anything from the name, the value, the declaration or the whole rule to your clipboard. web console in all panels: esc opens the split console; useful when debugging, or inspecting nodes in the command line: $0 references the currently selected node. $() is a shortcut to document.query
selector(). $$() returns an array with the results from document.query
selectorall(). copy copies anything as a string. right-click a node in the inspector and click "use in console" to create a tempn variable for it. cd switches the javascript evaluation context to a different iframe in the page. console.table() displays tabular data as table. help opens the mdn page describing the available command...
Animation.updatePlaybackRate() - Web APIs
is not immediately updated. it will be updated once the animation's ready promise is resolved. syntax animation.updateplaybackrate(2); parameters playbackrate the new speed to set. this may be a positive number (to speed up or slow down the animation), a negative number (to make it play backwards), or zero (to effectively pause the animation). return value none. ...
...imation.updateplaybackrate(2); parameters playbackrate the new speed to set. this may be a positive number (to speed up or slow down the animation), a negative number (to make it play backwards), or zero (to effectively pause the animation). return value none. examples a speed
selector component would benefit from smooth updating of updateplaybackrate(), as demonstrated below: speed
selector.addeventlistener('input', evt => { cartoon.updateplaybackrate(parsefloat(evt.target.value)); cartoon.ready.then(() => { console.log(`playback rate set to ${cartoon.playbackrate}`); }); }); specifications specification status comment web animationsthe definition of 'updateplaybackrate()' in that specification. working draft ...
AudioContext.createMediaStreamDestination() - Web APIs
ts to a url created from the blob. from here, you can play and save the opus file. ...
...osc.stop(0); e.target.disabled = true; } }); mediarecorder.ondataavailable = function(evt) { // push each chunk (blobs) in an array chunks.push(evt.data); }; mediarecorder.onstop = function(evt) { // make blob out of our blobs, and open it. var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); document.query
selector("audio").src = url.createobjecturl(blob); }; </script> </body> </html> note: you can view this example live, or study the source code, on github. specifications specification status comment web audio apithe definition of 'createmediastreamdestination()' in that specification. working draft ...
Body.text() - Web APIs
tifier passed to it as an argument — when one of the links is clicked. when getdata() is run, we create a new request using the request() constructor, then use it to fetch a specific .txt file. when the fetch is successful, we read a usvstring (text) object out of the response using text(), then set the innerhtml of the <article> element equal to the text object. ...
...f the links is clicked. when getdata() is run, we create a new request using the request() constructor, then use it to fetch a specific .txt file. when the fetch is successful, we read a usvstring (text) object out of the response using text(), then set the innerhtml of the <article> element equal to the text object. ...
CSSPseudoElement.type - Web APIs
the type read-only property of the csspseudoelement interface returns the type of the pseudo-element as a string, represented in the form of a css
selector. ...
...e returns the type of the pseudo-element as a string, represented in the form of a css
selector. syntax var typeofpseudoelement = csspseudoelement.type; value a cssomstring containing one of the following values: "::before" "::after" "::marker" examples the example below demonstrates the relationship between csspseudoelement.type and element.pseudo(): const myelement = document.query
selector('q'); const my
selector = '::after'; const csspseudoelement = myelement.pseudo(my
selector); const typeofpseudoelement = csspseudoelement.type; console.log(my
selector === typeofpseudoelement); // outputs true specifications specification status comment css pseudo-elements level 4the definition of 'type' in that specification. working draft initial definition. ...
CSSPseudoElement - Web APIs
the csspseudoelement interface represents a pseudo-element that may be the target of an event or animated using the web animations api. instances of this interface may be obtained by calling element.pseudo(). properties csspseudoelement.element read only returns the originating/parent element of the pseudo-element. csspseudoelement.type read only returns the pseudo-element
selector as a cssomstring. methods csspseudoelement extends eventtarget, so it inherits the following methods: eventtarget.addeventlistener() registers an event handler of a specific event type on the pseudo-element. eventtarget.dispatchevent() dispatches an event to this pseudo-element. eventtarget.removeeventlistener() removes an event listener from the pseudo-element. examples basic example using...
...element. examples basic example using element.pseudo using pseudo-elements, most modern browsers will automatically add quotation marks around text inside a <q> element. (a style rule may be needed to add quotation marks in older browsers.) the example below demonstrates the basic properties of the csspseudoelement object representing the opening quotation mark. const element = document.query
selector('q'); const csspseudoelement = element.pseudo('::before'); console.log(csspseudoelement.element); // outputs [object htmlquoteelement] console.log(csspseudoelement.type); // outputs '::before' specifications specification status comment css pseudo-elements level 4the definition of 'csspseudoelement' in that specification. working draft initial definition. ...
CanvasRenderingContext2D.arc() - Web APIs
es. the default is false (clockwise). examples drawing a full circle this example draws a complete circle with the arc() method. html <canvas></canvas> javascript the arc is given an x-coordinate of 100, a y-coordinate of 75, and a radius of 50. to make a full circle, the arc begins at an angle of 0 radians (0°), and ends at an angle of 2π radians (360°). ...
... an angle of 2π radians (360°). const canvas = document.query
selector('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(100, 75, 50, 0, 2 * math.pi); ctx.stroke(); result different shapes demonstrated this example draws various shapes to show what is possible with arc(). ...
Basic animations - Web APIs
tible" content="ie=edge"> <title>nokia 1100:snake..member berries</title> </head> <body> <div class="keypress hide"> <div class="up" onclick="emit(38)">↑</div> <div class="right" onclick="emit(39)">→</div> <div class="left" onclick="emit(37)">←</div> <div class="down" onclick="emit(40)">↓</div> </div> <div class="banner" id="
selector"> <div> time :<span id="time">0</span> </div> <div>lousygames ©</div> <div> score :<span id="score">0</span> </div> <div class="touch off" onclick="touch(this)">touch</div> </div> <canvas id="main"></canvas> </body> <style> body { margin: 0; overflow: hidden; background: #000 } .b...
...ckground: #000 } .banner { text-align: center; color: #fff; background: #3f51b5; line-height: 29px; position: fixed; left: 0; top: 0; right: 0; font-family: monospace; height: 30px; opacity: .4; display: flex; transition: .5s } .banner:hover { opacity: 1 } div#
selector>div { flex-basis: 30% } @keyframes diss { from { opacity: 1 } to { opacity: 0 } } .keypress>div { border: dashed 3px #fff; height: 48%; width: 48%; display: flex; align-content: center; justify-content: center; align-self: center; align-items: center; ...
Constraint validation API - Web APIs
e" required pattern="[a-za-z]+"> <button>submit</button> </form> the basic html form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. ...
...mit</button> </form> the basic html form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern. if you wanted to instead display custom error messages, you could use javascript like the following: const nameinput = document.query
selector('input'); const form = document.query
selector('form'); nameinput.addeventlistener('input', () => { nameinput.setcustomvalidity(''); nameinput.checkvalidity(); }); nameinput.addeventlistener('invalid', () => { if(nameinput.value === '') { nameinput.setcustomvalidity('enter your username!'); } else { nameinput.setcustomvalidity('usernames can only contain upper and lowercase letters. try again!'); } }); the example renders...
DOMTokenList - Web APIs
l values of the key/value pairs contained in this object. examples in the following simple example, we retrieve the list of classes set on a <p> element as a domtokenlist using element.classlist, add a class using domtokenlist.add(), and then update the node.textcontent of the <p> to equal the domtokenlist. first, the html: <p class="a b c"></p> now the javascript: let para = document.query
selector("p"); let classes = para.classlist; para.classlist.add("d"); para.textcontent = `paragraph classlist is "${classes}"`; the output looks like this: trimming of whitespace and removal of duplicates methods that modify the domtokenlist (such as domtokenlist.add()) automatically trim any excess whitespace and remove duplicate values from the list. for example: <span class=" d d e f"></span...
...asslist; para.classlist.add("d"); para.textcontent = `paragraph classlist is "${classes}"`; the output looks like this: trimming of whitespace and removal of duplicates methods that modify the domtokenlist (such as domtokenlist.add()) automatically trim any excess whitespace and remove duplicate values from the list. for example: <span class=" d d e f"></span> let span = document.query
selector("span"); let classes = span.classlist; span.classlist.add("x"); span.textcontent = `span classlist is "${classes}"`; the output looks like this: specifications specification status comment domthe definition of 'domtokenlist' in that specification. living standard initial definition ...
Document.adoptNode() - Web APIs
e(externalnode); parameters externalnode the node from another document to be adopted. return value the copied importednode in the scope of the importing document. after calling this method, importednode and externalnode are the same object. ...
...document to be adopted. return value the copied importednode in the scope of the importing document. after calling this method, importednode and externalnode are the same object. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.query
selector('iframe'); const iframeimages = iframe.contentdocument.query
selectorall('img'); const newparent = document.getelementbyid('images'); iframeimages.foreach(function(imgel) { newparent.appendchild(document.adoptnode(imgel)); }); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode(). best practice: although firefox doesn't curre...
Document.getElementById() - Web APIs
the document method getelementbyid() returns an element object representing the element whose id property matches the specified string. since element ids are required to be unique if specified, they're a useful way to get access to a specific element quickly. if you need to get access to an element which doesn't have an id, you can use query
selector() to find the element using any
selector. syntax var element = document.getelementbyid(id); parameters id the id of the element to locate. the id is case-sensitive string which is unique within the document; only one element may have any given id. return value an element object describing the dom element object matching the specified id, or null if no matching element was found in the document. example html <html> <head> <title>getele...
...ody> </html> javascript function changecolor(newcolor) { var elem = document.getelementbyid('para'); elem.style.color = newcolor; } result usage notes the capitalization of "id" in the name of this method must be correct for the code to function; getelementbyid() is not valid and will not work, however natural it may seem. unlike some other element-lookup methods such as document.query
selector() and document.query
selectorall(), getelementbyid() is only available as a method of the global document object, and not available as a method on all element objects in the dom. because id values must be unique throughout the entire document, there is no need for "local" versions of the function. example <!doctype html> <html> <head> <meta charset="utf-8"> <title>document</title> </head...
Document: gotpointercapture event - Web APIs
using setpointercapture(). bubbles no cancelable no interface pointerevent event handler property ongotpointercapture examples this example gets a <p> element and listens for the gotpointercapture event. it then calls setpointercapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
...a pointerdown event, which will trigger gotpointercapture. ...
Document: lostpointercapture event - Web APIs
released. bubbles no cancelable no interface pointerevent event handler property onlostpointercapture examples this example listens for the lostpointercapture event, and captures the pointer for an element on pointerdown. when the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
...pointer, the lostpointercapture event will be fired. ...
Examples of web and XML development using the DOM - Web APIs
tton" onclick="changetext();" /></p> </form> </body> </html> example 4: using stylesheets the stylesheets property on the document object returns a list of the stylesheets that have been loaded on that document. ...
... that have been loaded on that document. you can access these stylesheets and their rules individually using the stylesheet, style, and cssrule objects, as demonstrated in this example, which prints out all of the style rule
selectors to the console. ...
Element: auxclick event - Web APIs
examples in this example we define functions for two event handlers — onclick and onauxclick. the former changes the color of the button background, while the latter changes the button foreground (text) color. you also can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). ...
...ns for two event handlers — onclick and onauxclick. the former changes the color of the button background, while the latter changes the button foreground (text) color. you also can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). ...
Element: compositionend event - Web APIs
t composition system such as an input method editor completes or cancels the current composition session. for example, this event could be fired after a user finishes entering a chinese character using a pinyin ime. ...
...ss body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js const inputelement = document.query
selector('input[type="text"]'); const log = document.query
selector('.event-log-contents'); const clearlog = document.query
selector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', handleevent); inputelement.add...
Element: compositionstart event - Web APIs
nt is fired when a text composition system such as an input method editor starts a new composition session. for example, this event could be fired after a user starts entering a chinese character using a pinyin ime. ...
...ss body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js const inputelement = document.query
selector('input[type="text"]'); const log = document.query
selector('.event-log-contents'); const clearlog = document.query
selector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', handleevent); inputelement.add...
Element: compositionupdate event - Web APIs
in the context of a text composition session controlled by a text composition system such as an input method editor. for example, this event could be fired while a user enters a chinese character using a pinyin ime. ...
...ss body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js const inputelement = document.query
selector('input[type="text"]'); const log = document.query
selector('.event-log-contents'); const clearlog = document.query
selector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', handleevent); inputelement.add...
Element.computedStyleMap() - Web APIs
n list to which we will add all the css property / value pairs. <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a little bit of css a { --colour: red; color: var(--colour); } we add javascript to grab our link and return back a definition list of all the css property values using computedstylemap(). ...
...s://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a little bit of css a { --colour: red; color: var(--colour); } we add javascript to grab our link and return back a definition list of all the css property values using computedstylemap(). ...
Element.innerHTML - Web APIs
review, using innerhtml most likely will result in your code being rejected. for example, if you use innerhtml in a browser extension and submit the extension to addons.mozilla.org, it will not pass the automated review process. example this example uses innerhtml to create a mechanism for logging messages into a box on a web page. javascript function log(msg) { var logelem = document.query
selector(".log"); var time = new date(); var timestr = time.tolocaletimestring(); logelem.innerhtml += timestr + ": " + msg + "<br/>"; } log("logging mouse events inside this container..."); the log() function creates the log output by getting the current time from a date object using tolocaletimestring(), and building a string with the timestamp and the message text. then the message is appende...
... <div class="box"> <div><strong>log:</strong></div> <div class="log"></div> </div> the <div> w...
Element.toggleAttribute() - Web APIs
ntually present, and false otherwise. exceptions invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, toggleattribute() is used to toggle the readonly attribute of a <input>. ...
...ons invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, toggleattribute() is used to toggle the readonly attribute of a <input>. ...
Using Fetch - Web APIs
ontent-type': 'application/json', }, body: json.stringify(data), }) .then(response => response.json()) .then(data => { console.log('success:', data); }) .catch((error) => { console.error('error:', error); }); uploading a file files can be uploaded using an html <input type="file" /> input element, formdata() and fetch(). ...
...profile/avatar', { method: 'put', body: formdata }) .then(response => response.json()) .then(result => { console.log('success:', result); }) .catch(error => { console.error('error:', error); }); uploading multiple files files can be uploaded using an html <input type="file" multiple /> input element, formdata() and fetch(). ...
Using files from web applications - Web APIs
he dom file api in chrome code for details. accessing selected file(s) consider this html: <input type="file" id="input" multiple> the file api makes it possible to access a filelist containing file objects representing the files selected by the user. the multiple attribute on the input element allows the user to select multiple files. accessing the first selected file using a classical dom
selector: const selectedfile = document.getelementbyid('input').files[0]; accessing selected file(s) on a change event it is also possible (but not mandatory) to access the filelist through the change event. you need to use eventtarget.addeventlistener() to add the change event listener, like this: const inputelement = document.getelementbyid("input"); inputelement.addeventlistener("change", handlefil...
...ng the previous example) to a server. this can be done asynchronously very easily. creating the upload tasks continuing with the code that built the thumbnails in the previous example, recall that every thumbnail image is in the css class obj with the corresponding file attached in a file attribute. this allows us to select all of the images the user has chosen for uploading using document.query
selectorall(), like this: function sendfiles() { const imgs = document.query
selectorall(".obj"); for (let i = 0; i < imgs.length; i++) { new fileupload(imgs[i], imgs[i].file); } } line 2 fetches a nodelist, called imgs, of all the elements in the document with the css class obj. in our case, these will be all of the image thumbnails. once we have that list, it's trivial to go through it and ...
GlobalEventHandlers.onauxclick - Web APIs
t's more flexible. example in this example we define functions for two event handlers — onclick and onauxclick. the former changes the color of the button background, while the latter changes the button foreground (text) color. you can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). ...
...we define functions for two event handlers — onclick and onauxclick. the former changes the color of the button background, while the latter changes the button foreground (text) color. you can see the two functions in action by trying the demo out with a multi-button mouse (see it live on github; also see the source code). ...
GlobalEventHandlers.onkeypress - Web APIs
o use onkeydown instead. syntax target.onkeypress = functionref; value functionref is a function name or a function expression. the function receives a keyboardevent object as its sole argument. examples basic example this example logs the keyboardevent.code value whenever you press a key inside the <input> element. html <input> <p id="log"></p> javascript const input = document.query
selector('input'); const log = document.getelementbyid('log'); input.onkeypress = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result filter keys with a regular expression this example filters the characters typed into a form field using a regular expression. html <label>enter numbers only: <input> </label> javascript function numbersonly(event) { return event.charcode ...
...tion logkey(e) { log.textcontent += ` ${e.code}`; } result filter keys with a regular expression this example filters the characters typed into a form field using a regular expression. html <label>enter numbers only: <input> </label> javascript function numbersonly(event) { return event.charcode === 0 || /\d/.test(string.fromcharcode(event.charcode)); } const input = document.query
selector('input'); input.onkeypress = numbersonly; // prevent pasting (since pasted content might include non-number characters) input.onpaste = event => false; result capture the typing of a hidden word the following javascript function will do something after the user types the word "exit" in any point of a page. /* type the word "exit" in any point of your page... */ (function () { const ssec...
HTMLDialogElement: cancel event - Web APIs
bubbles no cancelable yes interface event event handler oncancel examples live example html <dialog class="example-dialog"> <button class="close" type="reset">close</button> </dialog> <button class="open-dialog">open dialog</button> <div class="result"></div> css button, div { margin: .5rem; } js const result = document.query
selector('.result'); const dialog = document.query
selector('.example-dialog'); dialog.addeventlistener('cancel', (event) => { result.textcontent = 'dialog was canceled'; }); const opendialog = document.query
selector('.open-dialog'); opendialog.addeventlistener('click', () => { if (typeof dialog.showmodal === 'function') { dialog.showmodal(); result.textcontent = ''; } else { res...
... living standard ...
HTMLDialogElement: close event - Web APIs
bubbles no cancelable no interface event event handler property onclose examples live example html <dialog class="example-dialog"> <button class="close" type="reset">close</button> </dialog> <button class="open-dialog">open dialog</button> <div class="result"></div> css button, div { margin: .5rem; } js const result = document.query
selector('.result'); const dialog = document.query
selector('.example-dialog'); dialog.addeventlistener('close', (event) => { result.textcontent = 'dialog was closed'; }); const opendialog = document.query
selector('.open-dialog'); opendialog.addeventlistener('click', () => { if (typeof dialog.showmodal === 'function') { dialog.showmodal(); result.textcontent = ''; } else { resul...
... living standard ...
HTMLElement: gotpointercapture event - Web APIs
sing setpointercapture(). bubbles yes cancelable no interface pointerevent event handler property ongotpointercapture examples this example gets a <p> element and listens for the gotpointercapture event. it then calls setpointercapture() on the element on a pointerdown event, which will trigger gotpointercapture. ...
... on a pointerdown event, which will trigger gotpointercapture. ...
HTMLElement: lostpointercapture event - Web APIs
bubbles yes cancelable no interface pointerevent event handler property onlostpointercapture examples this example listens for the lostpointercapture event for an element, and captures the pointer for the element on pointerdown. when the user subsequently releases the pointer, the lostpointercapture event will be fired. ...
...the pointer, the lostpointercapture event will be fired. ...
HTMLElement: pointercancel event - Web APIs
happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events. the touch-action css property prevents the input from continuing. after the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. ...
...events the input from continuing. after the pointercancel event is fired, the browser will also send pointerout followed by pointerleave. ...
HTMLElement: pointerdown event - Web APIs
essed to at least one button depressed. for touch, it is fired when physical contact is made with the digitizer. for pen, it is fired when the stylus makes physical contact with the digitizer. ...
...gitizer. ...
HTMLElement: pointerenter event - Web APIs
g device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see pointerdown). ...
...). ...
HTMLElement: pointerleave event - Web APIs
t is fired when a pointing device is moved out of the hit test boundaries of an element. for pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer. ...
...izer. ...
HTMLElement: pointermove event - Web APIs
nterevent event handler property onpointermove usage notes the event, which is of type pointerevent, provides all the information you need to know about the user's interaction with the pointing device, including the position, movement distance, button states, and much more. ...
...ction with the pointing device, including the position, movement distance, button states, and much more. ...
HTMLElement: pointerout event - Web APIs
p event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. ...
...e digitizer. ...
HTMLElement: transitionrun event - Web APIs
"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate where the transitionstart and transitionrun events fire. ...
...; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate where the transitionstart and transitionrun events fire. ...
HTMLElement: transitionstart event - Web APIs
.transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate where the transitionstart and transitionrun events fire. ...
...ground: rgba(255,0,0,1); transition-property: transform, background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate where the transitionstart and transitionrun events fire. ...
HTMLImageElement.naturalHeight - Web APIs
the html features a 400x398 pixel image which is placed inside a <div>. css .box { width: 200px; height: 200px; } .image { width: 100%; } .output { padding-top: 2em; } the main thing of note in the css above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). ...
... is placed inside a <div>. css .box { width: 200px; height: 200px; } .image { width: 100%; } .output { padding-top: 2em; } the main thing of note in the css above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). javascript let output = document.query
selector(".output"); let image = document.query
selector("img"); window.addeventlistener("load", event => { output.innerhtml += `natural size: ${image.naturalwidth} x ` + `${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simply dumps the natural and as-displayed sizes into the <div> with the class output. thi...
HTMLImageElement.naturalWidth - Web APIs
the html features a 400x398 pixel image which is placed inside a <div>. css .box { width: 200px; height: 200px; } .image { width: 100%; } .output { padding-top: 2em; } the main thing of note in the css above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). ...
... is placed inside a <div>. css .box { width: 200px; height: 200px; } .image { width: 100%; } .output { padding-top: 2em; } the main thing of note in the css above is that the style used for the container the image will be drawn in is 200px wide, and the image will be drawn to fill its width (100%). javascript let output = document.query
selector(".output"); let image = document.query
selector("img"); window.addeventlistener("load", event => { output.innerhtml += `natural size: ${image.naturalwidth} x ` + `${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simply dumps the natural and as-displayed sizes into the <div> with the class output. thi...
HTMLMediaElement: canplay event - Web APIs
event target element default action none event handler property globaleventhandlers.oncanplay specification html5 media examples these examples add an event listener for the htmlmediaelement's canplay event, then post a message when that event handler has reacted to the event firing. ...
... listener for the htmlmediaelement's canplay event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('canplay', (event) => { console.log('video can start, but not sure it will play through.'); }); using the oncanplay event handler property: const video = document.query
selector('video'); video.oncanplay = (event) => { console.log('video can start, but not sure it will play through.'); }; specifications specification status html living standardthe definition of 'canplay media event' in that specification. living standard html5the definition of 'canplay media event' in that specification. recommendation ...
HTMLMediaElement: canplaythrough event - Web APIs
target element default action none event handler property globaleventhandlers.oncanplaythrough specification html5 media examples these examples add an event listener for the htmlmediaelement's canplaythrough event, then post a message when that event handler has reacted to the event firing. ...
...post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('canplaythrough', (event) => { console.log('i think i can play through the entire ' + ' video without ever having to stop to buffer.'); }); using the oncanplaythrough event handler property: const video = document.query
selector('video'); video.oncanplaythrough = (event) => { console.log('i think i can play thru the entire ' + ' video without ever having to stop to buffer.'); }; specifications specification status html living standardthe definition of 'canplaythrough media event' in that specification. living standard html5the definition of 'canplaythrough media event' in that ...
HTMLMediaElement: durationchange event - Web APIs
target element default action none event handler property globaleventhandlers.ondurationchange specification html5 media examples these examples add an event listener for the htmlmediaelement's durationchange event, then post a message when that event handler has reacted to the event firing. ...
...aelement's durationchange event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('durationchange', (event) => { console.log('not sure why, but the duration of the video has changed.'); }); using the ondurationchange event handler property: const video = document.query
selector('video'); video.ondurationchange = (event) => { console.log('not sure why, but the duration of the video has changed.'); }; specifications specification status html living standardthe definition of 'durationchange media event' in that specification. living standard html5the definition of 'durationchange media event' in that specification. recommendation ...
HTMLMediaElement: ended event - Web APIs
event handler property globaleventhandlers.onended specification html5 media this event is also defined in media capture and streams and web audio api examples these examples add an event listener for the htmlmediaelement's ended event, then post a message when that event handler has reacted to the event firing. ...
...'s ended event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('ended', (event) => { console.log('video stopped either because 1) it was over, ' + 'or 2) no further data is available.'); }); using the onended event handler property: const video = document.query
selector('video'); video.onended = (event) => { console.log('video stopped either because 1) it was over, ' + 'or 2) no further data is available.'); }; specifications specification status html living standardthe definition of 'ended media event' in that specification. living standard html5the definition of 'ended media event' in that specification. recommend...
HTMLMediaElement: loadeddata event - Web APIs
venthandlers.onloadeddata specification html5 media note that this event will not fire in mobile/tablet devices if data-saver is on in browser settings. examples these examples add an event listener for the htmlmediaelement's loadeddata event, then post a message when that event handler has reacted to the event firing. ...
...hen post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('loadeddata', (event) => { console.log('yay! the readystate just increased to ' + 'have_current_data or greater for the first time.'); }); using the onloadeddata event handler property: const video = document.query
selector('video'); video.onloadeddata = (event) => { console.log('yay! the readystate just increased to ' + 'have_current_data or greater for the first time.'); }; specifications specification status html living standardthe definition of 'loadeddata media event' in that specification. living standard html5the definition of 'loadeddata media event' in that speci...
HTMLMediaElement: loadedmetadata event - Web APIs
mozsamplerate read only int the sample rate per second. mozframebufferlength read only int the number of samples collected in all channels. examples these examples add an event listener for the htmlmediaelement's loadedmetadata event, then post a message when that event handler has reacted to the event firing. ...
...ta event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('loadedmetadata', (event) => { console.log('the duration and dimensions ' + ' of the media and tracks are now known. '); }); using the onloadedmetadata event handler property: const video = document.query
selector('video'); video.onloadedmetadata = (event) => { console.log('the duration and dimensions ' + ' of the media and tracks are now known. '); }; specifications specification status html living standardthe definition of 'loadedmetadata media event' in that specification. living standard html5the definition of 'canplay media event' in that specification. r...
HTMLMediaElement: playing event - Web APIs
event target element default action none event handler property globaleventhandlers.onplaying specification html5 media examples these examples add an event listener for the htmlmediaelement's playing event, then post a message when that event handler has reacted to the event firing. ...
...hese examples add an event listener for the htmlmediaelement's playing event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('playing', (event) => { console.log('video is no longer paused'); }); using the onplaying event handler property: const video = document.query
selector('video'); video.onplaying = (event) => { console.log('video is no longer paused.'); }; specifications specification status html living standardthe definition of 'playing media event' in that specification. living standard html5the definition of 'playing media event' in that specification. recommendation ...
HTMLMediaElement: ratechange event - Web APIs
nt target element default action none event handler property globaleventhandlers.onratechange specification html5 media examples these examples add an event listener for the htmlmediaelement's ratechange event, then post a message when that event handler has reacted to the event firing. ...
...les add an event listener for the htmlmediaelement's ratechange event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('ratechange', (event) => { console.log('the playback rate changed.'); }); using the onratechange event handler property: const video = document.query
selector('video'); video.onratechange = (event) => { console.log('the playback rate changed.'); }; specifications specification status html living standardthe definition of 'ratechange media event' in that specification. living standard html5the definition of 'ratechange media event' in that specification. recommendation ...
HTMLMediaElement: seeked event - Web APIs
e event target element default action none event handler property globaleventhandlers.onseeked specification html5 media examples these examples add an event listener for the htmlmediaelement's seeked event, then post a message when that event handler has reacted to the event firing. ...
...t listener for the htmlmediaelement's seeked event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('seeked', (event) => { console.log('video found the playback position it was looking for.'); }); using the onseeked event handler property: const video = document.query
selector('video'); video.onseeked = (event) => { console.log('video found the playback position it was looking for.'); }; specifications specification status html living standardthe definition of 'seeked media event' in that specification. living standard html5the definition of 'seeked media event' in that specification. recommendation ...
HTMLMediaElement: seeking event - Web APIs
event target element default action none event handler property globaleventhandlers.onseeking specification html5 media examples these examples add an event listener for the htmlmediaelement's seeking event, then post a message when that event handler has reacted to the event firing. ...
...amples add an event listener for the htmlmediaelement's seeking event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('seeking', (event) => { console.log('video is seeking a new position.'); }); using the onseeking event handler property: const video = document.query
selector('video'); video.onseeking = (event) => { console.log('video is seeking a new position.'); }; specifications specification status html living standardthe definition of 'seeking media event' in that specification. living standard html5the definition of 'seeking media event' in that specification. recommendation ...
HTMLMediaElement: stalled event - Web APIs
event target element default action none event handler property globaleventhandlers.onstalled specification html5 media examples these examples add an event listener for the htmlmediaelement's stalled event, then post a message when that event handler has reacted to the event firing. ...
...mples add an event listener for the htmlmediaelement's stalled event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('stalled', (event) => { console.log('failed to fetch data, but trying.'); }); using the onstalled event handler property: const video = document.query
selector('video'); video.onstalled = (event) => { console.log('failed to fetch data, but trying.'); }; specifications specification status html living standardthe definition of 'stalled media event' in that specification. living standard html5the definition of 'stalled media event' in that specification. recommendation ...
HTMLMediaElement: suspend event - Web APIs
event target element default action none event handler property globaleventhandlers.onsuspend specification html5 media examples these examples add an event listener for the htmlmediaelement's suspend event, then post a message when that event handler has reacted to the event firing. ...
...amples add an event listener for the htmlmediaelement's suspend event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('suspend', (event) => { console.log('data loading has been suspended.'); }); using the onsuspend event handler property: const video = document.query
selector('video'); video.onsuspend = (event) => { console.log('data loading has been suspended.'); }; specifications specification status html living standardthe definition of 'suspend media event' in that specification. living standard html5the definition of 'suspend media event' in that specification. recommendation ...
HTMLMediaElement: volumechange event - Web APIs
target element default action none event handler property globaleventhandlers.onvolumechange specification html5 media examples these examples add an event listener for the htmlmediaelement's volumechange event, then post a message when that event handler has reacted to the event firing. ...
...ples add an event listener for the htmlmediaelement's volumechange event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('volumechange', (event) => { console.log('the volume changed.'); }); using the onvolumechange event handler property: const video = document.query
selector('video'); video.onvolumechange = (event) => { console.log('the volume changed.'); }; specifications specification status html living standardthe definition of 'volumechange media event' in that specification. living standard html5the definition of 'volumechange media event' in that specification. recommendation ...
HTMLMediaElement: waiting event - Web APIs
event target element default action none event handler property globaleventhandlers.onwaiting specification html5 media examples these examples add an event listener for the htmlmediaelement's waiting event, then post a message when that event handler has reacted to the event firing. ...
...xamples add an event listener for the htmlmediaelement's waiting event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('waiting', (event) => { console.log('video is waiting for more data.'); }); using the onwaiting event handler property: const video = document.query
selector('video'); video.onwaiting = (event) => { console.log('video is waiting for more data.'); }; specifications specification status html living standardthe definition of 'waiting media event' in that specification. living standard html5the definition of 'waiting media event' in that specification. recommendation ...
ImageCapture.getPhotoCapabilities() - Web APIs
lue a promise that resolves with a photocapabilities object. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
...solution sample, uses the results from getphotocapabilities() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
ImageCapture.getPhotoSettings() - Web APIs
whether the red-eye reduction should be used if it is available. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotosettings() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
...to resolution sample, uses the results from getphotosettings() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
ImageCapture.grabFrame() - Web APIs
st bitmappromise = imagecapture.grabframe() return value a promise that resolves to an imagebitmap object. example this example is extracted from this simple image capture demo. it shows how to use the promise returned by grabframe() to copy the returned frame to a <canvas> element. for simplicy it does not show how to instantiate the imagecapture object. ...
...e a promise that resolves to an imagebitmap object. example this example is extracted from this simple image capture demo. it shows how to use the promise returned by grabframe() to copy the returned frame to a <canvas> element. for simplicy it does not show how to instantiate the imagecapture object. ...
ImageCapture.takePhoto() - Web APIs
he red-eye reduction should be used if it is available. return value a promise that resolves with a blob. example this example is extracted from this simple image capture demo. it shows how to use the promise returned by takephoto() to copy the returned blob to an <img> element. for simplicy it does not show how to instantiate the imagecapture object. ...
... return value a promise that resolves with a blob. example this example is extracted from this simple image capture demo. it shows how to use the promise returned by takephoto() to copy the returned blob to an <img> element. for simplicy it does not show how to instantiate the imagecapture object. ...
Key Values - Web APIs
ncluded where available. learn how to use these key values in javascript using keyboardevent.key special values | modifier keys | whitespace keys | navigation keys | editing keys | ui keys | device keys | ime and composition keys | function keys | phone keys | multimedia keys | audio control keys | tv control keys | media controller keys | speech recognition keys | document keys | application
selector keys | browser control keys | numeric keypad keys special values values of key which have special meanings other than identifying a specific key or character. keyboardevent.key value description virtual keycode windows mac linux android "unidentified" the user agent wasn't able to map the event's virtual keycode to a specific key value. ...
...ilreply" [1] opens the user interface to reply to a message. appcommand_reply_to_mail gdk_key_reply (0x1008ff72) qt::key_reply (0x010000e5) "mailsend" [1] sends the current message. appcommand_send_mail gdk_key_send (0x1008ff7b) qt::key_send (0x010000eb) [1] prior to firefox 37, this key generated the key value "unidentified". application
selector keys some keyboards offer special keys for launching or switching to certain common applications. key values for those are listed here. keyboardevent.key value description virtual keycode windows mac linux android "launchcalculator" [5] the calculator key, often labeled with an icon. this is often used as a generic application launcher key (appcomman...
MediaDevices.getUserMedia() - Web APIs
ontents of a frame. examples width and height this example gives a preference for camera resolution, and assigns the resulting mediastream object to a video element. // prefer camera resolution nearest to 1280x720. var constraints = { audio: true, video: { width: 1280, height: 720 } }; navigator.mediadevices.getusermedia(constraints) .then(function(mediastream) { var video = document.query
selector('video'); video.srcobject = mediastream; video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end. using the new api in older browsers here's an example of using navigator.mediadevices.getusermedia(), with a polyfill to cope with older browsers. note that this polyfill does ...
... video.src = window.url.createobjecturl(stream); } video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); frame rate low...
MediaDevices - Web APIs
ing purposes. returns a promise that resolves to a mediastream. getusermedia() with the user's permission through a prompt, turns on a camera and/or a microphone on the system and provides a mediastream containing a video track and/or an audio track with the input. example 'use strict'; // put variables in global scope to make them available to the browser console. ...
...turns on a camera and/or a microphone on the system and provides a mediastream containing a video track and/or an audio track with the input. example 'use strict'; // put variables in global scope to make them available to the browser console. ...
MediaSettingsRange - Web APIs
s. mediasettingsrange.min returns the minimum value of this setting. mediasettingsrange.step returns the minimum difference between consecutive values of this setting. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities().imagewidth to modify the size of an input range. ...
...tive values of this setting. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities().imagewidth to modify the size of an input range. ...
MessageChannel() - Web APIs
constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. ...
... we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. ...
MessageChannel.port1 - Web APIs
aded, we pass messagechannel.port2 to the <iframe> using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is associated to the port1 to listen when the message arrives. ...
...e <iframe> using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph. the handlemessage method is associated to the port1 to listen when the message arrives. ...
MessageChannel.port2 - Web APIs
constructor. when the iframe has loaded, we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. ...
... we pass port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph. messagechannel.port1 is listened to, to check when the message arrives. ...
MessageChannel - Web APIs
ssagechannel constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph. ...
...oaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph. ...
MessagePort.onmessage - Web APIs
tructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. ...
...pass messagechannel.port2 to the iframe using messageport.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. ...
MessagePort.postMessage() - Web APIs
constructor. when the iframe has loaded, we pass messagechannel.port2 to the iframe using window.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. ...
..., we pass messagechannel.port2 to the iframe using window.postmessage along with a message. the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives. ...
MessagePort - Web APIs
sagechannel() constructor. when the iframe has loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph. ...
...loaded, we register an onmessage handler for messagechannel.port1 and transfer messagechannel.port2 to the iframe using the window.postmessage method along with a message. when a message is received back from the iframe, the onmessage function simply outputs the message to a paragraph. ...
MouseEvent.button - Web APIs
n actions reversed. some pointing devices only have one button and use keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. others may have many buttons mapped to different functions and button values. ...
...y have one button and use keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. others may have many buttons mapped to different functions and button values. ...
Using Navigation Timing - Web APIs
collecting timing information using the api is as simple as obtaining the performance object using window.performance and looking up what you need within the object returned. for example, to measure the perceived loading time for a page: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; document.query
selector(".output").innertext = loadingtime + " ms"; }, false); this code, executed when the load event occurs, subtracts from the current time the time at which the navigation whose timing was recorded began (performance.timing.navigationstart), and outputs that information to the screen by inserting it into an element. html <div class="output"> </div> css .output { border: 1px solid #bbb...
...performance.navigation.type indicates what kind of load operation took place: a navigation, a reload, or a shift through the browser's history. we also obtain the number of redirects that were incurred during the navigation from performance.navigation.redire...
Navigator.getUserMedia() - Web APIs
aints, and settings. successcallback a function which is invoked when the request for media access is approved. the function is called with one parameter: the mediastream object that contains the media stream. your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following example: function(stream) { var video = document.query
selector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here. }; } errorcallback when the call fails, the function specified in the errorcallback is invokedwith a mediastreamerror object as its sole argument; this object is is modeled on domexception. see {anch("errors")}} below for a list of the errors which can occur. return...
... section under the mediadevices.getusermedia() for modern examples. ...
Navigator.share() - Web APIs
er is not correctly specified, and will also reject if the user cancels sharing. examples in our web share test (see the source code) there is a button which, when clicked, invokes the web share api to share mdn's url. ...
...f the user cancels sharing. examples in our web share test (see the source code) there is a button which, when clicked, invokes the web share api to share mdn's url. the javascript looks like this: const sharedata = { title: 'mdn', text: 'learn web development on mdn!', url: 'https://developer.mozilla.org', } const btn = document.query
selector('button'); const resultpara = document.query
selector('.result'); // must be triggered some kind of "user activation" btn.addeventlistener('click', async () => { try { await navigator.share(sharedata) resultpara.textcontent = 'mdn shared successfully' } catch(err) { resultpara.textcontent = 'error: ' + err } }); sharing files to share files, first test for and call navigator.canshare(). then include an array of files in the call...
PhotoCapabilities - Web APIs
fill light options. options may include auto, off, or flash. example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
...solution sample, uses the results from getphotocapabilities() to modify the size of an input range. this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream. ...
RTCPeerConnection: iceconnectionstatechange event - Web APIs
n. in this example, a handler for iceconnectionstatechange is set up to update a call state indicator by using the value of iceconnectionstate to create a string which corresponds to the name of a css class that we can assign to the status indicator to cause it to reflect the current state of the connection. ...
...css class that we can assign to the status indicator to cause it to reflect the current state of the connection. pc.addeventlistener("iceconnectionstatechange", ev => { let stateelem = document.query
selector("#call-state"); stateelem.classname = `${pc.iceconnectionstate}-state`; }, false); this can also be written as: pc.oniceconnectionstatechange = ev => { let stateelem = document.query
selector("#call-state"); stateelem.classname = `${pc.iceconnectionstate}-state`; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'iceconnectionstatechange' in that specification. candidate recommendation ...
Request() - Web APIs
om. example in our fetch request example (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call. since we are fetching an image, we run body.blob on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
...}); note that you could also pass the init object into the fetch call to get t...
Response.clone() - Web APIs
ponse clone live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(). when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements. ...
...ct using the request() constructor, passing it a jpg path. we then fetch this request using fetch(). when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements. ...
ServiceWorker - Web APIs
mple (live demo). the code listens for any change in the serviceworker.state and returns its value. ...
...register('service-worker.js', { scope: './' }).then(function (registration) { var serviceworker; if (registration.installing) { serviceworker = registration.installing; document.query
selector('#kind').textcontent = 'installing'; } else if (registration.waiting) { serviceworker = registration.waiting; document.query
selector('#kind').textcontent = 'waiting'; } else if (registration.active) { serviceworker = registration.active; document.query
selector('#kind').textcontent = 'active'; } if (serviceworker) { // logstate(serviceworker.state); serviceworker.addeventlistener('statechange', function (e) { // logstate(e.target.state); ...
StylePropertyMapReadOnly.get() - Web APIs
css, including a custom property and an inhertable property: p { font-weight: bold; } a { --colour: red; color: var(--colour); } we use the element's computedstylemap() to return a stylepropertymapreadonly object. we create an array of properties of interest and use the stylepropertymapreadonly's get() method to get only those values. ...
...d; } a { --colour: red; color: var(--colour); } we use the element's computedstylemap() to return a stylepropertymapreadonly object. we create an array of properties of interest and use the stylepropertymapreadonly's get() method to get only those values. ...
StylePropertyMapReadOnly - Web APIs
touch of css with a custom property to better demonstrate the output: p { --somevariable: 1.6em; --someothervariable: translatex(33vw); --anothervariable: 42; line-height: var(--somevariable); } we add javascript to grab our paragraph and return back a definition list of all the default css property values using computedstylemap(). ...
...ariable: 1.6em; --someothervariable: translatex(33vw); --anothervariable: 42; line-height: var(--somevariable); } we add javascript to grab our paragraph and return back a definition list of all the default css property values using computedstylemap(). ...
SubtleCrypto.deriveKey() - Web APIs
c key. let alicessecretkey = await derivesecretkey(aliceskeypair.privatekey, bobskeypair.publickey); // bob generates the same secret key using his private key and alice's public key. let bobssecretkey = await derivesecretkey(bobskeypair.privatekey, aliceskeypair.publickey); // alice can then use her copy of the secret key to encrypt a message to bob. ...
... = await derivesecretkey(bobskeypair.privatekey, aliceskeypair.publickey); // alice can then use her copy of the secret key to encrypt a message to bob. let encryptbutton = document.query
selector(".ecdh .encrypt-button"); encryptbutton.addeventlistener("click", () => { encrypt(alicessecretkey); }); // bob can use his copy to decrypt the message. let decryptbutton = document.query
selector(".ecdh .decrypt-button"); decryptbutton.addeventlistener("click", () => { decrypt(bobssecretkey); }); } pbkdf2 in this example we ask the user for a password, then use it to derive an aes key using pbkdf2, then use the aes key to encrypt a message. see the complete code on github. /* get some key material to use as input to the derivekey method. the key material is a password supplied ...
TextEncoder.prototype.encodeInto() - Web APIs
w textencoder; function encodeintowithsentinel(string, u8array, position) { var stats = encoder.encodeinto(string, position ? ...
... u8array, position) { var stats = encoder.encodeinto(string, position ? ...
Basic scissoring - Web APIs
canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) {...
... canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { paragraph.innerhtml = "failed to get we...
Color masking - Web APIs
: inherit; font-weight : 900; color : white; margin : auto; padding : 0.6em 1.2em; } #red-toggle { background-color : red; } #green-toggle { background-color : green; } #blue-toggle { background-color : blue; } window.addeventlistener("load", function setupanimation (evt) { "use strict" window.removeeventlistener(evt.type, setupanimation, false); var canvas = document.query
selector("canvas"); var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.query
selector("p").innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); var timer = setinterval(drawanimation, 1000); var mask ...
... || canvas.getcontext("experimental-webgl"); if (!gl) { document.query
selector("p").innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); var timer = setinterval(drawanimation, 1000); var mask = [true, true, true]; var redtoggle = document.query
selector("#red-toggle"), greentoggle = document.query
selector("#green-toggle"), bluetoggle = document.query
selector("#blue-toggle"); redtoggle.addeventlistener("click", setcolormask, false); greentoggle.addeventlistener("click", setcolormask, false); bluetoggle.addeventlistener("click", setcolormask, false); function setcolormask(evt) { var index = evt.target === greentoggle && ...
Raining rectangles - Web APIs
"use strict" window.addeventlistener("load", setupanimation, false); var gl, timer, rainingrect, scoredisplay, missesdisplay; function setupanimation (evt) { window.removeeventlistener(evt.type, setupanimation, false); if (!(gl = getrenderingcontext())) return; gl.enable(gl.scissor_test); rainingrect = new rectangle(); timer = settimeout(drawanimation, 17); document.query
selector("canvas") .addeventlistener("click", playerclick, false); var displays = document.query
selectorall("strong"); scoredisplay = displays[0]; missesdisplay = displays[1]; } var score = 0, misses = 0; function drawanimation () { gl.scissor(rainingrect.position[0], rainingrect.position[1], rainingrect.size[0] , rainingrect.size[1]); gl.clear(gl.color_buffer_bit); rainingrect.
...ion = [ randnums[2]*(gl.drawingbufferwidth - rect.size[0]), gl.drawingbufferheight ]; rect.velocity = 1.0 + 6.0*math.random(); rect.color = getrandomvector(); gl.clearcolor(rect.color[0], rect.color[1], rect.color[2], 1.0); function getrandomvector() { return [math.random(), math.random(), math.random()]; } } function getrenderingcontext() { var canvas = document.query
selector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { var paragraph = document.query
selector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.dr...
Web Audio API best practices - Web APIs
we handle this? when you create an audio context (either offline or online) it is created with a state, which can be suspended, running, or closed. when working with an audiocontext, if you create the audio context from inside a click event the state should automatically be set to running. here is a simple example of creating the context from inside a click event: const button = document.query
selector('button'); button.addeventlistener('click', function() { const audioctx = new audiocontext(); }, false); if however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction. we can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume() met...
...octx = new audiocontext(); }, false); if however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction. we can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume() method. const audioctx = new audiocontext(); const button = document.query
selector('button'); button.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } }, false); you might instead be working with an offlineaudiocontext, in which case you can resume the suspended audio context with the startrendering() method. user control if your website or appl...
Controlling multiple parameters with ConstantSourceNode - Web APIs
ogether. playing a boolean that we'll use to keep track of whether or not we're currently playing the tones. now let's look at the setup() function, which is our handler for the window's load event; it handles all the initialization tasks that require the dom to be in place. ...
... of whether or not we're currently playing the tones. now let's look at the setup() function, which is our handler for the window's load event; it handles all the initialization tasks that require the dom to be in place. ...
Example and tutorial: Simple synth keyboard - Web APIs
t up to be ready to contain a list of all currently-playing oscillators. it starts off empty, since there are none playing yet. mastergainnode is set to null; during the setup process, it will be configured to contain a gainnode which all playing oscillators will connect to and play through to allow the overall volume to be controlled using a single slider control. let keyboard = document.query
selector(".keyboard"); let wavepicker = document.query
selector("select[name='waveform']"); let volumecontrol = document.query
selector("input[name='volume']"); references to elements we'll need access to are obtained: keyboard is the container element into which the keys will be placed. wavepicker is the <select> element used to choose the waveform to use for the notes. volumecontrol is the <input> ...
...f class "octave". ...
Using the Web Storage API - Web APIs
fired for sessionstorage changes). this won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. pages on other domains can't access the same storage objects. ...
... same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. pages on other domains can't access the same storage objects. on the events page (see events.js) the only javascript is as follows: window.addeventlistener('storage', function(e) { document.query
selector('.my-key').textcontent = e.key; document.query
selector('.my-old').textcontent = e.oldvalue; document.query
selector('.my-new').textcontent = e.newvalue; document.query
selector('.my-url').textcontent = e.url; document.query
selector('.my-storage').textcontent = json.stringify(e.storagearea); }); here we add an event listener to the window object that fires when the storage object associated with the current origin is changed. as you can see above...
Using Web Workers - Web APIs
e. </script> <script type="text/javascript"> // this script will be parsed by js engines because its mime type is text/javascript. function pagelog(smsg) { // use a fragment: browser will only render/reflow once. var ofragm = document.createdocumentfragment(); ofragm.appendchild(document.createtextnode(smsg)); ofragm.appendchild(document.createelement('br')); document.query
selector('#logdisplay').appendchild(ofragm); } </script> <script type="text/js-worker"> // this script won't be parsed by js engines because its mime type is text/js-worker. onmessage = function(oevent) { postmessage(myvar); }; // rest of your worker code goes here. </script> <script type="text/javascript"> // this script will be parsed by js engines because its mime type is text/javascrip...
...e type is text/js-worker. onmessage = function(oevent) { postmessage(myvar); }; // rest of your worker code goes here. </script> <script type="text/javascript"> // this script will be parsed by js engines because its mime type is text/javascript. // in the past...: // blob builder existed // ...but now we use blob...: var blob = new blob(array.prototype.map.call(document.query
selectorall('script[type=\'text\/js-worker\']'), function (oscript) { return oscript.textcontent; }),{type: 'text/javascript'}); // creating a new document.worker property containing all our "text/js-worker" scripts. document.worker = new worker(window.url.createobjecturl(blob)); document.worker.onmessage = function(oevent) { pagelog('received: ' + oevent.data); }; // start the worker. ...
Window.getDefaultComputedStyle() - Web APIs
window.getdefaultcomputedstyle(elem).position; document.getelementbyid("output").innerhtml = thecssprop; // will output "static" </script> use with pseudo-elements the getdefaultcomputedstyle() method can pull style info from pseudo-elements (e.g., ::before or ::after). <style> h3:after { content: ' rocks!'; } </style> <h3>generated content</h3> <script> var h3 = document.query
selector('h3'), result = getdefaultcomputedstyle(h3, ':after').content; console.log('the generated content is: ', result); // returns 'none' </script> notes the returned value is, in certain known cases, expressly incorrect by deliberate intent. in particular, to avoid the so called css history leak security issue, browsers may expressly "lie" about the used value for a link and always retur...
.../ returns 'none' </script> notes the returned value is, in certain known cases, expressly incorrect by deliberate intent. in particular, to avoid the so called css history leak security issue, browsers may expressly "lie" about the used value for a link and always return values as if a user has never visited the linked site, and/or limit the styles that can be applied using the :visited pseudo-
selector. see http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/ and http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/ for details of the examples of how this is implemented. specifications proposed to the css working group. ...
window.location - Web APIs
nullam ultrices dolor ac dolor imperdiet ullamcorper. suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. quisque in ante ...
... _itframe++; } function _chkowner () { if (_isbot) { _isbot = false; return; } if (_scrollid > -1) { clearinterval(_scrollid); _scrollid = -1; } } if (window.addeventlistener) { window.addeventlistener("scroll", _chkowner, false); } else if (window.attachevent) { window.attachevent("onscroll", _chkowner); } return function (sbookmark, busehash) { var onode = document.query
selector(sbookmark); _scrolly = document.documentelement.scrolltop; _scrollx = document.documentelement.scrollleft; _bookmark = sbookmark; _usehash = busehash === true; _nodex = onode.offsetleft; _nodey = onode.offsettop; _itframe = 1; if (_scrollid === -1) { _scrollid = setinterval(_next, math.round(nduration / nframes)); } }; })(); specifications specification status...
Window: resize event - Web APIs
example reports the window size each time it is resized. bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. ...
.... bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. ...
WindowOrWorkerGlobalScope.fetch() - Web APIs
der. examples in our fetch request example (see fetch request live) we create a new request object using the relevant constructor, then fetch it using a fetch() call. since we are fetching an image, we run body.blob() on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
...}); you could also pass the init object in with the request constructor to get the same effect: let myreques...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
color() { clearinterval(nintervid); } </script> </head> <body onload="changecolor();"> <div id="my_box"> <p>hello world</p> </div> <button onclick="stoptextcolor();">stop</button> </body> </html> example 3: typewriter simulation the following example simulates typewriter by first clearing and then slowly typing content into the nodelist that matches a specified group of
selectors. <!doctype html> <html> <head> <meta charset="utf-8" /> <title>javascript typewriter - mdn example</title> <script> function typewriter (s
selector, nrate) { function clean () { clearinterval(nintervid); btyping = false; bstart = true; ocurrent = null; asheets.length = nidx = 0; } function scroll (osheet, npos, beraseandstop) { if (!osheet.hasownproperty('parts'...
....parts.length; nchild++) { onode.removechild(this.parts[nchild]); this.parts[nchild] = new sheet(this.parts[nchild]); } } var nintervid, ocurrent = null, btyping = false, bstart = true, nidx = 0, spart = "", asheets = [], amap = []; this.rate = nrate || 100; this.play = function () { if (btyping) { return; } if (bstart) { var aitems = document.query
selectorall(s
selector); if (aitems.length === 0) { return; } for (var nitem = 0; nitem < aitems.length; nitem++) { asheets.push(new sheet(aitems[nitem])); /* uncomment the following line if you have previously hidden your elements via css: */ // aitems[nitem].style.visibility = "visible"; } bstart = false; } nintervid = setinterval(typewrite, this...
ARIA: switch role - Accessibility
<button role="switch" aria-checked="true" id="speakerpower" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerpower" class="switch">speaker power</label> javascript this javascript code defines and applies a function to handle click events on switch widgets. the function changes the aria-checked attribute from true to false, or vice versa. ...
... result the result looks like this: specifications specification status comment accessible rich internet applications (wai-aria) 1.1 recommendation defines aria in general along with all roles, properties,...
An overview of accessible web applications and widgets - Accessibility
visibility changes when content visibility is changed (i.e., an element is hidden or shown), developers should change the aria-hidden property value. the techniques described above should be used to declare css to visually hide an element using display:none. here is an e...
...labelledby="tp1-label" aria-describedby="tp1" aria-required="false" /> <div id="tp1" class="tooltip" role="tooltip" aria-hidden="true">your first name is optional</div> </div> the css for this markup is shown in example 2b. note that there is no custom classname used, only the status of the aria-hidden attribute on line 1. example 2b. attribute-based
selector for indicating state div.tooltip[aria-hidden="true"] { display: none; } the javascript to update the aria-hidden property has the form shown in example 2c. note that the script only updates the aria-hidden attribute (line 2); it does not need to also add or remove a custom classname. example 2c. javascript to update the aria-checked attribute var showtip = function(el) { el.setattribute...
-webkit-box-reflect - CSS: Cascading Style Sheets
eapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ above | below | right | left ]? <length>? <image>?where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
:-moz-locale-dir(ltr) - CSS: Cascading Style Sheets
the :-moz-locale-dir(ltr) css pseudo-class is a mozilla extension that matches an element if the user interface is being displayed left-to-right. this is determined by the preference intl.uidirection.locale (where locale is the current locale) being set to "ltr". note: this
selector is mainly used by extensions and themes to adapt the user interface based on the user's locale. (this can vary from window to window, and even from tab to tab.) it also allows extensions to work even when they don't support the user's default locale, since they can support both left-to-right and right-to-left layouts regardless of locale specifics. this
selector does not work properly from html; it always matches, regardless of whether the ui locale is left-to-right or right-to-left. syntax :-moz-loc...
...it was designed for use with xul. ...
:-moz-locale-dir(rtl) - CSS: Cascading Style Sheets
the :-moz-locale-dir(rtl) css pseudo-class is a mozilla extension that matches an element if the user interface is being displayed right-to-left. this is determined by the preference intl.uidirection.locale (where locale is the current locale) being set to "rtl". note: this
selector is mainly used by extensions and themes to adapt the user interface based on the user's locale. (this can vary from window to window, and even from tab to tab.) it also allows extensions to work even when they don't support the user's default locale, since they can support both left-to-right and right-to-left layouts regardless of locale specifics. this
selector does not work properly from html; it never matches, no matter whether the ui locale is left-to-right or right-to-left. syntax :-moz-locale-d...
...can support both left-to-right and right-to-left layouts regardless of locale specifics. this
selector does not work properly from html; it never matches, no matter whether the ui locale is left-to-right or right-to-left. syntax :-moz-locale-dir(rtl) examples this example will not work if you're not using firefox, and might not work properly even in firefox due to an issue with using this
selector in html. html <p>if you're using a right-to-left interface, this should be red.</p> css p:-moz-locale-dir(rtl) { color: red; } result specifications not part of any standard. ...
:-moz-only-whitespace - CSS: Cascading Style Sheets
note: in
selectors level 4 the :empty
selector was changed to act like :-moz-only-whitespace, but no browser currently supports this yet. the :-moz-only-whitespace css pseudo-class matches elements that only contains text nodes that only contain whitespace. ...
... ...
::after (:after) - CSS: Cascading Style Sheets
ackground-color: #ffba10; border-color: black; border-style: dotted; } result tooltips this example uses ::after, in conjunction with the attr() css expression and a data-descr custom data attribute, to create tooltips. no javascript is required! we can also support keyboard users with this technique, by adding a tabindex of 0 to make each span keyboard focusable, and using a css :focus
selector. this shows how flexible ::before and ::after can be, though for the most accessible experience a semantic disclosure widget created in some other way (such as with details and summary elements) is likely to be more appropriate. html <p>here we have some <span tabindex="0" data-descr="collection of words and punctuation">text</span> with a few <span tabindex="0" data-descr="small popups tha...
... specification status comment css pseudo-elements level 4the definition of '::after' in that specification. working draft no significant changes to the previous specification. css animationsthe definition of 'animations on pseudo-element properties' in that specification. working draft allows animations on properties defined on pseudo-elements.
selectors level 3the definition of '::after' in that specification. recommendation introduces the two-colon syntax. css level 2 (revision 1)the definition of '::after' in that specification. recommendation initial definition, using the one-colon syntax. ...
::before (:before) - CSS: Cascading Style Sheets
note that there are no icons used, and the check-mark is actually the ::before that has been styled in css. go ahead and get some stuff done. result special characters as this is css; not html, you can ...
...de leftwards white arrow*/ display: inline; } result specifications specification status comment css pseudo-elements level 4the definition of '::before' in that specification. working draft no significant changes to the previous specification. css animations working draft allows animations on properties defined on pseudo-elements.
selectors level 3the definition of '::before' in that specification. recommendation introduces the two-colon syntax. css level 2 (revision 1)the definition of '::before' in that specification. recommendation initial definition, using the one-colon syntax ...
::cue-region - CSS: Cascading Style Sheets
ns and other cues in media with vtt tracks. ::cue-region { color: yellow; font-weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only exception is that background and its shorthand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. ...
...ue-region { color: yellow; font-weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only exception is that background and its shorthand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. ...
::cue - CSS: Cascading Style Sheets
e used to style captions and other cues in media with vtt tracks. ::cue { color: yellow; font-weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only exception is that background and its longhand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. ...
... with vtt tracks. ::cue { color: yellow; font-weight: bold; } the properties are applied to the entire set of cues as if they were a single unit. the only exception is that background and its longhand properties apply to each cue individually, to avoid creating boxes and obscuring unexpectedly large areas of the media. ...
:any-link - CSS: Cascading Style Sheets
in other words, it matches every <a>, <area>, or <link> element that has an href attribute. thus, it matches all elements that match :link or :visited. ...
... working draft initial definition. ...
:checked - CSS: Cascading Style Sheets
/* matches any checked/selected radio, checkbox, or option */ :checked { margin-left: 25px; border: 1px solid blue; } the user can engage this state by checking/selecting an element, or disengage it by unchecking/deselecting the element. note: because browsers often treat <option>s as replaced elements, the extent to which they can be styled with the :checked pseudo-class varies from browser to browser. ...
...ass and without hidden radioboxes, see this demo, taken from the :hover reference page. specifications specification status comment html living standardthe definition of ':checked' in that specification. living standard no change. html5the definition of ':checked' in that specification. recommendation defines the semantic regarding html.
selectors level 4the definition of ':checked' in that specification. working draft no change.
selectors level 3the definition of ':checked' in that specification. recommendation defines the pseudo-class, but not the associated semantic browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please ...
:default - CSS: Cascading Style Sheets
multiple <select>s can have more than one selected option, so all will match :default. <input type="checkbox"> and <input type="radio"> match if they have the checked attribute. ...
... working draft no change. ...
:dir() - CSS: Cascading Style Sheets
t-to-left text */ :dir(rtl) { background-color: red; } the :dir() pseudo-class uses only the semantic value of the directionality, i.e., the one defined in the document itself. it doesn't account for styling directionality, i.e., the directionality set by css properties such as direction. note: be aware that the behavior of the :dir() pseudo-class is not equivalent to the [dir=…] attribute
selectors. the latter match the html dir attribute, and ignore elements that lack it — even if they inherit a direction from their parent. (similarly, [dir=rtl] and [dir=ltr] won't match the auto value.) in contrast, :dir() will match the value calculated by the user agent, even if inherited. note: in html, the direction is determined by the dir attribute. other document types may have different meth...
... working draft initial definition. ...
:disabled - CSS: Cascading Style Sheets
living standard no change. html5the defi...
...i++) { billingitems[i].disabled = !billingitems[i].disabled; } } result specifications specification status comment html living standardthe definition of ':disabled' in that specification. living standard no change. html5the definition of ':disabled' in that specification. recommendation defines the semantics of html and forms.
selectors level 4the definition of ':disabled' in that specification. working draft no change.
selectors level 3the definition of ':disabled' in that specification. recommendation defines the pseudo-class, but not the associated semantics. ...
:empty - CSS: Cascading Style Sheets
/* selects any <div> that contains no content */ div:empty { background: lime; } syntax :empty examples html <div class="box"><!-- i will be lime. ...
... assistive technology. this is commonly used for buttons that rely solely on an icon to convey purpose. what is an accessible name? | the paciello group hidden content for better a11y | go make things mdn understanding wcag, guideline 2.4 explanations understanding success criterion 2.4.4 | w3c understanding wcag 2.0 specifications specification status comment
selectors level 4the definition of 'the :empty pseudo-class' in that specification. working draft changed to act like :-moz-only-whitespace.
selectors level 3the definition of 'the :empty pseudo-class' in that specification. recommendation initial definition ...
:focus-visible - CSS: Cascading Style Sheets
the :focus-visible pseudo-class applies while an element matches the :focus pseudo-class and the ua (user agent) determines via heuristics that the focus should be made evident on the element. (many browsers show a “focus ring” by default in this case.) this
selector is useful to provide a different focus indicator based on the user’s input modality (mouse vs. keyboard). note that firefox supports similar functionality through an older, prefixed pseudo-class — :-moz-focusring. syntax :focus-visible examples basic example in this example, the :focus-visible
selector uses the ua's behavior to determine when to match. compare what happens when you click on the different controls with a mouse, versus when you tab through them using a keyboard. note the difference in behavior from eleme...
... working draft initial definition. ...
:focus-within - CSS: Cascading Style Sheets
pseudo-class represents an element that has received focus or contains an element that has received focus. in other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus. (this includes descendants in shadow trees.) /* selects a <div> when one of its descendants is focused */ div:focus-within { background: cyan; } this
selector is useful, to take a common example, for highlighting an entire <form> container when the user focuses on one of its <input> fields. syntax :focus-within examples in this example, the form will receive special coloring styles when either text input receives focus. html <p>try typing into this form.</p> <form> <label for="given_name">given name:</label> <input id="given_name" type="text...
... working draft initial definition. ...
:host - CSS: Cascading Style Sheets
lass selects the shadow host of the shadow dom containing the css it is used inside — in other words, this allows you to select a custom element from inside its shadow dom. note: this has no effect when used outside a shadow dom. ...
... inside its shadow dom. note: this has no effect when used outside a shadow dom. /* selects a shadow root host */ :host { font-weight: bold; } syntax :host examples styling the shadow host the following snippets are taken from our host-
selectors example (see it live also). ...
:indeterminate - CSS: Cascading Style Sheets
pseudo-class represents any form element whose state is indeterminate, such as checkboxes which have their html indeterminate attribute set to true, radio buttons which are members of a group in which all radio buttons are unchecked, and indeterminate <progress> elements. ...
... working draft no change. ...
:lang() - CSS: Cascading Style Sheets
recommendation no significant change. css level 2 (revision 1)the definition of ':lang()' in that specification. recommendation initial definition. ...
...g(en) > q { quotes: '\201c' '\201d' '\2018' '\2019'; } :lang(fr) > q { quotes: '« ' ' »'; } :lang(de) > q { quotes: '»' '«' '\2039' '\203a'; } result specifications specification status comment
selectors level 4the definition of ':lang()' in that specification. working draft adds wildcard language matching and comma-separated list of languages.
selectors level 3the definition of ':lang()' in that specification. recommendation no significant change. css level 2 (revision 1)the definition of ':lang()' in that specification. recommendation initial definition. ...
:only-of-type - CSS: Cascading Style Sheets
the :only-of-type css pseudo-class represents an element that has no siblings of the same type. /* selects each <p>, but only if it is the */ /* only <p> element inside its parent */ p:only-of-type { background-color: lime; } note: as originally defined, the selected element had to have a parent. beginning with
selectors level 4, this is no longer required. syntax :only-of-type examples styling elements with no siblings of the same type html <main> <div>i am `div` #1.</div> <p>i am the only `p` among my siblings.</p> <div>i am `div` #2.</div> <div>i am `div` #3. <i>i am the only `i` child.</i> <em>i am `em` #1.</em> <em>i am `em` #2.</em> </div> </main> css main :only-of-type { color: red; } result specifications specification status co...
...siblings of the same type html <main> <div>i am `div` #1.</div> <p>i am the only `p` among my siblings.</p> <div>i am `div` #2.</div> <div>i am `div` #3. <i>i am the only `i` child.</i> <em>i am `em` #1.</em> <em>i am `em` #2.</em> </div> </main> css main :only-of-type { color: red; } result specifications specification status comment
selectors level 4the definition of ':only-of-type' in that specification. working draft matching elements are not required to have a parent.
selectors level 3the definition of ':only-of-type' in that specification. recommendation initial definition. ...
:read-only - CSS: Cascading Style Sheets
tarea>. input:-moz-read-only, textarea:-moz-read-only, input:read-only, textarea:read-only { border: 0; box-shadow: none; background-color: white; } textarea:-moz-read-write, textarea:read-write { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } you can find the full source code at readonly-confirmation.html; this renders like so: styling read-only non-form controls this
selector doesn't just select <input>/<textarea> elements — it will select any element that cannot be edited by the user. <p contenteditable>this paragraph is editable; it is read-write.</p> <p>this paragraph is not editable; it is read-only.</p> p { font-size: 150%; padding: 5px; border-radius: 5px; } p:read-only { background-color: red; color: white; } p:read-write { background-color: ...
...: white; } p:read-write { background-color: lime; } specifications specification status comment html living standardthe definition of ':read-only' in that specification. living standard no change. html5the definition of ':read-only' in that specification. recommendation defines the semantics regarding html and constraint validation.
selectors level 4the definition of ':read-only' in that specification. working draft defines the pseudo-class, but not the associated semantics. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefi...
:read-write - CSS: Cascading Style Sheets
area>. input:-moz-read-only, textarea:-moz-read-only, input:read-only, textarea:read-only { border: 0; box-shadow: none; background-color: white; } textarea:-moz-read-write, textarea:read-write { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } you can find the full source code at readonly-confirmation.html; this renders like so: styling read-write non-form controls this
selector doesn't just select <input>/<textarea> elements — it will select any element that can be edited by the user, such as a <p> element with contenteditable set on it. <p contenteditable>this paragraph is editable; it is read-write.</p> <p>this paragraph is not editable; it is read-only.</p> p { font-size: 150%; padding: 5px; border-radius: 5px; } p:read-only { background-color: red; c...
...white; } p:read-write { background-color: lime; } specifications specification status comment html living standardthe definition of ':read-write' in that specification. living standard no change. html5the definition of ':read-write' in that specification. recommendation defines the semantics regarding html and constraint validation.
selectors level 4the definition of ':read-write' in that specification. working draft defines the pseudo-class, but not the associated semantics. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgef...
additive-symbols - CSS: Cascading Style Sheets
@counter-styleinitial valuen/acomputed valueas specified formal syntax [ <integer> && <symbol> ]#where <symbol> = <string> | <image> | <custom-ident>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
negative - CSS: Cascading Style Sheets
ter-styleinitial value"-" hyphen-minuscomputed valueas specified formal syntax <symbol> <symbol>?where <symbol> = <string> | <image> | <custom-ident>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
pad - CSS: Cascading Style Sheets
rule@counter-styleinitial value0 ""computed valueas specified formal syntax <integer> && <symbol>where <symbol> = <string> | <image> | <custom-ident>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
prefix - CSS: Cascading Style Sheets
@counter-styleinitial value"" (the empty string)computed valueas specified formal syntax <symbol>where <symbol> = <string> | <image> | <custom-ident>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
suffix - CSS: Cascading Style Sheets
nitial value". ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
symbols - CSS: Cascading Style Sheets
related at-rule@counter-styleinitial valuen/acomputed valueas specified formal syntax <symbol>+where <symbol> = <string> | <image> | <custom-ident>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
Adjacent sibling combinator - CSS: Cascading Style Sheets
the adjacent sibling combinator (+) separates two
selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element. /* paragraphs that come immediately after any image */ img + p { font-weight: bold; } syntax former_element + target_element { style properties } examples css li:first-of-type + li { color: red; } html <ul> <li>one</li> <li>two!</li> <li>three</li> </ul> result specifications specification status comment
selectors level 4the definition of 'next-sibling combinator' in that specification. working draft renames it the "next-sibling" combinator.
selectors level 3the definition of 'adjacent sibling combinator' in that specification. recommendat...
...cations specification status comment
selectors level 4the definition of 'next-sibling combinator' in that specification. working draft renames it the "next-sibling" combinator.
selectors level 3the definition of 'adjacent sibling combinator' in that specification. recommendation css level 2 (revision 1)the definition of 'adjacent sibling
selectors' in that specification. recommendation initial definition. ...
Stacking context example 3 - CSS: Cascading Style Sheets
« css « understanding css z-index stacking context example 3 this last example shows problems that arise when mixing several positioned elements in a multi-level html hierarchy and when z-indexes are assigned using class
selectors. let's take as an example a three-level hierarchical menu made from several positioned divs. second-level and third-level divs appear when hovering or clicking on their parents. usually this kind of menu is script-generated either client-side or server-side, so style rules are assigned with a class
selector instead of the id
selector. if the three menu levels partially overlap, then managing stacking could become a problem. the first-level menu is only relatively positioned, so no stacking context is created. the second-level menu is absolutely positioned insi...
...t stacking context level #1 level #2 (z-index: 1) level #3 ... level #3 level #2 (z-index: 1) ... level #2 (z-index: 1) level #1 ... level #1 this problem can be avoided by removing overlapping between different level menus, or by using individual (and different) z-index values assigned through the id
selector instead of class
selector, or by flattening the html hierarchy. note: in the source code you will see that second-level and third level menus are made of several divs contained in an absolutely positioned container. this is useful to group and position all of them at once. example source code <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
an choose to override styles in many browsers using a custom user stylesheet designed to tailor the experience to the user's wishes. cascading order the cascading algorithm determines how to find the value to apply for each property for each document element. it first filters all the rules from the different sources to keep only the rules that apply to a given element. that means rules whose
selector matches the given element and which are part of an appropriate media at-rule. then it sorts these rules according to their importance, that is, whether or not they are followed by !important, and by their origin. the cascade is in ascending order, which means that !important values from a user-defined style sheet have precedence over normal values originated from a user-agent style sheet: ...
...p>nd</sup></li> </ul> in this case, declarations inside li and .specific rules should apply. no declaration is marked as !important, so the precedence order is author style sheets before user style sheets or user-agent stylesheet. so three declarations are in competition: margin-left: 0 margin-left: 3px margin-left: 1px the last one is ignored (on a screen), and the first two have the same
selector, hence the same specificity. therefore, it is the last one that is then selected: margin-left: 3px note that the declaration defined in the user css, though having a greater specificity, is not chosen as the cascade algorithm is applied before the specificity algorithm. specifications specification status comment css cascading and inheritance level 4 candidate r...
General sibling combinator - CSS: Cascading Style Sheets
the general sibling combinator (~) separates two
selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element. /* paragraphs that are siblings of and subsequent to any image */ img ~ p { color: red; } syntax former_element ~ target_element { style properties } examples css p ~ span { color: red; } html <span>this is not red.</span> <p>here is a paragraph.</p> <code>here is some code.</code> <span>and here is a red span!</span> <code>more code...</code> <span>and this is a red span!</span> result specifications specification status comment
selectors level 4the definition of 'subsequent-sibling combinator' in that specification. working draft ...
... recommendation initial definition. ...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
other contexts. custom properties are subject to the cascade and inherit their value from their parent. basic usage declaring a custom property is done using a custom property name that begins with a double hyphen (--), and a property value that can be any valid css value. like any other property, this is written inside a ruleset, like so: element { --main-bg-color: brown; } note that the
selector given to the ruleset defines the scope that the custom property can be used in. a common best practice is to define custom properties on the :root pseudo-class, so that it can be applied globally across your html document: :root { --main-bg-color: brown; } however, this doesn't always have to be the case: you maybe have a good reason for limiting the scope of your custom properties. note: c...
...is the default value of any custom property keep in mind that these are custom properties, not actual variables like you might find in other programming languages. the value is computed where it is needed, not stored for use in other rules. for instance, you cannot set a property for an element and expect to retrieve it in a sibling's descendant's rule. the property is only set for the matching
selector and its descendants, like any normal css. custom property fallback values using the var() function, you can define multiple fallback values when the given variable is not yet defined; this can be useful when working with custom elements and shadow dom. fallback values aren't used to fix the browser compatibility. if the browser doesn't support css custom properties, the fallback value won't h...
background-image - CSS: Cascading Style Sheets
tednocomputed valueas specified, but with <url> values made absoluteanimation typediscrete formal syntax <bg-image>#where <bg-image> = none | <image>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
background - CSS: Cascading Style Sheets
ound | no-repeat ]{1,2}<attachment> = scroll | fixed | local<box> = border-box | padding-box | content-boxwhere <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient><length-percentage> = <length> | <percentage>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
border-image-source - CSS: Cascading Style Sheets
so applies to ::first-letter.inheritednocomputed valuenone or the image with its uri made absoluteanimation typediscrete formal syntax none | <image>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
<color> - CSS: Cascading Style Sheets
examples color value tester in this example we provide a <div> and a text input. entering a valid color into the input causes the <div> to adopt that color, allowing you to test our color values. ...
... provide a <div> and a text input. entering a valid color into the input causes the <div> to adopt that color, allowing you to test our color values. ...
content - CSS: Cascading Style Sheets
| <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient><quote> = open-quote | close-quote | no-open-quote | no-close-quote<target> = <target-counter()> | <target-counters()> | <target-text()><leader()> = leader( <leader-type> )where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...style>? )<target-text()> = target-text( [ <string> | <url> ] , [ content | before | after | first-letter ]? )<leader-type> = dotted | solid | space | <string>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
cross-fade() - CSS: Cascading Style Sheets
al-image> = <image> | <color>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...3} , <alpha-value>? )<hsl()> = hsl( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsl( <hue>, <percentage>, <percentage>, <alpha-value>? )<hsla()> = hsla( <hue> <percentage> <percentage> [ / <alpha-value> ]? ) | hsla( <hue>, <percentage>, <percentage>, <alpha-value>? )where <image-tags> = ltr | rtl<image-src> = <url> | <string><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <color-stop-list> )<repeating-radial-gradient()> = repeating-radial-gradient( [ <endi...
mask-border-source - CSS: Cascading Style Sheets
nd all graphics elementsinheritednocomputed valueas specified, but with <url> values made absoluteanimation typediscrete formal syntax none | <image>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
mask-image - CSS: Cascading Style Sheets
alues made absoluteanimation typediscrete formal syntax <mask-reference>#where <mask-reference> = none | <image> | <mask-source>where <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient><mask-source> = <url>where <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...<cf-final-image>? )<gradient> = <linear-gradient()> | <repeating-linear-gradient()> | <radial-gradient()> | <repeating-radial-gradient()> | <conic-gradient()>where <image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
mask - CSS: Cascading Style Sheets
lude<masking-mode> = alpha | luminance | match-sourcewhere <image> = <url> | <image()> | <image-set()> | <element()> | <paint()> | <cross-fade()> | <gradient><mask-source> = <url><length-percentage> = <length> | <percentage><shape-box> = <box> | margin-boxwhere <image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...&& <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
shape-outside - CSS: Cascading Style Sheets
> ]? )<circle()> = circle( [ <shape-radius> ]? [ at <position> ]? )<ellipse()> = ellipse( [ <shape-radius>{2} ]? [ at <position> ]? )<polygon()> = polygon( <fill-rule>? , [ <length-percentage> <length-percentage> ]# )<path()> = path( [ <fill-rule>, ]? <string> )<image()> = image( <image-tags>? [ <image-src>? , <color>? ]! ...
...p | center | bottom | <length-percentage> ]? | [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]<fill-rule> = nonzero | evenodd<image-tags> = ltr | rtl<image-src> = <url> | <string><color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color><image-set-option> = [ <image> | <string> ] <resolution><id-
selector> = <hash-token><cf-mixing-image> = <percentage>? && <image><cf-final-image> = <image> | <color><linear-gradient()> = linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<repeating-linear-gradient()> = repeating-linear-gradient( [ <angle> | to <side-or-corner> ]? , <color-stop-list> )<radial-gradient()> = radial-gradient( [ <ending-shape> | <size> ]? [ at <position> ]? , <colo...
transition-timing-function - CSS: Cascading Style Sheets
m: 4px; background-color: black; border: 1px solid red; color: white; transition-property: all; transition-duration: 7s; } .parent > div.box1{ width: 90vw; min-width: 24em; background-color: magenta; color: yellow; border: 1px solid orange; transition-property: all; transition-duration: 2s; } function updatetransition() { var els = document.query
selectorall(".parent > div[class]"); for(var c = els.length, i = 0; i < c; i++) { els[i].classlist.toggle("box1"); } } var intervalid = window.setinterval(updatetransition, 10000); .ease { transition-timing-function: ease; } .easein { transition-timing-function: ease-in; } .easeout { transition-timing-function: ease-out; } .easeinout { transition-timing-function: ease-in-out; } .l...
...tom: 4px; background-color: black; border: 1px solid red; color: white; transition-property: all; transition-duration:7s; } .parent > div.box1{ width: 90vw; min-width: 24em; background-color: magenta; color: yellow; border: 1px solid orange; transition-property: all; transition-duration:2s; } function updatetransition() { var els = document.query
selectorall(".parent > div[class]"); for(var c = els.length, i = 0; i < c; i++) { els[i].classlist.toggle("box1"); } } var intervalid = window.setinterval(updatetransition, 10000); .jump-start { transition-timing-function: steps(5, jump-start); } .jump-end { transition-timing-function: steps(5, jump-end); } .jump-none { transition-timing-function: steps(5, jump-none); } .jump-both { ...
white-space - CSS: Cascading Style Sheets
ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliqu...
...ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. duis aute irure dolor in repre...
<a>: The Anchor element - HTML: Hypertext Markup Language
html <p>paint by holding down the mouse button and moving it. ...
...see referer header: privacy and security concerns for information. using target="_blank" without rel="noreferrer" and rel="noopener" makes the website vulnerable to window.opener api exploitation attacks (vulne...
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
content categories transparent content. permitted content flow content. tag omission none, both the starting and ending tag are mandatory. permitted parent elements any element that accepts flow content. dom interface htmlcontentelement attributes this element includes the global attributes. select a comma-separated list of
selectors. these have the same syntax as css
selectors. they select the content to insert in place of the <content> element. example here is a simple example of using the <content> element. it is an html file with everything needed in it. note: for this code to work, the browser you display it in must support web components. see enabling web components in firefox. <html> <head></head> <body> ...
... file with everything needed in it. note: for this code to work, the browser you display it in must support web components. see enabling web components in firefox. <html> <head></head> <body> <!-- the original content accessed by <content> --> <div> <h4>my content heading</h4> <p>my content text</p> </div> <script> // get the <div> above. var mycontent = document.query
selector('div'); // create a shadow dom on the <div> var shadowroot = mycontent.createshadowroot(); // insert into the shadow dom a new heading and // part of the original content: the <p> tag. shadowroot.innerhtml = '<h2>inserted heading</h2> <content select="p"></content>'; </script> </body> </html> if you display this in a web browser it should look like the following. specificat...
<input type="file"> - HTML: Hypertext Markup Language
in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types. because of this, you should make sure that the accept attribute is backed up by appropriate server-side validation. notes you cannot set the value of a file picker from a script — doing something like the following has no effect: const input = document.query
selector("input[type=file]"); input.value = "foo"; when a file is chosen using an <input type="file">, the real path to the source file is not shown in the input's value attribute for obvious security reasons. instead, the filename is shown, with c:\fakepath\ appended to the beginning of it. there are some historical reasons for this quirk, but it is supported across all modern browsers, and in fac...
...iew. next, we hide the <input> element — we do this because file inputs tend to be ugly, difficult to style, and inconsistent in their design across browsers. you can activate the input element by clicking its <label>, so it is better to visually hide the input and style the label like a button, so the user will know to interact with it if they want to upload files. const input = document.query
selector('input'); const preview = document.query
selector('.preview'); input.style.opacity = 0; note: opacity is used to hide the file input instead of visibility: hidden or display: none, because assistive technology interprets the latter two styles to mean the file input isn't interactive. next, we add an event listener to the input to listen for changes to its selected value changes (in this case,...
<input type="tel"> - HTML: Hypertext Markup Language
> <span class="validity"></span> </span> </div> <div> <button>submit</button> </div> </form> the javascript is relatively simple — it contains an onchange event handler that, when the <select> value is changed, updates the <input> element's pattern, placeholder, and aria-label to suit the format of telephone numbers in that country/territory. ...
... </div> <div> <button>submit</button> </div> </form> the javascript is relatively simple — it contains an onchange event handler that, when the <select> value is changed, updates the <input> element's pattern, placeholder, and aria-label to suit the format of telephone numbers in that country/territory. ...
JavaScript modules - JavaScript
ample loads. instead, we include three buttons — "circle", "square", and "triangle" — that, when pressed, dynamically load the required module and then use it to draw the associated shape. in this example we've only made changes to our index.html and main.js files — the module exports remain the same as before. ...
..."square", and "triangle" — that, when pressed, dynamically load the required module and then use it to draw the associated shape. in this example we've only made changes to our index.html and main.js files — the module exports remain the same as before. ...
import - JavaScript
file.js'; getusefulcontents('http://www.example.com', data => { dosomethinguseful(data); }); dynamic import this example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. this is not the only way to implement this functionality. the import() function also supports await. ...
...m', data => { dosomethinguseful(data); }); dynamic import this example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. this is not the only way to implement this functionality. the import() function also supports await. const main = document.query
selector("main"); for (const link of document.query
selectorall("nav > a")) { link.addeventlistener("click", e => { e.preventdefault(); import('/modules/my-module.js') .then(module => { module.loadpageinto(main); }) .catch(err => { main.textcontent = err.message; }); }); } specifications specification ecmascript (ecma-262)the definition of 'imports' in that specification. ...
Critical rendering path - Web Performance
des inheriting styles. the incremental processing features don't apply to css like they do with html, because subsequent rules may override previous ones. the css object model gets built as the css is parsed, but can't be used to build the render tree until it is completely parsed because styles that are going to be overwritten with later parsing should not be rendered to the screen. in terms of
selector performance, less specific
selectors are faster than more specific ones. for example, .foo {} is faster than .bar .foo {} because when the browser finds .foo, in the second scenario, it has to walk up the dom to check if .foo has an ancestor .bar. the more specific tag requires more work from the browser, but this penalty is not likely worth optimizing. if you measure the time it takes to parse ...
...ser, but this penalty is not likely worth optimizing. if you measure the time it takes to parse css, you'll be amazed at how fast browsers truly are. the more specific rule is more expensive because it has to traverse more nodes in the dom tree - but that extra expense is generally minimal. measure first. optimize as needed. specificity is likely not your low hanging fruit. when it comes to css,
selector performance optimization, improvements will only be in microseconds. there are other ways to optimize css, such as minification, and separating defered css into non-blocking requests by using media queries. render tree the render tree captures both the content and the styles: the dom and cssom trees are combined into the render tree. to construct the render tree, the browser checks every node, ...
seed - SVG: Scalable Vector Graphics
working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'seed'...
... working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'seed' in that specificatio...
SVG documentation index - SVG: Scalable Vector Graphics
for drawing an svg element that requires more than one coordinate. elements that only need one coordinate use the x attribute instead. 254 x2 svg, svg attribute the x2 attribute is used to specify the second x-coordinate for drawing an svg element that requires more than one coordinate. elements that only need one coordinate use the x attribute instead. 255 xchannel
selector filters, needsexample, svg, svg attribute the xchannel
selector attribute indicates which color channel from in2 to use to displace the pixels in in along the x-axis. 256 xlink:arcrole deprecated, svg, svg attribute the xlink:arcrole attribute specifies a contextual role for the element and corresponds to the rdf primer notion of a property. 257 xlink:href...
...for drawing an svg element that requires more than one coordinate. elements that only need one coordinate use the y attribute instead. 266 y2 svg, svg attribute the y2 attribute is used to specify the second y-coordinate for drawing an svg element that requires more than one coordinate. elements that only need one coordinate use the y attribute instead. 267 ychannel
selector filters, svg, svg attribute the ychannel
selector attribute indicates which color channel from in2 to use to displace the pixels in in along the y-axis. 268 z filters, svg, svg attribute the z attribute defines the location along the z-axis for a light source in the coordinate system established by the primitiveunits attribute on the <filter> element, assuming that, ...
Index - XPath
it uses a non-xml syntax to provide a flexible way of addressing (pointing to) different parts of an xml document. it can also be used to test addressed nodes within a document to determine whether they match a pattern or not. 2 axes transforming_xml_with_xslt, xpath, xpath_reference, xslt, xslt_reference for further information on using xpath expressions, please see the for further reading section at the end of transforming xml with xslt document. also see the 'axes' section in the xpath spec. ...
...te and namespace nodes. 14 preceding-sibling axe, xpath the preceding-sibling axis indicates all the nodes that have the same parent as the context node and appear before the context node in the source document. 15 self axe, xpath the self axis indicates the context node itself. it can be abbreviated as a single period (.). 16 comparison of css
selectors and xpath css, draft, needscontent, reference,
selectors, xpath this article seeks to document the difference between css
selectors and xpath for web developers to be able to better choose the right tool for the right job. 17 functions transforming_xml_with_xslt, xpath, xpath_reference, xslt, xslt_reference no summary! 18 boolean xslt, xslt_reference...
XPath
t parts of an xml document. it can also be used to test addressed nodes within a document to determine whether they match a pattern or not. xpath is mainly used in xslt, but can also be used as a much more powerful way of navigating through the dom of any xml-like language document using xpathexpression, such as html and svg, instead of relying on the document.getelementbyid() or parentnode.query
selectorall() methods, the node.childnodes properties, and other dom core features. xpath uses a path notation (as in urls) for navigating through the hierarchical structure of an xml document. it uses a non-xml syntax so that it can be used in uris and xml attribute values. note: support for xpath varies widely; it's supported reasonably well in firefox (although there are no plans to improve support ...
...most practical way and valid alternative to xpath. view all... tools chropath xpath panel that integrates tightly into firebug, providing an editor and inspector (firefox add-on). xmlquire (formerly known as sketchpath) a graphical xpath builder/debugger(.net). xpath tester an online xpath builder/debugger. related topics xslt, xquery, xml, dom, jxon, jsonpath comparison of css
selectors and xpath ...
Content Scripts - Archive of obsolete content
+ ' window.alert("the context menu was clicked on url:\\n" + href);' + '};' + 'window.addeventlistener("myaddonid-contextmenu-clicked",' + ' function(event){contextmenualert(event.detail);});' }); let cm = require("sdk/context-menu"); cm.item({ label: "alert url", context: [ cm.urlcontext(["*.mozilla.org"]), cm.
selectorcontext("a[href]") ], contentscript: 'self.on("click", function (node, data) {' + ' var event = new customevent("myaddonid-contextmenu-clicked",' + ' {detail:node.href});' + ' window.dispatchevent(event);' + '});' }); cross-domain content scripts by default, content scripts don't have...
Displaying annotations - Archive of obsolete content
ontent script the content script for the matcher page-mod is initialized with a list of all the annotations that the user has created. when a page is loaded the matcher searches the dom for elements that match annotations. if it finds any it binds functions to that element's mouseenter and mouseleave events to send messages to the main module, asking it to show or hide the annotation. like the
selector, the matcher also listens for the window's unload event and on unload sends a detach message to the main module, so the add-on can clean it up. the complete content script is here: self.on('message', function onmessage(annotations) { annotations.foreach( function(annotation) { if(annotation.url == document.location.tostring()) { createanchor(annotation); } }); $('...
Overview - Archive of obsolete content
itor panel enables the user to enter a new annotation. the annotation-list panel shows a list of all stored annotations. the annotation panel displays a single annotation. additionally, we use the notifications module to notify the user when the add-on's storage quota is full. working with the dom we'll use two page-mods to interact with the doms of pages that the user has opened. the
selector enables the user to choose an element to annotate. it identifies page elements which are eligible for annotation, highlights them on mouseover, and tells the main add-on code when the user clicks a highlighted element. the matcher is responsible for finding annotated elements: it is initialized with the list of annotations and searches web pages for the elements they are associated with. it...
Storing annotations - Archive of obsolete content
specting private browsing since annotations record the user's browsing history we should avoid recording annotations in private windows. there's a very simple way to do this: do nothing. by omitting the "private-browsing" key from the annotator's "package.json" file, the annotator opts out of private browsing altogether. this means that its widget will not appear on any private windows and its
selector and matcher content scripts won't run, so the user won't be able to enter any annotations in private windows. try it: execute cfx run and open a new private window: you should no longer see the annotator's widget. now we can create and store annotations, the last piece is to display them when the user loads the page. ...
Examples and demos from articles - Archive of obsolete content
what follows is a brief list of examples and demos from our theoretical articles. live demos javascript rich-text editor [zip] how to standardize the creation of complete rich-text editors in web pages. [article] typewriter effect [html] the following example will delete and re-type simulating a typewriter all the text content of the nodelist which match a specified group of
selectors. [article] fade in/out [html] sometimes a page uses dozens and dozens of animations. in such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the cleartimeout() function. a possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create ...
Extension Theming Guidelines - Archive of obsolete content
y are not replaceable by custom themes stylesheets guidelines include stylesheets for every new window that your extension adds and for every window that your extension overlays content into be sure to add a stylesheet from your chrome skin package. while it may be tempting to use the same stylesheet in multiple places try to avoid this so that themes can correctly target the right windows. css
selectors when writing stylesheet rules for windows that you are overlaying always try to be specific with the css
selector. if you are not then you run a risk of conflicting with content that other extensions add to the window. xul guidelines xbl bindings xbl bindings are applied using style rules. however these are rarely part of the style of the widgets but more about adding custom widgets. in this ca...
Custom XUL Elements with XBL - Archive of obsolete content
le window. replacing elements should always be a last resort solution, specially if it is done on the main browser window. it's very easy to break the ui of the application or other extensions if you do this the wrong way, so be very careful about it. if you only need to change some specific instances of an element, use very specific css rules. you can use the -moz-binding property with any css
selector. « previousnext » this tutorial was kindly donated to mozilla by appcoast. ...
Performance best practices in extensions - Archive of obsolete content
ooking for these specific kinds of leaks, it's worth exercising your extension's functionality and checking the contents of about:memory for any excessive memory usage. for example, bug 719601 featured a "system principal" javascript compartment containing 100s of mbs of memory, which is much larger than usual. avoid writing slow css read the "writing efficient css" guide. remember that any
selector in your rule which might match many different nodes is a source of inefficiency during either
selector matching or dynamic update processing. this is especially bad for the latter if the
selector can dynamically start or stop matching. avoid unqualified ":hover" like the plague. avoid dom mutation event listeners dom mutation event listeners are extremely expensive and, once added to a documen...
Setting up an extension development environment - Archive of obsolete content
kage your extension's chrome in a jar or in directories, developing in directories is simpler. if you choose a jared structure for releasing, you can still develop with a directory structure by editing your chrome.manifest. for example, rather than having content myextension jar:chrome/myextension.jar!/content/ use content myextension chrome/content/ preventing the first launch extension
selector requires gecko 8.0(firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) starting in firefox 8, on the first launch of a new version of firefox, it presents user interface letting users select which third party add-ons to keep. this lets them weed out add-ons that were installed without their knowledge, or that are no longer needed. however, this interface can be disruptive when debugging add-ons. y...
Index of archived content - Archive of obsolete content
javascript timers javascript daemons management label and description lookupnamespaceuri lookupprefix miscellaneous modules on page load page loading post data to window preferences progress listeners query
selector rosetta running applications svg animation svg general scrollbar sidebar stringview tabbox toolbar tree uri parsing view source for xul applications windows xml-related code snippets xml:ba...
Layout FAQ - Archive of obsolete content
frame(br)(1)@035ffb1c {330,225,0,0} [state=00000020] [content=035aebf0] > > the linebox is used to contain everything on a single line: example how do you fix inconsistent float behavior in firefox involving a two column layout using display:table and floating div elements? this is a bug in firefox. you can work around it by removing display:table in the style rule with the "#main"
selector or adding clear:both to it. why does move movement disappear when i use mouse events to click and drag? since the dragging action is involved, you might need to disable it. try using event.preventdefault() what is the purpose of the ns_lossyconvertucs2toascii() function? this function converts an nsastring to an nsacstring by assuming that all the 16-bit units are ascii and just dropping ...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
aller than its parent. if you prefer the internet explorer behavior, simply do not specify a height on the outer element. figure 4. div overflow hover differences the nonstandard css hover behavior in internet explorer occurs on quite a few web sites. it usually manifests itself by changing text style when hovered over in mozilla, but not in internet explorer. this is because the a:hover css
selector in internet explorer matches <a href="">...</a> but not <a name="">...</a>, which sets anchors in html. the text changes occur because authors encapsulate the areas with the anchor-setting markup: css: a:hover {color: green;} html: <a href="foo.com">this text should turn green when you hover over it.</a> <a name="anchor-name"> this text should change color when hovered over, but doe...
Elements - Archive of obsolete content
s - the includes attribute can be used to indicate that only certain content should be placed at the insertion point specified by the children element. its value can be a tag name or multiple tag names separated by the pipe character ("|"). a child can only be placed within the insertion point if it is matched by the value in the includes attribute. only immediate children are matched against the
selector. for example, an xml fragment <customelement><foobar><hoge/></foobar></customelement> with an binding definition <binding id="customelement"><content><xul:box><children includes="hoge"/></xul:box></content></binding> for the customelement element, <xul:box/> becomes empty because the
selector includes="hoge" doesn't match for the immediate child foobar element. implementation <!entity % implem...
Introduction to XUL - Archive of obsolete content
. a value of "*" is a wildcard signifying all elements with the attribute. xulelement xulelement extends element. interface xulelement : element { nodelist getelementsbyattribute(in domstring name, in domstring value); }; getelementsbyattribute functions as does its namesake in xuldocument, though this version returns only those elements which match the criteria and are descendants (in css
selector terminology) of the given element. xulelement also supports other methods for hooking up broadcasters; a function performed automatically by the xul document loader and therefore not normally used in javascript. xul elements as mentioned above, a xul file is mostly an html file with xml syntax. a xul file may contain nothing but html elements and be completely functional. but xul defines sever...
Complete - Archive of obsolete content
see the registration details in installed-chrome.txt and chrome.rdf. when the xul file, allcustom.xul is loaded, the stylesheet declaration near the top loads a stylesheet from chrome://allcustom/skin/. the application's chrome registry converts this to the correct css file for the theme you are using. the xul toolbarbutton tag has an id all-custom-1. the css stylesheet uses the corresponding
selector #all-custom-1 to provide the appropriate image: button-1.png file structure in the new file structure, there is a skin directory for all the themes. each theme has its own directory there. in each theme's directory, there is an allcustom directory. this is useful when files from various components and extensions and all unpacked in the same place—it keeps each set of files separate. the allcus...
Adding Style Sheets - Archive of obsolete content
style import from xul: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> style import from css: @import url(chrome://global/skin/); the second syntax is preferred because it reduces the number of dependencies within the xul file itself. remove the global style sheet import from findfile.xul and add the import to findfile.css. all elements can be styled using css. you can use
selectors to select the element that you wish to have styled. (the
selector is the part before the curly brace in a style rule). the following list summarizes some of the
selectors available: button matches all button tags. #special-button matches the element with an id of special-button. .bigbuttons matches all elements with a class of bigbuttons. butt...
Anonymous Content - Archive of obsolete content
</xul:box> <xul:button label="zoom out"/> </xul:box> </content> </binding> from the dom's perspective, the child elements are still in their original location. that is, the outer xul box has two children, which are the two images. the inner box with the border has one child, the children tag. this is an important distinction when using the dom with xbl. this also applies to css
selector rules. multiple children elements you can also use multiple children elements and have certain elements be placed in one location and other elements placed in another. by adding a includes attribute and setting it to a vertical bar-separated list of tags, you can make only elements in that list be placed at that location. for example, the following xbl will cause text labels and buttons to appear...
Using the standard theme - Archive of obsolete content
r has currently chosen. at the beginning, there is no style when creating a new xul <tt>window</tt> (or a new <tt>dialog</tt>, for that matter) in your extension, and you do not associate a style sheet with it, your widgets will be unstyled. meaning, some internal default will be applied, which does by no means correspond to the standard theme (the theme currently chosen by the user in the theme
selector), or even the default theme delivered with your the base application. applying the standard theme in order to use the theme currently chosen by the user of the base application (the so called "global skin"), you have to add the following line to your xul file: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> this imports the styles found in the <tt>global/skin</tt> chrome direct...
action - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
arrowscrollbox - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
assign - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
bbox - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
binding - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related tbd ...
bindings - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related tbd ...
box - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements vbox, hbox ...
broadcaster - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
broadcasterset - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
button - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprovider, nsidomxulbuttonelement ...
caption - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements groupbox, checkbox ...
checkbox - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprovider, nsidomxulcheckboxelement ...
column - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements grid, columns, rows, row ...
command - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related xul:list of commands ...
commandset - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
conditions - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
content - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata relacionados tbd ...
datepicker - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsidomxulcontrolelement ...
deck - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related stack ...
dialogheader - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements dialog, window ...
dropmarker - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
editor - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprovider ...
grippy - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
groupbox - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprovider ...
hbox - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements box, vbox ...
iframe - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related nsiaccessibleprovider ...
key - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata details on key, keycode, and modifiers attributes for example, consider the following key: <key key="r" modifiers="shift"/> this key will only match when the shif...
keyset - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
listcol - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements listbox, listcell, listcols, listhead, listheader, listitem ...
listcols - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements listbox, listcell, listcol, listhead, listheader, listitem ...
listhead - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements listbox, listcell, listcol, listcols, listheader, listitem ...
listheader - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements listbox, listcell, listcol, listcols, listhead, listitem ...
member - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
menubar - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements menu, menuitem, menulist, menupopup, menuseparator interfaces nsiaccessibleprovider ...
menuseparator - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements menu, menubar, menuitem, menulist, menupopup interfaces nsiaccessibleprovider, nsidomxulcontaineritemelement, nsidomxulselectcontrolitemelem...
observes - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
page - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
param - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
popupset - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements popup, menupopup ...
preferences - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related preferences system documentation: introduction: getting started | examples | troubleshooting reference: prefwindow | prefpane | preferences | prefe...
progressmeter - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprovider ...
query - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
queryset - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
radio - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements radiogroup, checkbox interfaces nsiaccessibleprovider, nsidomxulselectcontrolitemelement, nsidomxullabeledcontrolelement ...
resizer - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
richlistitem - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprovider, nsidomxulselectcontrolitemelement ...
rule - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
script - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
scrollbar - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
scrollbox - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
scrollcorner - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
spacer - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements separator, splitter ...
spinbuttons - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
stack - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related deck ...
statusbar - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements statusbarpanel interfaces nsiaccessibleprovider ...
stringbundle - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related xul property files ...
stringbundleset - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
template - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
textnode - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
timepicker - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsidomxulcontrolelement ...
titlebar - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
toolbar - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes chromeclass-toolbar when this class is used, the toolbar will be hidden when a window is opened by setting the toolbar option to no in the...
toolbarbutton - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbargrippy, toolbaritem, toolbarpalette, toolbarseparator, toolbarset, toolbarspacer, toolbarspring, toolbox interfaces ...
toolbargrippy - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbutton, toolbaritem, toolbarpalette, toolbarseparator, toolbarset, toolbarspacer, toolbarspring, toolbox interfaces nsiacces...
toolbaritem - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbutton, toolbargrippy, toolbarpalette, toolbarseparator, toolbarset, toolbarspacer, toolbarspring, toolbox ...
toolbarpalette - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbutton, toolbargrippy, toolbaritem, toolbarseparator, toolbarset, toolbarspacer, toolbarspring, toolbox ...
toolbarseparator - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbutton, toolbargrippy, toolbaritem, toolbarpalette, toolbarset, toolbarspacer, toolbarspring, toolbox ...
toolbarset - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbutton, toolbargrippy, toolbaritem, toolbarpalette, toolbarseparator, toolbarspacer, toolbox ...
toolbarspacer - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbutton, toolbargrippy, toolbaritem, toolbarpalette, toolbarseparator, toolbarset, toolbarspring, toolbox interfaces nsiacces...
toolbarspring - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbutton, toolbargrippy, toolbaritem, toolbarpalette, toolbarseparator, toolbarset, toolbarspacer, toolbox inter...
tree - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata startediting( row, column ) return type: no return value activates user editing of the given cell, which is specified by row index number and the nsitreecolumn in ...
treechildren - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata example <tree flex="1"> <treecols> <treecol id="sender" label="sender" flex="1"/> <treecol id="subject" label="subject" flex="2"/> </treecols> <treec...
triple - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
vbox - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements box, hbox ...
where - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
window - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata see also: dom window object methods note the error message "xml parsing error: undefined entity...<window" can be caused by a missing or unreachable dtd file refer...
wizardpage - Archive of obsolete content
tens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), query
selector(), query
selectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related wizard ...
reftest opportunities files - Archive of obsolete content
est/parsing4 http://dbaron.org/css/test/parsing5 http://dbaron.org/css/test/parsing6 http://dbaron.org/css/test/sec040102 http://dbaron.org/css/test/casesens http://dbaron.org/css/test/xmltypesel http://dbaron.org/css/test/unitless http://dbaron.org/css/test/exunit http://dbaron.org/css/test/emunit http://dbaron.org/css/test/sec040310 http://dbaron.org/css/test/parsing3 http://dbaron.org/css/test/
selector_confusion http://dbaron.org/css/test/univsel http://dbaron.org/css/test/childsel http://dbaron.org/css/test/sibsel http://dbaron.org/css/test/attrsel http://dbaron.org/css/test/twoclass http://dbaron.org/css/test/xmlid http://dbaron.org/css/test/pseudos http://dbaron.org/css/test/pseudos2 http://dbaron.org/css/test/pseudos3 http://dbaron.org/css/test/firstchild http://dbaron.org/css/test/sec05110...
2006-11-10 - Archive of obsolete content
images discussion on how where to change source code so that images could be blocked in mozilla. this can be defined within the nsicontentpolicy. applying site- and page-specific settings during layout discussion on the best possible solution for integrating firefox 3 with the ability to apply site- and page-specific user settings during layout. the idea of using a single sheet and the per-site
selectors that dbaron implemented would allow for a quick proof of concept. the pro's and con's of using a single sheet was discussed. meetings none this week. ...
Common Firefox theme issues and solutions - Archive of obsolete content
css or the pause and mute buttons will break in firefox 10. change the style rules: .playbutton[paused] {...} .mutebutton[muted] {...} to: .playbutton[paused="true"] {...} .mutebutton[muted="true"] {...} error console warnings unknown namespace for videocontrols.css the error console is reporting the following issue: warning: unknown namespace prefix 'html'. ruleset ignored due to bad
selector. source file: chrome://global/skin/media/videocontrols.css the solution to this issue is to add the following name space to the second line of the file right after, and in addition to, the existing @namespace: @namespace html url("http://www.w3.org/1999/xhtml"); you can generate the error console message by going to mozilla's mission page. if you are using the extension console² you can easil...
Theme changes in Firefox 3.5 - Archive of obsolete content
rent parts of the browser window inside the private browsing mode. see this blog post for an example. supporting 3.5 features video/audio player: controlbar has to be styled (chrome://global/skin/media/videocontrols.css) shadow effect for disabled text using text-shadow. greying menus of inactive windows: active windows get attribute 'active="true"'. to do this only for 3.5 use a css
selector that is only supported in 3.5, like so: window:not([active="true"]) menubar>menu:nth-child(1n) { color:threedshadow } private browsing: show private browsing state by coloring the url bar, or by adding an icon to the toolbox/tabbrowserbar. see private browsing for theme designers for details. native hyperlink color: use -moz-nativehyperlinktext, to select the computer's native hyperlink color.
-ms-content-zoom-snap-points - Archive of obsolete content
f -ms-content-zoom-limit-min is used. if any value specified is greater than that specified by the -ms-content-zoom-limit-max property, the value of -ms-content-zoom-limit-max is used. formal syntax snapinterval( <percentage>, <percentage> ) | snaplist( <percentage># ) examples this example demonstrates both types of values for the -ms-content-zoom-snap-points property. in the first
selector, the first snap-point is at 0%, and the interval is set to 100%. in the second
selector, each snap-point is listed separately—100%, 200%, 300%, and so on. .snappy1 { -ms-content-zoom-snap-points: snapinterval(0%, 100%); ... } .snappy2 { -ms-content-zoom-snap-points: snaplist(100%, 200%, 300%, 400%, 500%); ... } specifications not part of any specification. remarks this prop...
-ms-filter - Archive of obsolete content
filterfrom.filters.item(0).transition=12; imagefrom.style.visibility = "hidden"; filterto.style.visibility = ""; filterfrom.filters.item(0).play(14); } </script> </body> gradient progid:dximagetransform.microsoft.gr...
-ms-scroll-snap-points-x - Archive of obsolete content
croll-limit-x-min is used. if any value is greater than -ms-scroll-limit-x-max, then -ms-scroll-limit-x-max is used. formal syntax snapinterval( <length-percentage>, <length-percentage> ) | snaplist( <length-percentage># )where <length-percentage> = <length> | <percentage> examples this example demonstrates both types of values for the -ms-scroll-snap-points-x property. in the first
selector, the first snap-point is at 0%, and the interval is set to 100%. in the second
selector, each snap-point is listed separately — 100%, 200%, 300%, and so on. (the -ms-scroll-snap-points-x property behaves identically to the -ms-scroll-snap-points-y property, but along the x-axis.) .container { overflow-x: auto; overflow-y: hidden; -ms-scroll-snap-type: mandatory; -ms-scroll-snap-points-...
-ms-scroll-snap-points-y - Archive of obsolete content
croll-limit-y-min is used. if any value is greater than -ms-scroll-limit-y-max, then -ms-scroll-limit-y-max is used. formal syntax snapinterval( <length-percentage>, <length-percentage> ) | snaplist( <length-percentage># )where <length-percentage> = <length> | <percentage> examples this example demonstrates both types of values for the -ms-scroll-snap-points-y property. in the first
selector, the first snap-point is at 0%, and the interval is set to 100%. in the second
selector, each snap-point is listed separately — 100%, 200%, 300%, and so on. (the -ms-scroll-snap-points-y property behaves identically to the -ms-scroll-snap-points-x property, but along the y-axis.) .container { overflow-x: auto; overflow-y: hidden; -ms-scroll-snap-type: mandatory; -ms-scroll-snap-points-...
-ms-scroll-snap-x - Archive of obsolete content
rty is specified as one or both of the following values, in order and separated by spaces. -ms-scroll-snap-type the value of the -ms-scroll-snap-type property. -ms-scroll-snap-points-x the value of the -ms-scroll-snap-points-x property. formal syntax <'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-x'> examples the -ms-scroll-snap-x property is a shorthand property. the two
selectors in the following example have the same effect. .scroll1 { -ms-scroll-snap-type: proximity; -ms-scroll-snap-points-x: snaplist(100%, 200%, 300%, 400%, 500%); } .scroll2 { -ms-scroll-snap-x: proximity snaplist(100%, 200%, 300%, 400%, 500%); } specifications not part of any specification. remarks this property requires windows 8 or later. this property has no effect on non-scrollable ...
-ms-scroll-snap-y - Archive of obsolete content
rty is specified as one or both of the following values, in order and separated by spaces. -ms-scroll-snap-type the value of the -ms-scroll-snap-type property. -ms-scroll-snap-points-y the value of the -ms-scroll-snap-points-y property. formal syntax <'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-y'> examples the -ms-scroll-snap-y property is a shorthand property. the two
selectors in the following example have the same effect. .scroll1 { -ms-scroll-snap-type: mandatory; -ms-scroll-snap-points-y: snapinterval(0, 100%); } .scroll2 { -ms-scroll-snap-y: mandatory snapinterval(0, 100%); } specifications not part of any specification. remarks this property requires windows 8 or later. this property has no effect on non-scrollable elements. starting with windows 8...
:-moz-system-metric(images-in-menus) - Archive of obsolete content
the :-moz-system-metric(images-in-menus) css pseudo-class matches an element if the computer's user interface supports images in menus. this
selector is intended for use mainly by theme developers. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. ...
:-moz-system-metric(mac-graphite-theme) - Archive of obsolete content
:-moz-system-metric(mac-graphite-theme) will match an element if the user has chosen the "graphite" appearance in the "appearance" prefpane of the mac os x system preferences. this
selector is intended for use mainly by theme developers. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. examples demo ...
:-moz-system-metric(scrollbar-end-backward) - Archive of obsolete content
the :-moz-system-metric(scrollbar-end-backward) css pseudo-class will match an element if the computer's user interface includes a backward arrow button at the end of scrollbars. this
selector is intended for use mainly by theme developers. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(scrollbar-end-forward) - Archive of obsolete content
the :-moz-system-metric(scrollbar-end-forward) css pseudo-class will match an element if the computer's user interface includes a forward arrow button at the end of scrollbars. this
selector is intended for use mainly by theme developers. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(scrollbar-start-backward) - Archive of obsolete content
the :-moz-system-metric(scrollbar-start-backward) css pseudo-class will match an element if the computer's user interface includes a backward arrow button at the start of scrollbars. this
selector is intended for use mainly by theme developers. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(scrollbar-start-forward) - Archive of obsolete content
the :-moz-system-metric(scrollbar-start-forward) css pseudo-class will match an element if the computer's user interface includes a forward arrow button at the start of scrollbars. this
selector is intended for use mainly by theme developers. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. specifications not part of any specification. ...
:-moz-system-metric(windows-default-theme) - Archive of obsolete content
the :-moz-system-metric(windows-default-theme) css pseudo-class matches an element if the user is currently using one of the following themes in windows: luna, royale, zune, or aero (i.e., vista basic, vista standard, or aero glass). this will exclude windows classic themes as well as third-party themes. this
selector is intended for use mainly by theme developers. note: since firefox 58, this pseudo-class is no longer available to web content — it is only available internally (e.g. to xul / chrome code). see bug 1396066 for more details. example html content <p id="defaultthemes"> this paragraph should have a green background with luna/royale/zune/aero windows themes and red with other themes. </p> <p id="nondefaultthemes"> this paragraph should have a green background ...
::-ms-clear - Archive of obsolete content
. such inputs include: <input type="color"> <input type="date"> <input type="datetime"> <input type="datetime-local"> <input type="email"> <input type="month"> <input type="number"> <input type="search"> <input type="tel"> <input type="time"> <input type="url"> <input type="week"> allowable properties only the following css properties can be used in a rule with ::-ms-clear in its
selector. other properties are ignored. -ms-high-contrast-adjust background-clip background-color background-image background-origin background-position-x background-position-y background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-style border-left-width border-ri...
::-ms-fill-lower - Archive of obsolete content
the ::-ms-fill-lower css pseudo-element represents the lower portion of the track of a slider control; that is, the portion corresponding to values less than the value currently selected by the thumb. a slider control is one possible representation of <input type="range">. allowable properties only the following css properties can be used in a rule with ::-ms-fill-lower in its
selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-style border-left-width border-right-color border-right-style border-right-width border-top-color border-top-left...
::-ms-fill-upper - Archive of obsolete content
upper css pseudo-element is a microsoft extension that represents the upper portion of the track of a slider control; that is, the portion corresponding to values greater than the value currently selected by the thumb. a slider control is one possible representation of <input type="range">. allowable properties only the following css properties can be used in a rule with ::-ms-fill-upper in its
selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-style border-left-width border-right-color border-right-style border-right-width border-top-color bor...
::-ms-fill - Archive of obsolete content
can change the animation, as shown in this table: value description none turns off the animation so that no dots are displayed. -ms-bar shows animated dots that flow in a bar pattern. -ms-ring shows animated dots that flow in a ring pattern. allowable properties only the following css properties can be used in a rule with ::-ms-fill in its
selector. other properties are ignored. animation-name background-clip, background-color, background-image, background-origin, background-repeat, and background-size border border-radius box-shadow box-sizing color cursor display (values block, inline-block, none) font height margin -ms-background-position-x -ms-background-position-y -ms-high-contrast-adjust opacity outline-color, outli...
::-ms-reveal - Archive of obsolete content
sword field created by <input type="password">. the user presses the button to reveal the actual field value rather than asterisks. the password reveal button is usually displayed at the edge of the password field. the ::-ms-reveal pseudo-element is specific to internet explorer 10 and later. allowable properties only the following css properties can be used in a rule with ::-ms-reveal in its
selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-style border-left-width border-right-color border-right-style border-right-width border-top-color bor...
::-ms-ticks-after - Archive of obsolete content
ay property to block. it is possible to use the ::-ms-ticks-after, ::-ms-ticks-before, and ::-ms-track pseudo-elements together. to do so would create three sets of tick marks, but the best user experience is one set. to remove tick marks altogether, set the color property to transparent. allowable properties only the following css properties can be used in a rule with ::-ms-ticks-after in its
selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-style border-left-width border-right-color border-right-style border-right-width border-top-color bor...
::-ms-ticks-before - Archive of obsolete content
y property to block. it is possible to use the ::-ms-ticks-after, ::-ms-ticks-before, and ::-ms-track pseudo-elements together. to do so would create three sets of tick marks, but the best user experience is one set. to remove tick marks altogether, set the color property to transparent. allowable properties only the following css properties can be used in a rule with ::-ms-ticks-before in its
selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-style border-left-width border-right-color border-right-style border-right-width border-top-color bor...
::-ms-track - Archive of obsolete content
the ::-ms-track css pseudo-element is a microsoft extension that represents the track of a slider control. a slider control is one possible representation of <input type="range">. applying the color property within the ::-ms-track
selector affects the tick marks inside the track area. it is possible to use the ::-ms-ticks-after, ::-ms-ticks-before, and ::-ms-track pseudo-elements together. to do so would create three sets of tick marks, but the best user experience is one set. to remove tick marks altogether, set the color property to transparent. allowable properties only the following css properties can be used in a rule with ::-ms-track in its
selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat backgroun...
Accessing XML children - Archive of obsolete content
n types of nodes as well. var a = <foo> some text <bar>not text</bar> more text </foo>; var list = a.text(); list.length(); // returns 2 list[0]; // returns " some text " list[1]; // returns " more text " you can similarly access comment nodes: xml.ignorecomments = false; var a = <foo> some <!-- abc --> text </foo>; var comments = a.comments(); alert(comments[0]); // returns <!-- abc --> the *
selector will return all child nodes in an xml list. var a = <foo> <bar/> <baz/> </foo>; var list = a.*; list.length(); // returns 2 element attributes many xml elements have attributes with particular values assigned to them. for instance <pets> <dog color="brown">fido</dog> <cat color="grey">fluffy</cat> </pets> e4x allows you to access the attributes of a particular el...
Descendants and Filters - Archive of obsolete content
"/> <spike color="blue"/> </dogs> </pets>; element..fido.@color = "green"; element..spike.@color = "purple"; changes the colors of both of our pet dogs. the same rules that apply to the . operator apply to the .. operator. that is, if there are multiple descendants of the requested type, an xml list is returned, instead of the normal element. the *
selector returns all descendants in an xml list. filters in many cases, especially with the *
selector, you don't want to work with all of the nodes that would be returned by the . or .. operator. to work with only a specific subset, place a conditional in parentheses after the operator. consider var element = <dogs> <fido color="brown"/> <spike color="black"/> ...
Building up a basic demo with A-Frame - Game development
ooth material) and metalness (how metallic the material is). adding some javascript to the mix it is possible to populate the scene with entities created using javascript too, so let's use it to add a third shape, a cylinder. add a new <script> element at the end of the <body> element, just after the <a-scene> element, then add the following javascript code inside it: var scene = document.query
selector('a-scene'); var cylinder = document.createelement('a-cylinder'); cylinder.setattribute('color', '#ff9500'); cylinder.setattribute('height', '2'); cylinder.setattribute('radius', '0.75'); cylinder.setattribute('position', '3 1 0'); scene.appendchild(cylinder); we're getting a reference to the scene handler first, then we create the cylinder element as an a-frame entity. after that it's all about...
CSS Object Model (CSSOM) - MDN Web Docs Glossary: Definitions of Web-related terms
the cssom is very similar to the document object model (dom). both of them are part of the critical rendering path which is a series of steps that must happen to properly render a website. the cssom, together with the dom, to build the render tree, which is in turn used by the browser to layout and paint the web page. cssom api the css object model is also a set of apis allowing the manipulation of css from javascript. it is much like the dom, but for the css rather than the html. it allows users to read and modify the css style dynamically. ...
CSS preprocessor - MDN Web Docs Glossary: Definitions of Web-related terms
a css preprocessor is a program that lets you generate css from the preprocessor's own unique syntax. there are many css preprocessors to choose from, however most css preprocessors will add some features that don't exist in pure css, such as mixin, nesting
selector, inheritance
selector, and so on. these features make the css structure more readable and easier to maintain. to use a css preprocessor, you must install a css compiler on your web server; or use the css preprocessor to compile on the development environment, and then upload compiled css file to the web server. ...
Pseudo-class - MDN Web Docs Glossary: Definitions of Web-related terms
in css, a pseudo-class
selector targets elements depending on their state rather than on information from the document tree. for example, the
selector a:visited applies styles only to links that the user has already followed. learn more technical reference pseudo-class documentation ...
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
jquery is a javascript library that focuses on simplifying dom manipulation, ajax calls, and event handling. jquery uses a format, $(
selector).action() to assign an element(s) to an event. to explain it in detail, $(
selector) will call jquery to select
selector element(s), and assign it to an event api called .action(). $(document).ready(function(){ alert("hello world!"); $("#blackbox").hide(); }); the above code carries out the same function as the following code: window.onload = function() { alert("hello world!"); document.getelementbyid("blackbox").style.display = "none"; }; or: window.addeventlistener("load", () => { alert("hello world!"); document.getelementbyid("blackbox").style.display = "none"; }); learn more general knowledge jquery on wikipedia jquery offi...
MDN Web Docs Glossary: Definitions of Web-related terms
ol) and srtp (secure rtp) rtsp: real-time streaming protocol ruby s safe same-origin policy scm scope screen reader script-supporting element scroll container scrollport sctp sdp search engine second-level domain secure sockets layer (ssl)
selector (css) self-executing anonymous function semantics seo serialization server server timing session hijacking sgml shadow tree shim signature signature (functions) signature (security) simd simple header simple response header sisd site ...
Assessment: Accessibility troubleshooting - Learn web development
hat happens when you try to navigate it using a screenreader. can you update the article text to make it easier for screenreader users to navigate? the navigation menu part of the site (wrapped in <div class="nav"></div>) could be made more accessible by putting it in a proper html5 semantic element. which one should it be updated to? make the update. note: you'll need to update the css rule
selectors that style the tags to their proper equivalents for the semantic headings. once you add paragraph elements, you'll notice the styling looking better. the images the images are currently inaccessible to screenreader users. can you fix this? the audio player the <audio> player isn't accessible to hearing impaired (deaf) people — can you add some kind of accessible alternative for these ...
Test your skills: CSS and JavaScript accessibility - Learn web development
you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. css accessibility 1 in the first task you are presented with a list of links. however, their accessibility is pretty bad — there is no way to really tell that they are links, or to tell which one the user is focussed on. we'd like you to assume that the existing ruleset with the a
selector is supplied by some cms, and that you can't change it — instead, you need to create new rules to make the links look and behave like links, and for the user to be able to tell where they are in the list. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. css accessibility 2 in th...
HTML: A good basis for accessibility - Learn web development
ce — the screen reader hasn't got anything to use as signposts, so you can't retrieve a useful table of contents, and the whole page is seen as a single giant block, so it is just read out in one go, all at once. there are other issues too beyond accessibility — it is harder to style the content using css, or manipulate it with javascript, for example, because there are no elements to use as
selectors. using clear language the language you use can also affect accessibility. in general, you should use clear language that is not overly complex and doesn't use unnecessary jargon or slang terms. this not only benefits people with cognitive or other disabilities; it benefits readers for whom the text is not written in their first language, younger people ... everyone, in fact! apart from this, y...
HTML: A good basis for accessibility - Learn web development
ce — the screen reader hasn't got anything to use as signposts, so you can't retrieve a useful table of contents, and the whole page is seen as a single giant block, so it is just read out in one go, all at once. there are other issues too beyond accessibility — it is harder to style the content using css, or manipulate it with javascript, for example, because there are no elements to use as
selectors. using clear language the language you use can also affect accessibility. in general, you should use clear language that is not overly complex and doesn't use unnecessary jargon or slang terms. this not only benefits people with cognitive or other disabilities; it benefits readers for whom the text is not written in their first language, younger people ... everyone, in fact! apart from this, y...
Test your skills: Images and Form elements - Learn web development
ace, but we do not mind if some part of the image is cropped. in the example below see if you can match the image above. for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in this task, you have a simple form. your task is to make the following changes to the way this form looks: use attribute
selectors to target the search field and button inside .myform. make the form field and button use the same text size as the rest of the form. give the form field and button 10 px of padding. give the button a purple background (i used rebeccapurple), white foreground, no border and rounded corners of 5px. try updating the live code below to recreate the example as displayed in the image: for a...
Responsive design - Learn web development
of tests (e.g. whether the user's screen is greater than a certain width, or a certain resolution) and apply css selectively to style the page appropriately for the user's needs. for example, the following media query tests to see if the current web page is being displayed as screen media (therefore not a printed document) and the viewport is at least 800 pixels wide. the css for the .container
selector will only be applied if these two things are true. @media screen and (min-width: 800px) { .container { margin: 1em 2em; } } you can add multiple media queries within a stylesheet, tweaking your whole layout or parts of it to best suit the various screen sizes. the points at which a media query is introduced, and the layout changed, are known as breakpoints. a common approach when usi...
Using your new knowledge - Learn web development
r further help section at the bottom of this page. working with css the following live example shows a biography, which has been styled using css. the css properties that i have used are as follows — each one links to its property page on mdn, which will give you more examples of its use. font-family color border-bottom font-weight font-size text-decoration i have used a mixture of
selectors, styling elements such as h1 and h2, but also creating a class for the job title and styling that. use css to change how this biography looks by changing the values of the properties i have used. make the level one heading pink, using the css color keyword hotpink. give the heading a 10px dotted border-bottom which uses the css color keyword purple. make the level 2 heading italic. give t...
What is CSS? - Learn web development
rule-based language — you define rules specifying groups of styles that should be applied to particular elements or groups of elements on your web page. for example "i want the main heading on my page to be shown as large red text." the following code shows a very simple css rule that would achieve the styling described above: h1 { color: red; font-size: 5em; } the rule opens with a
selector . this selects the html element that we are going to style. in this case we are styling level one headings (<h1>). we then have a set of curly braces { }. inside those will be one or more declarations, which take the form of property and value pairs. each pair specifies a property of the element(s) we are selecting, then a value that we'd like to give the property. before the colon, we have the...
Using CSS generated content - Learn web development
of your stylesheet in different files and arrange for them to be linked with the appropriate language versions of your doucment. this issue does not arise if the content you specify consists of symbols or images that apply in all languages and cultures. examples text content css can insert text content before or after an element. to specify this, make a rule and add ::before or ::after to the
selector. in the declaration, specify the content property with the text content as its value. html a text where i need to <span class="ref">something</span> css .ref::before { font-weight: bold; color: navy; content: "reference "; } output the character set of a stylesheet is utf-8 by default, but it can also be specified in the link, in the stylesheet itself, or in other ways. for details...
Fundamental text and font styling - Learn web development
id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"> p { } </textarea> <h2>output</h2> <div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div> <div class="controls"> <input id="reset" type="button" value="reset" style="margin: 10px 10px 0 0;"> </div> </div> const htmlinput = document.query
selector(".html-input"); const cssinput = document.query
selector(".css-input"); const reset = document.getelementbyid("reset"); let htmlcode = htmlinput.value; let csscode = cssinput.value; const output = document.query
selector(".output"); const styleelem = document.createelement('style'); const headelem = document.query
selector('head'); headelem.appendchild(styleelem); function drawoutput() { output.
Styling lists - Learn web development
d;"></textarea> <h2>output</h2> <div class="output" style="width: 90%;height: 12em;padding: 10px;border: 1px solid #0095dd;overflow: auto;"></div> <div class="controls"> <input id="reset" type="button" value="reset" style="margin: 10px 10px 0 0;"> <input id="solution" type="button" value="show solution" style="margin: 10px 0 0 10px;"> </div> </div> var htmlinput = document.query
selector(".html-input"); var cssinput = document.query
selector(".css-input"); var reset = document.getelementbyid("reset"); var htmlcode = htmlinput.value; var csscode = cssinput.value; var output = document.query
selector(".output"); var solution = document.getelementbyid("solution"); var styleelem = document.createelement('style'); var headelem = document.query
selector('head'); headelem.appendchild(styl...
Typesetting a community school homepage - Learn web development
of this page. project brief you have been provided with some raw html for the homepage of an imaginary community college, plus some css that styles the page into a three column layout and provides some other rudimentary styling. you are to write your css additions below the comment at the bottom of the css file, to make sure it is easy to mark the bits you have done. don't worry if some of the
selectors are repetitious; we'll let you off in this instance. fonts: first of all, download a couple of free-to-use fonts. because this is a college, the fonts should be chosen to give the page a fairly serious, formal, trustworthy feel — a serif site-wide font for the general text body, coupled with sans-serif or slab serif for the headings might be nice. use a suitable service to generate bullet...
Learn to style HTML using CSS - Learn web development
ery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to html. css building blocks this module carries on where css first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. this module looks at the cascade and inheritance, all the
selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. the aim here is to provide you with a toolkit for writing competent css and help you understand all the essential theory, before moving on to more specific disciplines like text styling and css layout. styling text with the basics of the css language covered, the next css topic for you to conc...
The HTML5 input types - Learn web development
uld display an input value or the output of a calculation inside any element, but <output> is special — like <label>, it can take a for attribute that allows you to associate it with the element or elements that the output value came from. to actually display the current value, and update it as it changed, you must use javascript, but this is relatively easy to do: const price = document.query
selector('#price'); const output = document.query
selector('.price-output'); output.textcontent = price.value; price.addeventlistener('input', function() { output.textcontent = price.value; }); here we store references to the range input and the output in two variables. then we immediately set the output's textcontent to the current value of the input. finally, an event listener is set to ensure that ...
HTML forms in legacy browsers - Learn web development
input { /* this rule turns off the default rendering for the input types that have a border, including buttons defined with an input element */ border: 1px solid #ccc; } input[type="button"] { /* this does not restore the default rendering */ ...
Example 2 - Learn web development
m; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content window.addeventlistener("load", function () { var form = document.query
selector('form'); form.classlist.remove("no-widget"); form.classlist.add("widget"); }); result for js no js html content <form class="no-widget"> <select name="myfruit"> <option>cherry</option> <option>lemon</option> <option>banana</option> <option>strawberry</option> <option>apple</option> </select> <div class="select"> <span class="value">cherry</span> ...
Styling web forms - Learn web development
he good to style form controls that are easy to style with css, you shouldn't face much if any difficulties, since they mostly behave like any other html element. we already looked at some simple form styling in your first form, and the css building blocks module contains some useful form styling essentials too. as well as the basic css tools covered above, we've also been provided with several
selectors — ui pseudo-classes — that enable styling based on the current state of the ui. we cover these in detail in the next article, ui pseudo-classes. we'll walk through an example at the end of this article to give you some more ideas on basic form control styling and placement. before we do that however, we'd like to say a few words about specific aspects of form styling that are worth knowing ...
The web and web standards - Learn web development
paper, carpets and paintings you'd use to make the house look nice. javascript is the programming language we use to add interactivity to web sites, from dynamic style switching, to fetching updates from the server, right through to complex 3d graphics. ...
Tips for authoring fast-loading HTML pages - Learn web development
browser can immediately determine the height and/or width of your images and tables, it will be able to display a web page without having to reflow the content. this not only speeds the display of the page but prevents annoying changes in a page's layout when the page completes loading. for this reason, height and width should be specified for images, whenever possible. tables should use the css
selector: property combination: table-layout: fixed; and should specify widths of columns using the <col> and the <colgroup> elements. use lazy loading for images by default, imags are loaded eagerly; that is, the image is fetched and rendered as soon as it's processed in the html. all eagerly loaded images are rendered before the document's load event is sent. switching to lazy loading of images t...
Adding vector graphics to the Web - Learn web development
" disabled> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.query
selector('.output'); let code = textarea.value; let userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
From object to iframe — other embedding technologies - Learn web development
solution"> </div> html { font-family: sans-serif; } h2 { font-size: 16px; } .a11y-label { margin: 0; text-align: right; font-size: 0.7rem; width: 98%; } body { margin: 10px; background: #f5f9fa; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.query
selector('.output'); let code = textarea.value; let userentry = textarea.value; function updatecode() { output.innerhtml = textarea.value; } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = htmlsolution; solution.value = 'show solution'; updatecode(); }); solution.addeventlistener('click', function() { if(solution.value === 's...
Responsive images - Learn web development
this was a page that had many pictures on it. using this technique could save mobile users a lot of bandwidth. note: when testing this with a desktop browser, if the browser fails to load the narrower images when you've got its window set to the narrowest width, have a look at what the viewport is (you can approximate it by going into the browser's javascript console and typing in document.query
selector('html').clientwidth). different browsers have minimum sizes that they'll let you reduce the window width to, and they might be wider than you'd think. when testing it with a mobile browser, you can use tools like firefox's about:debugging page to inspect the page loaded on the mobile using the desktop developer tools. to see which images were loaded, you can use firefox devtools's network moni...
Video and audio content - Learn web development
tecting track addition and removal you can monitor the track lists within a media element to detect when tracks are added to or removed from the element's media. for example, you can watch for the addtrack event being fired on the associated audiotracklist object (retrieved via htmlmediaelement.audiotracks) to be informed when audio tracks are added to the media: const mediaelem = document.query
selector("video"); mediaelem.audiotracks.onaddtrack = function(event) { audiotrackadded(event.track); } you'll find more information about this in our trackevent documentation. displaying video text tracks now we'll discuss a slightly more advanced concept that is really useful to know about. many people can't or don't want to hear the audio/video content they find on the web, at least at certain ti...
HTML table advanced features and accessibility - Learn web development
e elements are for applying css. inside the head of your html document, you'll see an empty <style> element. inside this element, add the following lines of css code: tbody { font-size: 95%; font-style: italic; } tfoot { font-weight: bold; } save and refresh, and have a look at the result. if the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated
selectors/rules to apply the same styling. note: we don't expect you to fully understand the css right now. you'll learn more about this when you go through our css modules (introduction to css is a good place to start; we also have an article specifically on styling tables). your finished table should look something like the following: hidden example <!doctype html> <html> <head> <meta char...
HTML table basics - Learn web development
'll tell you about in this article before we move on. html has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. these exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex
selector such as :nth-child(). note: styling columns like this is limited to a few properties: border, background, width, and visibility. to set other properties you'll have to either style every <td> or <th> in the column, or use a complex
selector such as :nth-child(). take the following simple example: <table> <tr> <th>data 1</th> <th style="background-color: yellow">data 2</th> </tr> ...
Introducing asynchronous JavaScript - Learn web development
we understand what synchronous javascript is. this section recaps some of the information we saw in the previous article. a lot of the functionality we have looked at in previous learning area modules is synchronous — you run some code, and the result is returned as soon as the browser can do so. let's look at a simple example (see it live here, and see the source): const btn = document.query
selector('button'); btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); in this block, the lines are executed one after the other: we grab a reference to a <button> element that is already available in the dom. we add a click event listener to it...
Functions — reusable blocks of code - Learn web development
but you can also create a function that doesn't have a name: function() { alert('hello'); } this is called an anonymous function — it has no name! it also won't do anything on its own. you generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked: const mybutton = document.query
selector('button'); mybutton.onclick = function() { alert('hello'); } the above example would require there to be a <button> element available on the page to select and click. you've already seen this structure a few times throughout the course, and you'll learn more about and see it in use in the next article. you can also assign an anonymous function to be the value of a variable, for example: con...
Drawing graphics - Learn web development
we have multiple canvases on the page, but we have removed the width and height attributes for now (you could add them back in if you wanted, but we will set them using javascript in a below section). canvases with no explicit width and height default to 300 pixels wide by 150 pixels high. now add the following lines of javascript inside the <script> element: const canvas = document.query
selector('.mycanvas'); const width = canvas.width = window.innerwidth; const height = canvas.height = window.innerheight; here we have stored a reference to the canvas in the canvas constant. in the second line we set both a new constant width and the canvas' width property equal to window.innerwidth (which gives us the viewport width). in the third line we set both a new constant height and the canvas...
Fetching data from the server - Learn web development
recognize) via xhr when it's selected in the drop-down menu. just inside the <script> element, add the following code. this stores a reference to the <select> and <pre> elements in constants and defines an onchange event handler function so that when the select's value is changed, its value is passed to an invoked function updatedisplay() as a parameter. const versechoose = document.query
selector('select'); const poemdisplay = document.query
selector('pre'); versechoose.onchange = function() { const verse = versechoose.value; updatedisplay(verse); }; let's define our updatedisplay() function. first of all, put the following beneath your previous code block — this is the empty shell of the function. note: steps 4 - 9 will all be performed within this function. function updat...
Third-party APIs - Learn web development
the repo for the example files you need in each section. they are found on third-party servers browser apis are built into the browser — you can access them from javascript immediately. for example, the web audio api we saw in the introductory article is accessed using the native audiocontext object. for example: const audioctx = new audiocontext(); ... const audioelement = document.query
selector('audio'); ... const audiosource = audioctx.createmediaelementsource(audioelement); // etc. third party apis, on the other hand, are located on third party servers. to access them from javascript you first need to connect to the api functionality and make it available on your page. this typically involves first linking to a javascript library available on the server via a <script> element, as s...
Silly story generator - Learn web development
he javascript is applied to your html properly, try removing everything else from the javascript file temporarily, adding in a simple bit of javascript that you know will create an obvious effect, then saving and refreshing. the following for example turns the background of the <html> element red — so the entire browser window should go red if the javascript is applied properly: document.query
selector('html').style.backgroundcolor = 'red'; math.round() is a built-in javascript method that simply rounds the result of a calculation to the nearest whole number. there are three instances of strings that need to be replaced. you may repeat the replace() method multiple times, or you can use regular expressions. for instance, let text = 'i am the biggest lover, i love my love'; text.replace(/lov...
Handling text — strings in JavaScript - Learn web development
actual strings. try this: let response = one + 'i am fine — ' + two; response; note: when you enter an actual string in your code, enclosed in single or double quotes, it is called a string literal. concatenation in context let's have a look at concatenation being used in action — here's an example from earlier in the course: <button>press me</button> const button = document.query
selector('button'); button.onclick = function() { let name = prompt('what is your name?'); alert('hello ' + name + ', nice to see you!'); } here we're using a window.prompt() function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable — in this case name. we then use a window.alert() function in line 5 to display ano...
Storing the information you need — Variables - Learn web development
are browser developer tools for more information on how to access this tool). what is a variable? a variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. but one special thing about variables is that their contained values can change. let's look at a simple example: <button>press me</button> const button = document.query
selector('button'); button.onclick = function() { let name = prompt('what is your name?'); alert('hello ' + name + ', nice to see you!'); } in this example pressing the button runs a couple of lines of code. the first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. the second line displays a welcome message that includes their nam...
JavaScript object basics - Learn web development
'); you were using a method available on an instance of the string class. every time you create a string in your code, that string is automatically created as an instance of string, and therefore has several common methods and properties available on it. when you accessed the document object model using lines like this: const mydiv = document.createelement('div'); const myvideo = document.query
selector('video'); you were using methods available on an instance of the document class. for each webpage loaded, an instance of document is created, called document, which represents the entire page's structure, content, and other features such as its url. again, this means that it has several common methods and properties available on it. the same is true of pretty much any other built-in object or a...
Working with JSON - Learn web development
tter contains some simple css to style our page, while the former contains some very simple body html: <header> </header> <section> </section> plus a <script> element to contain the javascript code we will be writing in this exercise. at the moment it only contains two lines, which grab references to the <header> and <section> elements and store them in variables: const header = document.query
selector('header'); const section = document.query
selector('section'); we have made our json data available on our github, at https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json. we are going to load it into our page, and use some nifty dom manipulation to display it, like this: obtaining the json to obtain the json, we use an api called xmlhttprequest (often called xhr). this ...
Object building practice - Learn web development
and javascript to our html. some very simple styles, which mainly serve to style and position the <h1>, and get rid of any scrollbars or margin around the edge of the page (so that it looks nice and neat). some javascript that serves to set up the <canvas> element and provide a general function that we're going to use. the first part of the script looks like so: const canvas = document.query
selector('canvas'); const ctx = canvas.getcontext('2d'); const width = canvas.width = window.innerwidth; const height = canvas.height = window.innerheight; this script gets a reference to the <canvas> element, then calls the getcontext() method on it to give us a context on which we can start to draw. the resulting constant (ctx) is the object that directly represents the drawing area of the canvas and...
Server-side web frameworks - Learn web development
form validation, testing framework, static file server, cgi/psgi detection, and first-class unicode support. a full-stack http and websocket client/server implementation with ipv6, tls, sni, idna, http/socks5 proxy, unix domain socket, comet (long polling), keep-alive, connection pooling, timeout, cookie, multipart, and gzip compression support. json and html/xml parsers and generators with css
selector support. very clean, portable and object-oriented pure-perl api with no hidden magic. fresh code based upon years of experience, free and open-source. spring boot (java) spring boot is one of a number of projects provided by spring. it is a good starting point for doing server-side web development using java. although definitely not the only framework based on java it is easy to use to crea...
React interactivity: Events and state - Learn web development
rminal/command line. objective: to learn about handling events and state in react, and use those to start making the case study app interactive. handling events if you've only written vanilla javascript before now, you might be used to having a separate javascript file, where you query for some dom nodes and attach listeners to them. ...
Getting started with Svelte - Learn web development
on by opening localhost:5000 in a new browser tab, right/ctrl-clicking on the hello world! label, and choosing inspect: when compiling the app, svelte changes our h1 styles definition to h1.svelte-1tky8bj, and then modifies every <h1> element in our component to <h1 class="svelte-1tky8bj">, so that it picks up the styles as required. note: you can override this behavior and apply styles to a
selector globally using the :global(...) modifier (see the svelte <style> docs for more information). making a couple of changes now that we have a general idea of how it all fits together, we can start making a few changes. at this point you can try updating your app.svelte component — for example change the <h1> element on line 6 of app.svelte so that it reads like this: <h1>hello {name} from mdn...
Styling Vue components with CSS - Learn web development
the last component we want to style is our todoitem component. to keep the style definitions close to the component we can add a <style> element inside it. however, if these styles alter things outside of this component, it could be challenging to track down the styles responsible, and fix the problem. this is where the scoped attribute can be useful — this attaches a unique html data attribute
selector to all of your styles, preventing them from colliding globally. to use the scoped modifier, create a <style> element inside todoitem.vue, at the bottom of the file, and give it a scoped attribute: <style scoped> </style> next, copy the following css into the newly created <style> element: .custom-checkbox > .checkbox-label { font-family: arial, sans-serif; -webkit-font-smoothing: antialia...
Introducing a complete toolchain - Learn web development
oject too — run the following command in your terminal: npm install --save-dev parcel-bundler using future features the code for our project is using some new web features including features that are so new they aren't fully standardised yet. for example, instead of reaching for a tool like sass, this particular project uses the w3c proposal for css nesting. css nesting allows us to nest css
selectors and properties inside one another thus creating more specific
selector scope. sass was one of the first preprocessors to support nesting (if not the first) but now after many years, nesting looks like it will soon be standardised, which means that we will have it available in our browsers without needing build tools. until then, parcel will do the transformation between nested css and natively ...
Experimental features in Firefox
rowser follows a system-wide color scheme setting). see bug 1550804 and bug 1137699 for more details. release channel version added enabled by default? nightly 72 no developer edition 72 no beta 72 no release 72 no preference name devtools.inspector.color-scheme-simulation.enabled execution context
selector this feature displays a button on the console's command line that lets you change the context in which the expression you enter will be executed. see bug 1605154 and bug 1605153 for more details. release channel version added enabled by default? nightly 75 no developer edition 75 no beta 75 no release 75 no ...
Multiple Firefox profiles
also like to allow multiple instances of firefox to run at the same time, add "-no-remote" after the profile name. mac os x you can find a useful tutorial to set up custom launchers here: managing multiple firefox profiles in osx. do note it's best to follow all steps in the "creating the scripts" section, including the "edit info.plist" step. leave off the profile name if you want the profile
selector to show up every time you launch. setting up multiple profiles for different firefox channels this section will be especially helpful if you are a developer, wanting to work with multiple channels, and each having their separate launcher. windows in windows, the developer and nightly builds get their own directory in the "programs" folder, so you don't have to worry about where to store the d...
HTMLIFrameElement.addNextPaintListener()
is event provides information about what has been repainted. it is mainly used to investigate performance optimization. note: the handler will receive the event once and then be thrown away. syntax instanceofhtmliframeelement.addnextpaintlistener(listener); returns void. parameters listener a function handler to listen for a mozafterpaint event. examples var browser = document.query
selector('iframe'); function onnextpaint() { console.log("paint has occured"); } browser.addnextpaintlistener(onnextpaint); specification not part of any specification. ...
HTMLIFrameElement.download()
llowing optional settings to be specified for the download. the available options are: filename: the filename to save the downloaded file as. if this is not specified, the filename used will be the original filename, as specified in the url. referrer: specifies a referrer for the downloaded file. if this is not specified there will be no referrer. examples var browser = document.query
selector('iframe'); var request = browser.download(foourl, { filename: 'foo.bin' }); request.onsuccess = function() { console.log("file downladed"); } request.onerror = function() { console.log("download error"); } specification not part of any specification. ...
Getting from Content to Layout
tructor implements nsimutationobserver which allows it to "watch" the content tree. nscssframeconstructor gets notified from the document's presshell (which implements nsidocumentobserver and observes the document) about all nodes in the document. the frame constructor takes these notifications and does the following: dispatches "restyle events" which trigger the reprocessing of relevant css
selectors and any restyling that needs to occur. adds and removes frames to make the frame tree a proper representation of the new content tree. restyling the restyletracker maintains a list of restyles to process. elements that need to be restyled are marked with flags (e.g element_has_pending_restyle) and are stored in the mpendingrestyles hashtable. a list of restyle roots (places in the content ...
PopupNotifications.jsm
er interaction). removeondismissal notifications with this parameter set to true will be removed when they would have otherwise been dismissed (that is, any time the popup is closed due to user interaction). popupiconurl a string specifying the url of the image to be displayed in the popup. this is normally specified in css using list-style-image and the .popup-notification-icon[popupid=...]
selector. learnmoreurl a string url. setting this property will make the prompt display a "learn more" link that, when clicked, opens the url in a new tab. notification events if you specify an event callback using the options parameter when calling show(), the callback function gets invoked when the state of the notification changes. the first parameter to the callback is a string identifying the st...
Mozilla Content Localized in Your Language
be truncated or resolved through ellipsis. title on the final page (meaning no more click through) should allow enough room to display full text. buttons capitalize the first letter of each word. limit to one or two words. use verbs that precisely describe the button's action. for example, "cancel", "clear history", "add email", "select all", etc. value
selector lists capitalize the first letter of the first word and the first letter of any proper nouns. limit to one or two words. note: if this doesn't apply to your language, indicate so as n/a. articles -- avoid them articles (such as the word "the" in english) should be avoided wherever possible. user interface elements have limited space available for text. ...
Localizing with Pontoon
using firefox affiliates website to demo pontoon's functionality and workflow. and there it is, opened inside pontoon: main toolbar as you can see, most of the interface is taken by the website being translated. only the toolbar on top belongs to pontoon, containing the following items (from left to right): list of strings opens a sidebar with a list of all strings to localize. project
selector (affiliates) switches between projects to localize. resource
selector (homepage) switches between project resources to localize, like subpages or localization files. hidden if no resources available for project. locale
selector (slovenian) switches between languages to localize. go opens project-resource-locale selection. progress indicator displays your progress on the resource b...
TimerFirings logging
_shot): [content] http://widgets.outbrain.com/outbrain.js:20:330 186 fn timer (one_shot): nsbrowserstatusfilter::timeouthandler 138 fn timer (one_shot): [content] https://self-repair.mozilla.org/repair/:7:13669 118 fn timer (one_shot): [content] http://a.visualrevenue.com/vrs.js:6:9423 108 fn timer (slack): layeractivitytracker 104 fn timer (slack): nsidocument::
selectorcache 104 fn timer (slack): cctimerfired ...
NSS_3.12.3_release_notes.html
x bug 335016: mpp_pprime (miller-rabin probabilistic primality test) may choose 0 or 1 as the random integer bug 347037: make shlibsign depend on the softoken only bug 371522: auto-update of crls stops after first update bug 380784: pk11mode in non fips mode failed. bug 394077: libpkix need to return revocation status of a cert bug 412468: modify certutil bug 417092: modify pkix_cert
selector api to return an error if cert was rejected. bug 426413: audit messages need distinct types bug 438870: free freebl hashing code of dependencies on nspr and libutil bug 439115: db merge allows nickname conflicts in merged db bug 439199: sse2 instructions for bignum are not implemented on windows 32-bit bug 441321: tolerate incorrect encoding of dsa signatures in ssl 3.0 handshakes bug...
nsIDOMWindowUtils
ise, no flush occurs. ascrollx ascrolly getvisiteddependentcomputedstyle() perform the equivalent of: window.getcomputedstyle(aelement, apseudoelement). getpropertyvalue(apropertyname) except that, when the link whose presence in history is allowed to influence aelement's style is visited, get the value the property would have if allowed all properties to change as a result of :visited
selectors (except for cases where getcomputedstyle uses data from the frame). this is easier to implement than adding our property restrictions to this api, and is sufficient for the present testing requirements (which are essentially testing 'color'). astring getvisiteddependentcomputedstyle( in nsidomelement aelement, in astring apseudoelement, in astring apropertyname ); parameters aelemen...
Use SQLite
storage of 2mb: var db = opendatabase('mydb', '1.0', 'test db', 2 * 1024 * 1024); var msg; db.transaction(function (tx) { tx.executesql('create table if not exists logs (id unique, log)'); tx.executesql('insert into logs (id, log) values (1, "foobar")'); tx.executesql('insert into logs (id, log) values (2, "logmsg")'); msg = '<p>log message created and row inserted.</p>'; document.query
selector('#status').innerhtml = msg; }); db.transaction(function (tx) { tx.executesql('select * from logs', [], function (tx, results) { var len = results.rows.length, i; msg = "<p>found rows: " + len + "</p>"; document.query
selector('#status').innerhtml += msg; for (i = 0; i < len; i++){ msg = "<p><b>" + results.rows.item(i).log + "</b></p>"; document.query
selector('#status').i...
Introduction to DOM Inspector - Firefox Developer Tools
ne of several viewers to display information about that node in the object pane of the dom inspector application window, all of which are available from the menupopup accessed from the upper left corner of the the object pane. in order to find out what the actual name of the file is being used to provide the search go icon, you can select the css rules viewer from this menu and see the various
selectors and rules that have been applied. the rule that applies the search icon to the element uses a class simple
selector and uses a list-style-image property to point to a file in the current theme. the list of viewers available from the viewer menu gives you some idea about how extensive the dom inspector's inspecting capabilities are. the following descriptions provide an overview of what these vi...
Browser Console - Firefox Developer Tools
the browser console this can be done with the hudservice. this example here makes it so that when you mouse over the "clear" button it will clear the browser console: components.utils.import("resource://devtools/shared/loader.jsm"); var hudservice = devtools.require("devtools/client/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); var clearbtn = hud.chromewindow.document.query
selector('.webconsole-clear-console-button'); clearbtn.addeventlistener('mouseover', function() { hud.jsterm.clearoutput(true); }, false); bonus features available for add-on sdk add-ons, the console api is available automatically. here's an example add-on that just logs an error when the user clicks a widget: widget = require("sdk/widget").widget({ id: "an-error-happened", label: "error!", wid...
CSS Flexbox Inspector: Examine Flexbox layouts - Firefox Developer Tools
eath the layout tab on the right-hand pane of the page inspector. the above and below screenshots should give you further hints on how to get to this. flex container options the flex container section of the layout view looks like this: there are two settings you can change in the flex container section: you can control the color of the overlay by clicking on the small circle next to the
selector. this will toggle a color picker so you can select a different color for the overlay. the switch on the right-hand side of the flex container section will also toggle the overlay on and off. flex item properties the flex items within the flex container are displayed as a numbered list in the flex items section. each entry displays the item's
selector. hover over an element to highlight it on ...
CSS Grid Inspector: Examine grid layouts - Firefox Developer Tools
and display settings choices are persisted across page loads for each separate page. let's examine these features in more detail. overlay grid each grid present on a page has an entry in the "overlay grid" section: each entry consists of (from left to right): a checkbox allowing you to toggle the grid overlay for that grid on and off. a name label to represent the grid, consisting of a
selector identifying the html element that has the grid applied to it. clicking this also toggles the grid overlay on and off. a target icon that when clicked immediately selects the html element that this grid entry relates to, inside the html pane. a color picker icon that allows you to change the primary color of the grid overlay. this is useful for selecting different colors so you can easily tell y...
Taking screenshots - Firefox Developer Tools
ed. --filename string the name to use in saving the file. the file should have a ".png" extension. --fullpage boolean if included, the full webpage will be saved. with this parameter, even the parts of the webpage which are outside the current bounds of the window will be included in the screenshot. when used, "-fullpage" will be appended to the file name. --
selector string a css
selector that selects a single element on the page. when supplied, only this element and its descendants will be included in the screenshot. note: if you capture an image to a filename like test.png, and then you capture to that same filename, the new image will overwrite the old image. so if you’re using the up-arrow history scroll to capture images in quick success...
AbortController.AbortController() - Web APIs
h request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.query
selector('.download'); var abortbtn = document.query
selector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }...
AbortController.abort() - Web APIs
h request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.query
selector('.download'); var abortbtn = document.query
selector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }...
AbortController.signal - Web APIs
h request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.query
selector('.download'); var abortbtn = document.query
selector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }...
AbortController - Web APIs
h request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.query
selector('.download'); var abortbtn = document.query
selector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }...
AbortSignal - Web APIs
h request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.query
selector('.download'); var abortbtn = document.query
selector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }...
Ambient Light Events - Web APIs
ing the addeventlistener method (using the devicelight event name) or by attaching an event handler to the window.ondevicelight property. once captured, the event object gives access to the light intensity expressed in lux through the devicelightevent.value property. ...
Animation.commitStyles() - Web APIs
api's animation interface commits the end styling state of an animation to the element being animated, even after that animation has been removed. it will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. syntax animation.commitstyles(); parameters none. return value none. examples const divelem = document.query
selector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); }); specifications specification status comment web animationsthe definition of 'commitstyles()' in that specification. working draft ...
Animation.onremove - Web APIs
event is sent when the animation is removed (i.e., put into an active replace state). syntax var removehandler = animation.onremove; animation.onremove = removehandler; value a function to be called to handle the remove event, or null if no remove event handler is set. ...
Animation.persist() - Web APIs
t() method of the web animations api's animation interface explicitly persists an animation, when it would otherwise be removed due to the browser's automatically removing filling animations behavior. syntax animation.persist(); parameters none. return value none. ...
Animation.replaceState - Web APIs
tion's replace state; when the animation has been removed by the browser's automatically removing filling animations behavior. persisted: the animation has been explicitly persisted by invoking animation.persist() on it. removed: the animation has been explicitly removed. ...
Attr.localName - Web APIs
name of an attribute. in previous dom specifications this api was defined within the node interface. syntax name = attribute.localname return value a domstring representing the local part of the attribute's qualified name. example the following example shows "id" in an alert dialog. html content <button id="example">click me</button> javascript content const element = document.query
selector("#example"); element.addeventlistener("click", function() { const attribute = element.attributes[0]; alert(attribute.localname); }); notes the local name of an attribute is the part of the attribute's qualified name that comes after the colon. qualified names are typically used in xml as part of the namespace(s) of the particular xml documents. note: in gecko 1.9.2 and earlier, the pro...
AudioListener.dopplerFactor - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.forwardX - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.forwardY - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.forwardZ - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.positionX - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.positionY - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.positionZ - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.setOrientation() - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.setPosition() - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.speedOfSound - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.upX - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.upY - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener.upZ - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioListener - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
AudioParam.setValueAtTime() - Web APIs
ttons are pressed, the currgain variable is incremented/decremented by 0.25, then the setvalueattime() method is used to set the gain value equal to currgain, one second from now (audioctx.currenttime + 1.) // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.query
selector('audio'); var pre = document.query
selector('pre'); var myscript = document.query
selector('script'); pre.innerhtml = myscript.innerhtml; var targetattimeplus = document.query
selector('.set-target-at-time-plus'); var targetattimeminus = document.query
selector('.set-target-at-time-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmed...
AudioParam.setValueCurveAtTime() - Web APIs
ebaudio-examples repo for the source code, or view the example live.) when this button is pressed, setvaluecurveattime() is used to change the gain value between the values contained in the wavearray array: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.query
selector('audio'); var pre = document.query
selector('pre'); var myscript = document.query
selector('script'); pre.innerhtml = myscript.innerhtml; var valuecurve = document.query
selector('.value-curve'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = ...
AudioTrack - Web APIs
ns null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source. usage notes to get an audiotrack for a given media element, use the element's audiotracks property, which returns an audiotracklist object from which you can get the individual tracks contained in the media: var el = document.query
selector("video"); var tracks = el.audiotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach(). this first example gets the first audio track on the media: var firsttrack = tracks[0]; the next example scans through all of the media's audio tracks, enabling any that are in the user's preferred language (taken from a variable userlanguage) and...
AudioTrackList: addtrack event - Web APIs
the addtrack event is fired when a track is added to an audiotracklist. bubbles no cancelable no interface trackevent event handler property onaddtrack examples using addeventlistener(): const videoelement = document.query
selector('video'); videoelement.audiotracks.addeventlistener('addtrack', (event) => { console.log(`audio track: ${event.track.label} added`); }); using the onaddtrack event handler property: const videoelement = document.query
selector('video'); videoelement.audiotracks.onaddtrack = (event) => { console.log(`audio track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification. living standard ...
AudioTrackList.length - Web APIs
indicates that there are no audio tracks in the media. syntax var trackcount = audiotracklist.length; value a number indicating how many audio tracks are included in the audiotracklist. each track can be accessed by treating the audiotracklist as an array of objects of type audiotrack. example this snippet gets the number of audio tracks in the first <video> element found in the dom by query
selector(). var videoelem = document.query
selector("video"); var numaudiotracks = 0; if (videoelem.audiotracks) { numaudiotracks = videoelem.audiotracks.length; } note that this sample checks to be sure htmlmediaelement.audiotracks is defined, to avoid failing on browsers without support for audiotrack. specifications specification status comment html living standardthe...
AudioTrackList.onaddtrack - Web APIs
d to the element; one addtrack event will occur for each audio track in the media resource. example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the audiotrack object representing the newly-added track. in this scenario, that function's role is to add the new track to a list of audio tracks available to choose from. document.query
selector("video").audiotracks.onaddtrack = function(event) { addtotracklist(event.track); }; specifications specification status comment html living standardthe definition of 'audiotracklist.onaddtrack' in that specification. living standard html5the definition of 'audiotracklist.onaddtrack' in that specification. recommendation ...
AudioTrackList.onchange - Web APIs
nchange = eventhandler; value set onchange to a function that should be called whenever tracks are enabled or disabled on the media element. example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. ...
AudioTrackList.onremovetrack - Web APIs
syntax audiotracklist.onremovetrack = eventhandler; value set onremovetrack to a function that accepts as input a trackevent object which indicates in its track property which audio track has been removed from the media element. example this simple example just fetches the current number of audio tracks in the media element whenever a track is removed from the media element. document.query
selector("my-video").audiotracks.onremovetrack = function(event) { mytrackcount = document.query
selector("my-video").audiotracks.length; }; the current number of audio tracks remaining in the media element is obtained from audiotracklist property length. specifications specification status comment html living standardthe definition of 'audiotracklist.onremovetrack' in tha...
AudioTrackList: removetrack event - Web APIs
the removetrack event is fired when a track is removed from an audiotracklist. bubbles no cancelable no interface trackevent event handler property onremovetrack examples using addeventlistener(): const videoelement = document.query
selector('video'); videoelement.audiotracks.addeventlistener('removetrack', (event) => { console.log(`audio track: ${event.track.label} removed`); }); using the onremovetrack event handler property: const videoelement = document.query
selector('video'); videoelement.audiotracks.onremovetrack = (event) => { console.log(`audio track: ${event.track.label} removed`); }; specifications specification status html living standardthe definition of 'removetrack' in that specification. livi...
AudioTrackList - Web APIs
ement, audiotracklist lets you set event handlers on the addtrack and removetrack events, so that you can detect when tracks are added to or removed from the media element's stream. see onaddtrack and onremovetrack for details and examples. examples getting a media element's audio track list to get a media element's audiotracklist, use its audiotracks property. var audiotracks = document.query
selector("video").audiotracks; monitoring track count changes in this example, we have an app that displays information about the number of channels available. to keep it up to date, handlers for the addtrack and removetrack events are set up. audiotracks.onaddtrack = updatetrackcount; audiotracks.onremovetrack = updatetrackcount; function updatetrackcount(event) { trackcount = audiotracks.length; ...
BaseAudioContext.createPanner() - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
BaseAudioContext.decodeAudioData() - Web APIs
to loop. the buttons in the example simply run getdata() to load the track and start it playing, and stop it playing, respectively. when the stop() method is called on the source, the source is cleared out. note: you can run the example live (or view the source.) // define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var source; var pre = document.query
selector('pre'); var myscript = document.query
selector('script'); var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); // use xhr to load an audio track, and // decodeaudiodata to decode it and stick it in a buffer. // then we put the buffer into the source function getdata() { source = audioctx.createbuffersource(); var request = new xmlhttprequest(); request.o...
BatteryManager.charging - Web APIs
on return, charging indicates whether or not the battery, which is a batterymanager object, is currently being charged; if the battery is charging, this value is true. otherwise, the value is false. ...
BatteryManager.chargingTime - Web APIs
time in seconds until the battery, which is a batterymanager object, is fully charged, or 0 if the battery is already fully charged. if the battery is currently discharging, this value is infinity. ...
BatteryManager.dischargingTime - Web APIs
ged and the system will suspend. this value is infinity if the battery is currently charging rather than discharging, or if the system is unable to report the remaining discharging time. ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput = new float32array(5); var phaseresponseoutput = new float32array(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>biquad filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.query
selector('.freq-response-output'); finally, after creating our biquad filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.valu...
Body.blob() - Web APIs
th a blob. example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. var myimage = document.query
selector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest) .then(response => response.blob()) .then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'blob()' in that specification. living standard ...
Body.bodyUsed - Web APIs
hat url as the source of an <img> element to display the image. notice that we log response.bodyused to the console once before the response.blob() call and once after. this returns false before and true afterwards, as at that point the body has been read. ...
Body.json() - Web APIs
y, a string, a number... example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file. when the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. ...
Body - Web APIs
examples the example below uses a simple fetch call to grab an image and display it in an <img> tag. you'll notice that since we are requesting an image, we need to run body.blob() (response implements body) to give the response its correct mime type. html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content const myimage = document.query
selector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg') .then(res => res.blob()) .then(res => { const objecturl = url.createobjecturl(res); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'body' in that specification. living standard ...
BroadcastChannel: message event - Web APIs
1px solid black; padding: .5rem; height: 150px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } textarea { padding: .2rem; } label, br { margin: .5rem 0; } button { vertical-align: top; height: 1.5rem; } const channel = new broadcastchannel('example-channel'); const messagecontrol = document.query
selector('#message'); const broadcastmessagebutton = document.query
selector('#broadcast-message'); broadcastmessagebutton.addeventlistener('click', () => { channel.postmessage(messagecontrol.value); }) receiver 1 <h1>receiver 1</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "fira sans", sans-serif; } h1 { font: 1.6e...
CSS - Web APIs
ods no inherited static methods. css.registerproperty() registers custom properties, allowing for property type checking, default values, and properties that do or do not inherit their value. css.supports() returns a boolean indicating if the pair property-value, or the condition, given in parameter is supported. css.escape() can be used to escape a string mostly for use as part of a css
selector. css factory functions can be used to return a new cssunitvalue with a value of the parameter number of the units of the name of the factory function method used. css.em(3) // cssunitvalue {value: 3, unit: "em"} specifications specification status comment css painting api level 1the definition of 'paintworklet' in that specification. working draft adds ...
CSSImageValue - Web APIs
e add some css, including a background image requesting a binary file: button { display: inline-block; min-height: 100px; min-width: 100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } we get the element's style map. ...
CSSMathSum - Web APIs
ssnumericarray object which contains one or more cssnumericvalue objects. event handlers no methods none. examples we create an element with a width determined using a calc() function, then console.log() the operator and values, and dig into the values a bit. ...
CSSMathValue.operator - Web APIs
ssmathclamp "clamp" cssmathnegate "negate" cssmathinvert "invert" examples we create an element with a width determined using a calc() function, then console.log() the operator. ...
CSSMathValue - Web APIs
properties cssmathvalue.operator indicates the operator that the current subtype represents. event handlers no methods none. examples we create an element with a width determined using a calc() function, then console.log() the operator. <div>has width</div> we assign a width with a calculation div { width: calc(30% - 20px); } we add the javascript const stylemap = document.query
selector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('width').values[1].value ); // -20 the cssmathvalue.operator returns 'sum' because stylemap.get('width').values[1].value ); is -20: adding a negative number. spe...
CSSPageRule - Web APIs
csspagerule is an interface representing a single css @page rule. it implements the cssrule interface with a type value of 6 (cssrule.page_rule). syntax the syntax is described using the webidl format. interface csspagerule : cssrule { attribute domstring
selectortext; readonly attribute cssstyledeclaration style; }; properties as a cssrule, csspagerule also implements the properties of this interface. it has the following specific properties: csspagerule.
selectortext represents the text of the page
selector associated with the at-rule. csspagerule.style read only returns the declaration block associated with the at-rule. methods as a cssrule, csspagerule also implements the methods of that interface. it has no specific methods. specifications specification statu...
CSSPseudoElement.element - Web APIs
nt interface returns a reference to the originating element of the pseudo-element, in other words its parent element. syntax var originatingelement = csspseudoelement.element; value an element representing the pseudo-element's originating element. ...
CSSRule.cssText - Web APIs
ement-style cssstyledeclaration.csstext. be aware that this property can no longer be set directly, as it is now specified to be functionally modify-only, and silently so. in other words, attempting to set it does absolutely nothing, and doesn't even omit a warning or error. furthermore, it has no settable sub-properties. therefore, to modify it, use the stylesheet's cssrules[index] properties .
selectortext and .style (or its sub-properties). see using dynamic styling information for details. syntax string = cssrule.csstext example <style> body { background-color: darkblue; } </style> <script> var stylesheet = document.stylesheets[0]; alert(stylesheet.cssrules[0].csstext); // body { background-color: darkblue; } </script> specifications specification status co...
CSSRule - Web APIs
ifies integer constants that can be used in conjunction with a cssrule's type property to discern the rule type (and therefore, which specialized interface it implements). the relationships between these constants and the interfaces are: type value rule-specific interface comments and examples cssrule.style_rule 1 cssstylerule the most common kind of rule:
selector { prop1: val1; prop2: val2; } cssrule.import_rule 3 cssimportrule an @import rule. (until the documentation is completed, see the interface definition in the mozilla source code: nsidomcssimportrule.) cssrule.media_rule 4 cssmediarule cssrule.font_face_rule 5 cssfontfacerule cssrule.page_rule 6 csspagerule cssrule...
CSSStyleDeclaration.getPropertyPriority() - Web APIs
s property. syntax var priority = style.getpropertypriority(property); parameters property is a domstring representing the property name to be checked. return value priority is a domstring that represents the priority (e.g. "important") if one exists. if none exists, returns the empty string. example the following javascript code checks whether margin is marked as important in a css
selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var isimportant = declaration.getpropertypriority('margin') === 'important'; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertypriority()' in that specification. working draft document object model (dom) level 2 sty...
CSSStyleDeclaration.getPropertyValue() - Web APIs
ing containing the value of a specified css property. syntax var value = style.getpropertyvalue(property); parameters property is a domstring representing the property name to be checked. return value value is a domstring containing the value of the property. if not set, returns the empty string. example the following javascript code queries the value of the margin property in a css
selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var value = declaration.getpropertyvalue('margin'); // "1px 2px" specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertyvalue()' in that specification. working draft document object model (dom) level 2 style specificatio...
CSSStyleDeclaration.removeProperty() - Web APIs
erty name to be removed. note that multi-word property names are hyphenated and not camel-cased. return value oldvalue is a domstring equal to the value of the css property before it was removed. exceptions domexception no_modification_allowed_err: if the property or declaration block is read only. example the following javascript code removes the background-color css property from a
selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.removeproperty()' in that specification. working draft document object model (dom) level 2 style specificationthe de...
CSSStyleRule - Web APIs
"h1,h2". cssstylerule.style read only returns the cssstyledeclaration object for the rule. cssstylerule.stylemap read only returns a stylepropertymap object which provides access to the rule's property-value pairs. specifications specification status comment css object model (cssom)the definition of 'cssstylerule' in that specification. ...
CSSStyleSheet - Web APIs
onally identical to the standard cssrules property; it returns a live cssrulelist which maintains an up-to-date list of all of the rules in the style sheet. legacy methods these methods are legacy methods first introduced by microsoft; they should not be used if they can be avoided, but are not in danger of being removed anytime soon. addrule() adds a new rule to the stylesheet given the
selector to which the style applies and the style block to apply to the matching elements. this differs from insertrule(), which simply takes the textual representation of the entire rule as a single string. removerule() functionally identical to deleterule(); removes the rule at the specified index from the stylesheet's rule list. notes in some browsers, if a stylesheet is loaded from a differen...
Using dynamic styling information - Web APIs
, and that is described in further detail below. note also that, as with individual element's dom styles, when speaking of manipulating the stylesheets, this is not actually manipulating the physical document(s), but merely the internal representation of the document. the basic style object exposes the stylesheet and the cssstylesheet interfaces. those interfaces contain members like insertrule,
selectortext, and parentstylesheet for accessing and manipulating the individual style rules that make up a css stylesheet. to get to the style objects from the document, you can use the document.stylesheets property and access the individual objects by index (e.g., document.stylesheets[0] is the first stylesheet defined for the document, etc.). modify a stylesheet rule with cssom <html> <head> <title>...
Using the CSS Painting API - Web APIs
ckground image, but this is the default size and placement of the yellow box we created in our paint worklet. we tried to keep the example simple. for more options, look at the canvas documentation. we also add a little bit of complexity later in this tutorial. using the paint worklet to use the paint worklet, we need to register it using addmodule() and include it in our css, ensuring the css
selector matches a dom node in our html registering the worklet the setup and design of our paint worklet took place in the external script shown above. we need to register that worklet from our main script. css.paintworklet.addmodule('nameofpaintworkletfile.js'); this can be done using the paint worklet's addmodule() method in a <script> within the main html or in an external javascript file linked t...
CSS Painting API - Web APIs
custom properties are accessible to the paintworklet. specifications specification status comment css painting api level 1 working draft initial definition. ...
CanvasRenderingContext2D.getTransform() - Web APIs
rm() and draw a square on it, then retrieve the matrix from it using gettransform(). we then apply the retrieved matrix directly to the second canvas context by passing the dommatrix object directly to settransform(), and draw a circle on it. ...
CanvasRenderingContext2D.setTransform() - Web APIs
matrix from it using canvasrenderingcontext2d.gettransform(). we then apply the retrieved matrix directly to the second canvas context by passing the dommatrix object directly to settransform() (i.e. the second type), and draw a circle on it. ...
Clipboard API - Web APIs
ssion must be requested, which you can do by trying to read data from the clipboard. this api is designed to supersede accessing the clipboard using document.execcommand(). accessing the clipboard instead of creating a clipboard object through instantiation, you access the system clipboard through the navigator.clipboard global: navigator.clipboard.readtext().then( cliptext => document.query
selector(".editor").innertext += cliptext); this snippet fetches the text from the clipboard and appends it to the first element found with the class editor. since readtext() (and read(), for that matter) returns an empty string if the clipboard isn't text, this code is safe. interfaces clipboard secure context provides an interface for reading and writing text and data to or from the system clipboa...
CustomElementRegistry.whenDefined() - Web APIs
displays placeholder content until the actual menu content is ready to display. <nav id="menu-container"> <div class="menu-placeholder">loading...</div> <nav-menu> <menu-item>item 1</menu-item> <menu-item>item 2</menu-item> ... <menu-item>item n</menu-item> </nav-menu> </nav> const container = document.getelementbyid('menu-container'); const placeholder = container.query
selector('.menu-placeholder'); // fetch all the children of menu that are not yet defined. const undefinedelements = container.query
selectorall(':not(:defined)'); const promises = [...undefinedelements].map( button => customelements.whendefined(button.localname) ); // wait for all the children to be upgraded, // then remove the placeholder. await promise.all(promises); container.removechild(placeholde...
DOMMatrixReadOnly.translate() - Web APIs
th="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a new, translated matrix — which is then applied to the blue square as a transform. the red square is left in place. const matrix = new dommatrixreadonly().translate(25, 25); document.query
selector('#transformed').setattribute('transform', matrix.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.translate()' in that specification. candidate recommendation initial definition ...
DOMTokenList.add() - Web APIs
nting the token (or tokens) to add to the tokenlist. return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then add a new token to the list, and write the list into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.query
selector("span"); let classes = span.classlist; classes.add("d"); span.textcontent = classes; the output looks like this: you can add multiple tokens as well: span.classlist.add("d", "e", "f"); specifications specification status comment domthe definition of 'add()' in that specification. living standard initial definition ...
DOMTokenList.contains() - Web APIs
h is true if the calling list contains token, otherwise false. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then test for the existence of "c" in the list, and write the result into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.query
selector("span"); let classes = span.classlist; let result = classes.contains("c"); if (result) { span.textcontent = "the classlist contains 'c'"; } else { span.textcontent = "the classlist does not contain 'c'"; } the output looks like this: specifications specification status comment domthe definition of 'contains()' in that specification. living standard init...
DOMTokenList.entries() - Web APIs
les in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of loop, writing them to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.query
selector("span"); let classes = span.classlist; let iterator = classes.entries(); for (let value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment domthe definition of 'entries() (as iterable<node>)' in that specification. living standard initial definition. ...
DOMTokenList.forEach() - Web APIs
callback. return value undefined. example in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the values using foreach(), writing each one to the <span>'s node.textcontent inside the foreach() inner function. ...
DOMTokenList.item() - Web APIs
ter than or equal to the length of the list. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then retrieve the last item in the list using item(tokenlist.length - 1), and write it into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.query
selector("span"); let classes = span.classlist; let item = classes.item(classes.length-1); span.textcontent = item; the output looks like this: specifications specification status comment domthe definition of 'item()' in that specification. living standard initial definition ...
DOMTokenList.keys() - Web APIs
xamples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ... of loop, writing each one to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: var span = document.query
selector("span"); var classes = span.classlist; var iterator = classes.keys(); for(var value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment domthe definition of 'keys() (as iterable<node>)' in that specification. living standard initial definition ...
DOMTokenList.length - Web APIs
epresenting the number of objects stored in the object. syntax tokenlist.length; value an integer. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the length of the list to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.query
selector("span"); let classes = span.classlist; let length = classes.length; span.textcontent = `classlist length = ${length}`; the output looks like this: specifications specification status comment domthe definition of 'length' in that specification. living standard initial definition ...
DOMTokenList.remove() - Web APIs
the list, no error is thrown, and nothing happens. return value undefined examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then remove a token from the list, and write the list into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.query
selector("span"); let classes = span.classlist; classes.remove("c"); span.textcontent = classes; the output looks like this: to remove multiple classes at once, you can supply multiple tokens. the order you supply the tokens doesn't have to match the order they appear in the list: let span2 = document.getelementsbytagname("span")[0] let classes2 = span.classlist; classes2.remove("c", "b"); span2.te...
DOMTokenList.replace() - Web APIs
replaced, or false if not. note: in older browsers, replace() returns void. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then replace a token in the list, and write the list into the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.query
selector("span"); let classes = span.classlist; let result = classes.replace("c", "z"); console.log(result); if (result) { span.textcontent = classes; } else { span.textcontent = 'token not replaced successfully'; } the output looks like this: polyfill the following polyfill will add the replace method to the domtokenlist class. the following code will only work with ie10-11. to use with earli...
DOMTokenList.toggle() - Web APIs
oolean indicating whether token is in the list after the call. examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we then replace a token in the list, and write the list into the <span>'s node.textcontent. ...
DOMTokenList.value - Web APIs
omstring, or clears and sets the list to the given value. syntax tokenlist.value; value a domstring examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the value of the list to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: let span = document.query
selector("span"); let classes = span.classlist; span.textcontent = classes.value; the output looks like this: specifications specification status comment domthe definition of 'value' in that specification. living standard initial definition ...
DOMTokenList.values() - Web APIs
les in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist. we when retrieve an iterator containing the values using values(), then iterate through those values using a for ... of loop, writing each one to the <span>'s node.textcontent. first, the html: <span class="a b c"></span> now the javascript: var span = document.query
selector("span"); var classes = span.classlist; var iterator = classes.values(); for(var value of iterator) { span.textcontent += value + ' ++ '; } the output looks like this: specifications specification status comment domthe definition of 'values() (as iterable<node>)' in that specification. living standard initial definition ...
DeprecationReportBody - Web APIs
nside the constructor: observer.observe(); because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details. ...
Detecting device orientation - Web APIs
, it's a tiny one), and the ball is in the center: .garden { position: relative; width : 200px; height: 200px; border: 5px solid #ccc; border-radius: 10px; } .ball { position: absolute; top : 90px; left : 90px; width : 20px; height: 20px; background: green; border-radius: 100%; } now, if we move our device, the ball will move accordingly: var ball = document.query
selector('.ball'); var garden = document.query
selector('.garden'); var output = document.query
selector('.output'); var maxx = garden.clientwidth - ball.clientwidth; var maxy = garden.clientheight - ball.clientheight; function handleorientation(event) { var x = event.beta; // in degree in the range [-180,180] var y = event.gamma; // in degree in the range [-90,90] output.innerhtml = "beta : " +...
Document: DOMContentLoaded event - Web APIs
-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } js const log = document.query
selector('.event-log-contents'); const reload = document.query
selector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('readystatechange', (event) => { log.textcontent =...
Document.alinkColor - Web APIs
useup events. syntax var color = document.alinkcolor; document.alinkcolor = color; color is a string containing the name of the color (e.g., blue, darkblue, etc.) or the hexadecimal value of the color (e.g., #0000ff) notes the default value for this property in mozilla firefox is red (#ee0000 in hexadecimal). document.alinkcolor is deprecated in dom level 2 html. one alternative is the css
selector :active. another alternative is document.body.alink, although this is deprecated in html 4.01 in favor of the css alternative. gecko supports both alinkcolor/:active and :focus. internet explorer 6 and 7 support alinkcolor/:active only for html anchor (<a>) links and the behavior is the same as :focus under gecko. there is no support for :focus in ie. ...
Document.evaluate() - Web APIs
var thisheading = headings.iteratenext(); var alerttext = "level 2 headings in this document are:\n"; while (thisheading) { alerttext += thisheading.textcontent + "\n"; thisheading = headings.iteratenext(); } alert(alerttext); // alerts the text of all h2 elements note, in the above example, a more verbose xpath is preferred over common shortcuts such as //h2. generally, more specific xpath
selectors as in the above example usually gives a significant performance improvement, especially on very large documents. this is because the evaluation of the query spends does not waste time visiting unnecessary nodes. using // is generally slow as it visits every node from the root and all subnodes looking for possible matches. further optimization can be achieved by careful use of the context parame...
Document: fullscreenerror event - Web APIs
event handler property onfullscreenerror as with the fullscreenchange event, two fullscreenerror events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which owns that element. ...
Document.hasFocus() - Web APIs
document has focus. example this example checks whether the document has focus every 300 milliseconds. to test the functionality of hasfocus(), click on the button to open a new window, and try switching between the two pages. ...
Document.head - Web APIs
nly property of the document interface returns the <head> element of the current document. syntax var objref = document.head; value an htmlheadelement. example <!doctype html> <head id="my-document-head"> <title>example: using document.head</title> </head> <script> var thehead = document.head; console.log(thehead.id); // "my-document-head"; console.log( thehead === document.query
selector("head") ); // true </script> notes document.head is read-only. trying to assign a value to this property will fail silently or, in strict mode, throws a typeerror . specifications specification status comment html 5.1the definition of 'document.head' in that specification. recommendation html5the definition of 'document.head' in that specification...
Document.importNode() - Web APIs
evelopers not to omit the argument. starting with gecko 29.0 (firefox 29 / thunderbird 29 / seamonkey 2.26)), a shallow clone is defaulted instead of a deep clone. return value the copied importednode in the scope of the importing document. note: importednode's node.parentnode is null, since it has not yet been inserted into the document tree! example const iframe = document.query
selector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const newnode = document.importnode(oldnode, true); document.getelementbyid("container").appendchild(newnode); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode(). best practi...
Document: readystatechange event - Web APIs
-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } js const log = document.query
selector('.event-log-contents'); const reload = document.query
selector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('readystatechange', (event) => { log.textcontent =...
Document - Web APIs
ccess was denied. document.routeevent() obsolete since gecko 24 see window.routeevent(). document.mozsetimageelement() allows you to change the element being used as the background image for a specified element id. the document interface is extended with the parentnode interface: document.getelementbyid(string id) returns an object reference to the identified element. document.query
selector() returns the first element node within the document, in document order, that matches the specified
selectors. document.query
selectorall() returns a list of all the element nodes within the document that match the specified
selectors. the document interface is extended with the xpathevaluator interface: document.createexpression() compiles an xpathexpression which can then be used for (r...
DocumentTimeline.DocumentTimeline() - Web APIs
r of milliseconds relative to the navigationstart moment of the active document for the current browsing context. examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
DocumentTimeline - Web APIs
mationtimeline.currenttime returns the time value in milliseconds for this timeline or null if it is inactive. examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline. ...
Element: click event - Web APIs
t must have an href) <area> (but it must have an href) <button> <img> <input> <label> (but it must be associated with a form control) <textarea> this list is incomplete; you can help mdn by doing further testing/research and expanding it. examples this example displays the number of consecutive clicks on a <button>. html <button>click</button> javascript const button = document.query
selector('button'); button.addeventlistener('click', event => { button.innerhtml = `click count: ${event.detail}`; }); result try making rapid, repeated clicks on the button to increase the click count. if you take a break between clicks, the count will reset. specifications specification status ui events working draft document object model (dom) level 3 events sp...
Element: select event - Web APIs
text"> and <textarea> elements. examples selection logger <input value="try selecting some text in this element."> <p id="log"></p> function logselection(event) { const log = document.getelementbyid('log'); const selection = event.target.value.substring(event.target.selectionstart, event.target.selectionend); log.textcontent = `you selected: ${selection}`; } const input = document.query
selector('input'); input.addeventlistener('select', logselection); onselect equivalent you can also set up the event handler using the onselect property: input.onselect = logselection; specifications specification status ui eventsthe definition of 'select' in that specification. working draft ...
Element.setAttribute() - Web APIs
ng "null". if you wish to remove an attribute, call removeattribute(). return value undefined. exceptions invalidcharactererror the specified attribute name contains one or more characters which are not valid in attribute names. example in the following example, setattribute() is used to set attributes on a <button>. html <button>hello world</button> javascript var b = document.query
selector("button"); b.setattribute("name", "hellobutton"); b.setattribute("disabled", ""); this demonstrates two things: the first call to setattribute() above shows changing the name attribute's value to "hellobutton". you can see this using your browser's page inspector (chrome, edge, firefox, safari). to set the value of a boolean attribute, such as disabled, you can specify any value. an empty ...
Element.slot - Web APIs
ted by a slotable element by including it inside the element with a slot attribute with the value my-text. here is one such example: <my-paragraph> <span slot="my-text">let's have some different text!</span> </my-paragraph> in our javascript file we get a reference to the <span> shown above, then log a reference to the name of the corresponding <slot> element. let slottedspan = document.query
selector('my-paragraph span') console.log(slottedspan.slot); // logs 'my-text' specifications specification status comment domthe definition of 'slot' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/...
Event.composed - Web APIs
the composed property returns true beause the click event is always able to propagate across shadow boundaries. you'll notice a difference in the value of composedpath for the...
Event.composedPath() - Web APIs
first, the composed property returns true beause the click event is always able to propagate across shadow boundaries. second, you'll notice a difference in the value of composedp...
Event.preventDefault() - Web APIs
ow, calling preventdefault() for a non-cancelable event, such as one dispatched via eventtarget.dispatchevent(), without specifying cancelable: true has no effect. syntax event.preventdefault(); examples blocking default click handling toggling a checkbox is the default action of clicking on a checkbox. ...
EventSource() - Web APIs
rameters url a usvstring that represents the location of the remote resource serving the events/messages. configuration optional provides options to configure the new connection. the possible entries are: withcredentials, defaulting to false, indicating if cors should be set to include credentials. examples var evtsource = new eventsource('sse.php'); var eventlist = document.query
selector('ul'); evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'eventsource()' in that spe...
EventSource.close() - Web APIs
the close() method of the eventsource interface closes the connection, if one is made, and sets the eventsource.readystate attribute to 2 (closed). note: if the connection is already closed, the method does nothing. syntax eventsource.close(); parameters none. return value void. examples var button = document.query
selector('button'); var evtsource = new eventsource('sse.php'); button.onclick = function() { console.log('connection closed'); evtsource.close(); } note: you can find a full example on github — see simple sse demo using php. specifications specification status comment html living standardthe definition of 'close()' in that specification. living standard initial definition ...
EventSource: message event - Web APIs
nt source. bubbles no cancelable no interface messageevent event handler property eventsource.onmessage examples in this basic example, an eventsource is created to receive events from the server; a page with the name sse.php is responsible for generating the events. ...
EventSource - Web APIs
source has opened. additionally, the event source itself may send messages with an event field, which will create ad-hoc events keyed to that value. examples in this basic example, an eventsource is created to receive unnamed events from the server; a page with the name sse.php is responsible for generating the events. var evtsource = new eventsource('sse.php'); var eventlist = document.query
selector('ul'); evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } each received event causes our eventsource object's onmessage event handler to be run. it, in turn, creates a new <li> element and writes the message's data into it, then appends the new element to the list element a...
EventTarget.addEventListener() - Web APIs
> </div> css .outer, .middle, .inner1, .inner2 { display: block; width: 520px; padding: 15px; margin: 15px; text-decoration: none; } .outer { border: 1px solid red; color: red; } .middle { border: 1px solid green; color: green; width: 460px; } .inner1, .inner2 { border: 1px solid purple; color: purple; width: 400px; } javascript const outer = document.query
selector('.outer'); const middle = document.query
selector('.middle'); const inner1 = document.query
selector('.inner1'); const inner2 = document.query
selector('.inner2'); const capture = { capture : true }; const nonecapture = { capture : false }; const once = { once : true }; const noneonce = { once : false }; const passive = { passive : true }; const nonepassive = { passive : false }; outer...
EventTarget.removeEventListener() - Web APIs
istener will not be invoked for the event it was registered for after being removed. however, it can be reattached. calling removeeventlistener() with arguments that do not identify any currently registered eventlistener on the eventtarget has no effect. example this example shows how to add a mouseover-based event listener that removes a click-based event listener. ...
File.lastModified - Web APIs
file as the number of milliseconds since the unix epoch (january 1, 1970 at midnight). files without a known last modified date return the current date. syntax const time = instanceoffile.lastmodified; value a number that represents the number of milliseconds since the unix epoch. ...
FileReader: abort event - Web APIs
order: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.query
selector('input[type="file"]'); const preview = document.query
selector('img.preview'); const eventlog = document.query
selector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function ...
FileReader: load event - Web APIs
order: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.query
selector('input[type="file"]'); const preview = document.query
selector('img.preview'); const eventlog = document.query
selector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function ...
FileReader: loadend event - Web APIs
order: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.query
selector('input[type="file"]'); const preview = document.query
selector('img.preview'); const eventlog = document.query
selector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function ...
FileReader: loadstart event - Web APIs
order: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.query
selector('input[type="file"]'); const preview = document.query
selector('img.preview'); const eventlog = document.query
selector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function ...
FileReader: progress event - Web APIs
order: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.query
selector('input[type="file"]'); const preview = document.query
selector('img.preview'); const eventlog = document.query
selector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function ...
FileReader.result - Web APIs
) the result is text in a string. example this example presents a function, read(), which reads a file from a file input. it works by creating a filereader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read(). the content is handled as raw text data. var fileinput = document.query
selector('input[type="file"]'); function read(callback) { var file = fileinput.files.item(0); var reader = new filereader(); reader.onload = function() { callback(reader.result); } reader.readastext(file); } specifications specification status comment file apithe definition of 'result' in that specification. working draft initial definition ...
FileRequest.onprogress - Web APIs
gets an object as its first parameter. those objects contain two properties: loaded a number representing the current amount of bytes processed by the operation. total a number representing the total amount of bytes that will be processed by the operation. example // assuming 'request' which is a filerequest object request.onprogress = function (status) { var progress = document.query
selector('progress'); progress.value = status.loaded; progress.max = status.total; } specification not part of any current specification. ...
FileHandle API - Web APIs
erface return a filerequest object. such an object is basically a domrequest with an extra power: it allows to monitor the progress of an operation. sometimes writing and reading operations can be very long, therefore it is a good idea to monitor the operation to provide feedback to the user. such monitoring can be done using the filerequest.onprogress event handler. ...
FormDataEvent.formData - Web APIs
the formdata read only property of the formdataevent interface contains the formdata object representing the data contained in the form when the event was fired. syntax formdata = formdataevent.formdata returns a formdata object. ...
FormDataEvent - Web APIs
nstructor formdataevent() creates a new formdataevent object instance. properties inherits properties from its parent interface, event. formdataevent.formdata contains the formdata object representing the data contained in the form when the event was fired. methods inherits methods from its parent interface, event. ...
GainNode - Web APIs
e audio when a mute button is clicked by changing the gain property value. ...
GlobalEventHandlers.onblur - Web APIs
s focus. note: the opposite of onblur is onfocus. syntax target.onblur = functionref; value functionref is a function name or a function expression. the function receives a focusevent object as its sole argument. example this example uses onblur and onfocus to change the text within an <input> element. html <input type="text" value="click here"> javascript let input = document.query
selector('input'); input.onblur = inputblur; input.onfocus = inputfocus; function inputblur() { input.value = 'focus has been lost'; } function inputfocus() { input.value = 'focus is here'; } result try clicking in and out of the form field, and watch its contents change accordingly. specifications specification status comment html living standardthe definition of 'onb...
GlobalEventHandlers.onchange - Web APIs
name or a function expression. the function receives an event object as its sole argument. example this example logs the number of characters in an <input> element, every time you modify its contents and then change focus away from it. html <input type="text" placeholder="type something here, then click outside of the field." size="50"> <p id="log"></p> javascript let input = document.query
selector('input'); let log = document.getelementbyid('log'); input.onchange = handlechange; function handlechange(e) { log.textcontent = `the field's value is ${e.target.value.length} character(s) long.`; } result specification specification status comment html living standardthe definition of 'onchange' in that specification. living standard ...
GlobalEventHandlers.onfocus - Web APIs
tails). note: the opposite of onfocus is onblur. syntax target.onfocus = functionref; value functionref is a function name or a function expression. the function receives a focusevent object as its sole argument. example this example uses onblur and onfocus to change the text within an <input> element. html <input type="text" value="click here"> javascript let input = document.query
selector('input'); input.onblur = inputblur; input.onfocus = inputfocus; function inputblur() { input.value = 'focus has been lost'; } function inputfocus() { input.value = 'focus is here'; } result try clicking in and out of the form field, and watch its contents change accordingly. specifications specification status comment html living standardthe definition of 'onf...
GlobalEventHandlers.onformdata - Web APIs
is happens when the form is submitted, but can also be triggered by the invocation of a formdata() constructor. onformdata is available on htmlformelement. syntax target.onformdata = functionref; value functionref is a function name or a function expression. the function receives a formdataevent object as its sole argument. ...
GlobalEventHandlers.oninput - Web APIs
unctionref; value functionref is a function name or a function expression. the function receives an inputevent object as its sole argument. example this example logs the number of characters in an <input> element, every time you modify its contents. html <input type="text" placeholder="type something here to see its length." size="50"> <p id="log"></p> javascript let input = document.query
selector('input'); let log = document.getelementbyid('log'); input.oninput = handleinput; function handleinput(e) { log.textcontent = `the field's value is ${e.target.value.length} character(s) long.`; } result specifications specification status comment html living standardthe definition of 'oninput' in that specification. living standard initial definitio...
GlobalEventHandlers.onkeydown - Web APIs
when the user presses a keyboard key. syntax target.onkeydown = functionref; value functionref is a function name or a function expression. the function receives a keyboardevent object as its sole argument. example this example logs the keyboardevent.code value whenever you press down a key inside the <input> element. html <input> <p id="log"></p> javascript const input = document.query
selector('input'); const log = document.getelementbyid('log'); input.onkeydown = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result specifications specification status comment html living standardthe definition of 'onkeydown' in that specification. living standard ...
GlobalEventHandlers.onkeyup - Web APIs
releases a key that was previously pressed. syntax target.onkeyup = functionref; value functionref is a function name or a function expression. the function receives a keyboardevent object as its sole argument. example this example logs the keyboardevent.code value whenever you release a key inside the <input> element. html <input> <p id="log"></p> javascript const input = document.query
selector('input'); const log = document.getelementbyid('log'); input.onkeyup = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result specifications specification status comment html living standardthe definition of 'onkeyup' in that specification. living standard ...
GlobalEventHandlers.onmouseout - Web APIs
n the mouse leaves an element. for example, when the mouse moves off of an image in the web page, the mouseout event is raised for that image element. syntax element.onmouseout = function; example this example adds an onmouseout and an onmouseover event to a paragraph. try moving your mouse over and out of the element. html <p>test your mouse on me!</p> javascript const p = document.query
selector('p'); p.onmouseover = logmouseover; p.onmouseout = logmouseout; function logmouseover() { p.innerhtml = 'mouse over detected'; } function logmouseout() { p.innerhtml = 'mouse out detected'; } result specification specification status comment html living standardthe definition of 'onmouseout' in that specification. living standard ...
GlobalEventHandlers.onmouseover - Web APIs
andlers mixin is an eventhandler that processes mouseover events. the mouseover event fires when the user moves the mouse over a particular element. syntax element.onmouseover = function; example this example adds an onmouseover and an onmouseout event to a paragraph. try moving your mouse over and out of the element. html <p>test your mouse on me!</p> javascript const p = document.query
selector('p'); p.onmouseover = logmouseover; p.onmouseout = logmouseout; function logmouseover() { p.innerhtml = 'mouse over detected'; } function logmouseout() { p.innerhtml = 'mouse out detected'; } result specifications specification status comment html living standardthe definition of 'onmouseover' in that specification. living standard ...
GlobalEventHandlers.onresize - Web APIs
ntax window.onresize = functionref; value functionref is a function name or a function expression. the function receives a focusevent object as its sole argument. examples window size logger <p>resize the browser window to fire the <code>resize</code> event.</p> <p>window height: <span id="height"></span></p> <p>window width: <span id="width"></span></p> const heightoutput = document.query
selector('#height'); const widthoutput = document.query
selector('#width'); function resize() { heightoutput.textcontent = window.innerheight; widthoutput.textcontent = window.innerwidth; } window.onresize = resize; specification specification status comment html living standardthe definition of 'onresize' in that specification. living standard ...
GlobalEventHandlers.onscroll - Web APIs
greater flexibility, you can pass a scroll event to the eventtarget.addeventlistener() method instead. example this example monitors scrolling on a <textarea>, and logs the element's vertical scroll position accordingly. html <textarea>1 2 3 4 5 6 7 8 9</textarea> <p id="log"></p> css textarea { width: 4rem; height: 8rem; font-size: 3rem; } javascript const textarea = document.query
selector('textarea'); const log = document.getelementbyid('log'); textarea.onscroll = logscroll; function logscroll(e) { log.textcontent = `scroll position: ${e.target.scrolltop}`; } result specifications specification status comment html living standardthe definition of 'onscroll' in that specification. living standard document object model (dom) level...
GlobalEventHandlers.onselect - Web APIs
lect inside a <textarea> element. html <textarea>try selecting some text in this element.</textarea> <p id="log"></p> javascript function logselection(event) { const log = document.getelementbyid('log'); const selection = event.target.value.substring(event.target.selectionstart, event.target.selectionend); log.textcontent = `you selected: ${selection}`; } const textarea = document.query
selector('textarea'); textarea.onselect = logselection; result specification specification status comment html living standardthe definition of 'onselect' in that specification. living standard ...
GlobalEventHandlers.ontransitioncancel - Web APIs
ansition: width 2s, height 2s, background-color 2s, transform 2s, color 2s; } .box:hover { background-color: #ffcccc; color: #000000; width: 200px; height: 200px; -webkit-transform: rotate(180deg); transform: rotate(180deg); } javascript next, we need to establish our event handlers to change the text content of the box when the transition begins and ends. ...
GlobalEventHandlers.ontransitionend - Web APIs
helvetica", "arial", sans-serif; transition: width 2s, height 2s, background-color 2s, transform 2s, color 2s; } .box:hover { background-color: #ffcccc; color: #000000; width: 200px; height: 200px; transform: rotate(180deg); } javascript next, we need to establish our event handlers to change the text content of the box when the transition begins and ends. let box = document.query
selector(".box"); box.ontransitionrun = function(event) { box.innerhtml = "zooming..."; } box.ontransitionend = function(event) { box.innerhtml = "done!"; } result the resulting content looks like this: notice what happens when you hover your mouse cursor over the box, then move it away. specification specification status comment css transitionsthe definition of 'on...
HTMLCanvasElement.captureStream() - Web APIs
0, frames will not be captured automatically; instead, they will only be captured when the returned track's requestframe() method is called. return value a reference to a mediastream object, which has a single canvascapturemediastreamtrack in it. exceptions notsupportederror the value of framerate is negative. example // find the canvas element to capture var canvaselt = document.query
selector('canvas'); // get the stream var stream = canvaselt.capturestream(25); // 25 fps // do things to the stream // e.g. send it to another computer using an rtcpeerconnection // pc is an rtcpeerconnection created elsewhere pc.addstream(stream); specifications specification status comment media capture from dom elementsthe definition of 'htmlcanvaselement.captures...
HTMLContentElement.select - Web APIs
the htmlcontentelement.select property reflects the select attribute. it is a domstring containing a space-separated list of css
selectors that select the content to insert in place of the <content> element. syntax object.select = "css
selector css
selector ..."; example // select <h1> elements and elements with class="error" mycontentobject.select = "h1 .error"; specifications this feature is no longer defined by any standards. ...
HTMLContentElement - Web APIs
the htmlcontentelement interface represents a <content> html element, which is used in shadow dom. properties this interface inherits the properties of htmlelement. htmlcontentelement.select is a domstring that reflects the select html attribute. the value is a comma-separated list of css
selectors that select the content to insert in place of the <content> element. methods this interface inherits the methods of htmlelement. htmlcontentelement.getdistributednodes() returns a static nodelist of the distributed nodes associated with this <content> element. specifications this feature is no longer defined by any standards. ...
HTMLDetailsElement: toggle event - Web APIs
id="ch3"> <summary>chapter iii</summary> boethius falls back upon his present sense of misery. philosophy reminds him of the brilliancy of his former fortunes. </details> </section> css body { display: flex; flex-direction: row-reverse; } #log { flex-shrink: 0; padding-left: 3em; } #summaries { flex-grow: 1; } javascript function logitem(e) { const item = document.query
selector(`[data-id=${e.target.id}]`); item.toggleattribute('hidden'); } const chapters = document.query
selectorall('details'); chapters.foreach((chapter) => { chapter.addeventlistener('toggle', logitem); }); result specifications specification status comment html living standardthe definition of 'toggle event' in that specification. living standard ...
HTMLElement: beforeinput event - Web APIs
ndler property none sync / async sync composed yes default action update the dom element examples this example logs current value of the element immediately before replacing that value with the new one applied to the <input> element. html <input placeholder="enter some text" name="name"/> <p id="values"></p> javascript const input = document.query
selector('input'); const log = document.getelementbyid('values'); input.addeventlistener('beforeinput', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification status ui eventsthe definition of 'beforeinput event' in that specification. working draft ...
HTMLElement: input event - Web APIs
element changes. this is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like. examples this example logs the value whenever you change the value of the <input> element. html <input placeholder="enter some text" name="name"/> <p id="values"></p> javascript const input = document.query
selector('input'); const log = document.getelementbyid('values'); input.addeventlistener('input', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification status html living standardthe definition of 'input event' in that specification. living standard document object model (dom) level 3 events specificati...
HTMLFormElement.requestSubmit() - Web APIs
to send the request using requestsubmit() if it's available. if a submit button with the id main-submit is found, that's used to submit the form. otherwise, the form is submitted with no submitter parameter, so it's submitted directly by the form itself. if, on the other hand, requestsubmit() isn't available, this code falls back to calling the form's submit() method. let myform = document.query
selector("form"); let submitbutton = myform.query
selector("#main-submit"); if (myform.requestsubmit) { if (submitbutton) { myform.requestsubmit(submitbutton); } else { myform.requestsubmit(); } } else { myform.submit(); } specifications specification status comment html living standardthe definition of 'requestsubmit()' in that specification. living stand...
HTMLFormElement - Web APIs
entry list representing the form's data is constructed. also available via the onformdata property. reset the reset event fires when a form is reset. also available via the onreset property. submit the submit event fires when a form is submitted. also available via the onsubmit property. usage notes obtaining a form element object to obtain an htmlformelement object, you can use a css
selector with query
selector(), or you can get a list of all of the forms in the document using its forms property. document.forms returns an array of htmlformelement objects listing each of the forms on the page. you can then use any of the following syntaxes to get an individual form: document.forms[index] returns the form at the specified index into the array of forms. document.forms[id] returns ...
HTMLImageElement.crossOrigin - Web APIs
image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads. javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a newly-created image. ...
HTMLImageElement.currentSrc - Web APIs
image should be drawn at 50% of the document width if the viewport is under 400px wide; otherwise, the image is drawn at 90% width of the document. html <img src="/files/16797/clock-demo-400px.png" alt="clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 50%, 90%"> javascript var clockimage = document.query
selector("img"); let p = document.createelement("p"); if (!clockimage.currentsrc.endswith("200px.png")) { p.innertext = "using the 200px image."; } else { p.innertext = "using the 400px image!"; } document.body.appendchild(p); result specifications specification status comment html living standardthe definition of 'htmlimageelement.currentsrc' in that specification. ...
HTMLImageElement.height - Web APIs
e to update)</p> <img src="/files/17373/clock-demo-200px.png" alt="clock" srcset="/files/17373/clock-demo-200px.png 200w, /files/17374/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 300px"> javascript the javascript code looks at the height to determine the height of the image given the width at which it's currently drawn. var clockimage = document.query
selector("img"); let output = document.query
selector(".size"); const updateheight = event => { output.innertext = clockimage.height; }; window.addeventlistener("load", updateheight); window.addeventlistener("resize", updateheight); result this example may be easier to try out in its own window. specifications specification status comment html living standardthe definit...
HTMLImageElement.loading - Web APIs
concerting or offputting at best and can cause users to click the wrong thing at worst, depending on the exact timing of the deferred loads and reflows. example the addimagetolist() function shown below adds a photo thumbnail to a list of items, using lazy-loading to avoid loading the image from the network until it's actually needed. ...
HTMLImageElement.sizes - Web APIs
ax-width: 100%; border: 1px solid #888; box-shadow: 0 0.5em 0.3em #888; margin-bottom: 1.25em; } javascript the javascript code handles the two buttons that let you toggle the third width option between 40em and 50em; this is done by handling the click event, using the javascript string object method replace() to replace the relevant portion of the sizes string. let image = document.query
selector("article img"); let break40 = document.getelementbyid("break40"); let break50 = document.getelementbyid("break50"); break40.addeventlistener("click", event => image.sizes = image.sizes.replace(/50em,/, "40em,")); break50.addeventlistener("click", event => image.sizes = image.sizes.replace(/40em,/, "50em,")); result this result may be viewed in its own window here. specifications ...
HTMLImageElement.srcset - Web APIs
the string the wrap must occur. .box { width: 200px; border: 2px solid rgba(150, 150, 150, 255); padding: 0.5em; word-break: break-all; } .box img { width: 200px; } javascript the following code is run within a handler for the window's load event. it uses the image's currentsrc property to fetch and display the url selected by the browser from the srcset. let box = document.query
selector(".box"); let image = box.query
selector("img"); let newelem = document.createelement("p"); newelem.innerhtml = `image: <code>${image.currentsrc}</code>`; box.appendchild(newelem); result in the displayed output below, the selected url will correspond with whether your display results in selecting the 1x or the 2x version of the image. if you happen to have both standard and high density displa...
HTMLImageElement.width - Web APIs
"clock" srcset="/files/16864/clock-demo-200px.png 200w, /files/16797/clock-demo-400px.png 400w" sizes="(max-width: 400px) 200px, 400px"> javascript the javascript code looks at the width to determine the width of the image at the moment. this is done in the window's load and resize event handlers, in order to always provide this information. var clockimage = document.query
selector("img"); let output = document.query
selector(".size"); const updatewidth = event => { output.innertext = clockimage.width; }; window.addeventlistener("load", updatewidth); window.addeventlistener("resize", updatewidth); result this example may be easier to try out in its own window. specifications specification status comment html living standardthe definition ...
HTMLInputElement: invalid event - Web APIs
invalid element. in this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged. html <form action="#"> <ul> <li><label>enter an integer between 1 and 10: <input type="number" min="1" max="10" required></label></li> <li><input type="submit" value="submit"></li> </ul> </form><p id="log"></p> javascript const input = document.query
selector('input') const log = document.getelementbyid('log') input.addeventlistener('invalid', logvalue) function logvalue(e) { log.textcontent += e.target.value } result specifications specification status comment html living standardthe definition of 'invalid event' in that specification. living standard html 5.1the definition of 'invalid event' in th...
HTMLInputElement: search event - Web APIs
e the most recent keystroke (with new keystrokes resetting the timeout so the firing of the event is debounced). current ua implementations of <input type="search"> have an additional control to clear the field. using this control also fires the search event. in that case the value of the <input> element will be the empty string. examples // addeventlistener version const input = document.query
selector('input[type="search"]'); input.addeventlistener('search', () => { console.log("the term searched for was " + input.value); }) // onsearch version const input = document.query
selector('input[type="search"]'); input.onsearch = () => { console.log("the term searched for was " + input.value); }) specifications this event is not part of any specification. ...
HTMLMediaElement.autoplay - Web APIs
ying without permission or in the background. do not rely on autoplay actually starting playback and instead use play event. examples ... <video id="video" controls> <source src="https://player.vimeo.com/external/250688977.sd.mp4?s=d14b1f1a971dde13c79d6e436b88a6a928dfe26b&profile_id=165"> </video> *** disable autoplay (recommended) *** false is the default value document.query
selector('#video').autoplay = false; specifications specification status comment html living standardthe definition of 'htmlmediaelement.autoplay' in that specification. living standard no change from html5 html5the definition of 'htmlmediaelement.autoplay' in that specification. recommendation initial definition. ...
HTMLMediaElement.captureStream() - Web APIs
cessing code, or as a source for webrtc. example in this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the id "playback" into a mediastream. the stream can then be used for other purposes—like a source for streaming over webrtc, to allow sharing prerecorded videos with another person during a video call. document.query
selector('.playandrecord').addeventlistener('click', function() { var playbackelement = document.getelementbyid("playback"); var capturestream = playbackelement.capturestream(); playbackelement.play(); }); see recording a media element for a longer and more intricate example and explanation. specifications specification status comment media capture from dom elementsthe de...
HTMLMediaElement: emptied event - Web APIs
event target element default action none event handler property globaleventhandlers.onemptied specification html5 media examples these examples add an event listener for the htmlmediaelement's emptied event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('emptied', (event) => { console.log('uh oh. the media is empty. did you call load()?'); }); using the onemptied event handler property: const video = document.query
selector('video'); video.onemptied = (event) => { console.log('uh oh. the media is empty. did you call load()?'); }; specifications specification status html living standa...
HTMLMediaElement.load() - Web APIs
lly changes the playback position (that is, it was not already at the beginning), a timeupdate event is sent. once media has been selected and loading is ready to begin, the loadstart event is delivered. from this point onward, events are sent just like any media load. example this example finds a <video> element in the document and resets it by calling load(). var mediaelem = document.query
selector("video"); mediaelem.load(); specifications specification status comment html living standardthe definition of 'htmlmediaelement.load()' in that specification. living standard initial definition. html5the definition of 'htmlmediaelement.load()' in that specification. recommendation initial definition. ...
HTMLMediaElement: loadstart event - Web APIs
height: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "button log" "video log"; } button { grid-area: button; width: 10rem; margin: .5rem 0; } video { grid-area: video; } .event-log { grid-area: log; } .event-log>label { display: block; } js const loadvideo = document.query
selector('button'); const video = document.query
selector('video'); const eventlog = document.query
selector('.event-log-contents'); let source = null; function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}\n`; } video.addeventlistener('loadstart', handleevent); video.addeventlistener('progress', handleevent); video.addeventlistener('canplay', handleevent); video.ad...
HTMLMediaElement: pause event - Web APIs
ace event target element default action none event handler property globaleventhandlers.onpause specification html5 media examples these examples add an event listener for the htmlmediaelement's pause event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('pause', (event) => { console.log('the boolean paused property is now true. either the ' + 'pause() method was called or the autoplay attribute was toggled.'); }); using the onpause event handler property: const video = document.query
selector('video'); video.onpause = (event) => { console.log('the boolean paused property is now true. either the ' + 'pa...
HTMLMediaElement: play event - Web APIs
rface event target element default action none event handler property globaleventhandlers.onplay specification html5 media examples these examples add an event listener for the htmlmediaelement's play event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('play', (event) => { console.log('the boolean paused property is now false. either the ' + 'play() method was called or the autoplay attribute was toggled.'); }); using the onplay event handler property: const video = document.query
selector('video'); video.onplay = (event) => { console.log('the boolean paused property is now false. either the ' + 'play...
HTMLMediaElement: progress event - Web APIs
5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "button log" "video log"; } button { grid-area: button; width: 10rem; margin: .5rem 0; } video { grid-area: video; } .event-log { grid-area: log; } .event-log>label { display: block; } javascript const loadvideo = document.query
selector('button'); const video = document.query
selector('video'); const eventlog = document.query
selector('.event-log-contents'); let source = null; function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}\n`; } video.addeventlistener('loadstart', handleevent); video.addeventlistener('progress', handleevent); video.addeventlistener('canplay', handleevent); video.ad...
HTMLMediaElement.seekable - Web APIs
the seekable read-only property of the htmlmediaelement returns a timeranges object that contains the time ranges that the user is able to seek to, if any. syntax var seekable = audioorvideo.seekable; value a timeranges object. examples var video = document.query
selector("video"); var timerangesobject = video.seekable; var timeranges = []; //go through the object and output an array for (let count = 0; count < timerangesobject.length; count ++) { timeranges.push([timerangesobject.start(count), timerangesobject.end(count)]); } specifications specification status comment html living standardthe definition of 'htmlmediaelement' in that specification. living standard no change from html5 html5the definition of 'htmlmediaelement' in that specificat...
HTMLMedia​Element​.textTracks - Web APIs
ystage1.vtt" srclang="en" label="key stage 1"> <track kind="metadata" src="keystage2.vtt" srclang="en" label="key stage 2"> <track kind="metadata" src="keystage3.vtt" srclang="en" label="key stage 3"> </video> the htmlmediaelement.texttracks returns a texttrackslist thru which we can iterate. here we print all the properties of each english track to the console. var tracks = document.query
selector('video').texttracks; for (var i = 0, l = tracks.length; i < l; i++) { /* tracks.length == 10 */ if (tracks[i].language == 'en') { console.dir(tracks[i]); } } properties & methods properties length returns the number of text tracks in texttracklist object. methods gettrackbyid() the gettrackbyid(id) method returns the first texttrack in the texttracklist object that mat...
HTMLMediaElement: timeupdate event - Web APIs
event handler property globaleventhandlers.ontimeupdate specification html5 media examples these examples add an event listener for the htmlmediaelement's timeupdate event, then post a message when that event handler has reacted to the event firing. remember, the event frequency is dependant on the system load. using addeventlistener(): const video = document.query
selector('video'); video.addeventlistener('timeupdate', (event) => { console.log('the currenttime attribute has been updated. again.'); }); using the ontimeupdate event handler property: const video = document.query
selector('video'); video.ontimeupdate = (event) => { console.log('the currenttime attribute has been updated. again.'); }; specifications specification status ...
HTMLOrForeignElement.dataset - Web APIs
attribute is set, its value is always converted into a string. for example: null is converted into the string "null". to remove an attribute, you can use the delete operator. syntax const dataattrmap = element.dataset value a domstringmap. ...
HTMLOrForeignElement.nonce - Web APIs
the nonce property of the htmlorforeignelement interface returns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed. in later implementations, elements only expose their nonce attribute to scripts (and not to side-channels like css attribute
selectors). examples retrieving a nonce value in the past, not all browsers supported the nonce idl attribute, so a workaround is to try to use getattribute as a fallback: let nonce = script['nonce'] || script.getattribute('nonce'); however, recent browsers version hide nonce values that are accessed this way (an empty string will be returned). the idl property (script['nonce']) will be the only way to access nonces. nonce hiding helps preventing that attackers exfilt...
HTMLSlotElement.assignedElements() - Web APIs
tmlslotelement.assignedelements(options) parameters options optional an object that sets options for the nodes to be returned. the available options are: flatten: a boolean indicating whether to return the assigned elements of any available child <slot> elements (true) or not (false). defaults to false. return value an array of elements. examples let slots = this.shadowroot.query
selector('slot'); let elements = slots.assignedelements({flatten: true}); specifications specification status comment html living standardthe definition of 'assignedelements()' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please ch...
HTMLSlotElement.assignedNodes() - Web APIs
an object that sets options for the nodes to be returned. the available options are: flatten: a boolean indicating whether to return the assigned nodes of any available child <slot> elements (true) or not (false). defaults to false. return value an array of nodes. examples the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.query
selectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example. e...
HTMLSlotElement.name - Web APIs
the name property of the htmlslotelement interface returns or sets the slot name. a slot is a placeholder inside a web component that users can fill with their own markup. syntax var name = htmlslotelement.name htmlslotelement.name = name value a domstring. examples the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.query
selectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example. every time th...
HTMLSlotElement: slotchange event - Web APIs
event event handler property none in order to trigger a slotchange event, one has to set or remove the slot attribute. examples element.setattribute('slot', slotname); // element.assignedslot = $slot element.removeattribute('slot'); // element.assignedslot = null the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.query
selectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the <slot>s, then add a slotchange event listener to the template's second slot — which is the one which has its contents changed in the example. every tim...
HTMLSlotElement - Web APIs
the assigned elements of any other slots that are descendants of this slot. if no assigned nodes are found, it returns the slot's fallback content. events slotchange fired on an htmlslotelement instance (<slot> element) when the node(s) contained in that slot change. examples the following snippet is taken from our slotchange example (see it live also). let slots = this.shadowroot.query
selectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example. e...
HTMLTableElement.createCaption() - Web APIs
the new <caption> element. syntax htmltableelement = table.createcaption(); return value htmltablecaptionelement example this example uses javascript to add a caption to a table that initially lacks one. html <table> <tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td><td>cell 2.3</td></tr> </table> javascript let table = document.query
selector('table'); let caption = table.createcaption(); caption.textcontent = 'this caption was created by javascript!'; result specifications specification status comment html living standardthe definition of 'htmltableelement: createcaption' in that specification. living standard ...
HTMLTableElement.deleteCaption() - Web APIs
there is no <caption> element associated with the table, this method does nothing. syntax htmltableelement.deletecaption() example this example uses javascript to delete a table's caption. html <table> <caption>this caption will be deleted!</caption> <tr><td>cell 1.1</td><td>cell 1.2</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td></tr> </table> javascript let table = document.query
selector('table'); table.deletecaption(); result specifications specification status comment html living standardthe definition of 'htmltableelement: deletecaption' in that specification. living standard ...
HTMLTableElement.deleteRow() - Web APIs
resenting the last row of the table, the exception index_size_err is thrown. example this example uses javascript to delete a table's second row. html <table> <tr><td>cell 1.1</td><td>cell 1.2</td><td>cell 1.3</td></tr> <tr><td>cell 2.1</td><td>cell 2.2</td><td>cell 2.3</td></tr> <tr><td>cell 3.1</td><td>cell 3.2</td><td>cell 3.3</td></tr> </table> javascript let table = document.query
selector('table'); // delete second row table.deleterow(1); result specifications specification status comment html living standardthe definition of 'htmltableelement: deleterow' in that specification. living standard ...
HTMLTableElement.deleteTFoot() - Web APIs
etfoot() method removes the <tfoot> element from a given <table>. syntax htmltableelement.deletetfoot(); example this example uses javascript to delete a table's footer. html <table> <thead><th>name</th><th>score</th></thead> <tr><td>bob</td><td>541</td></tr> <tr><td>jim</td><td>225</td></tr> <tfoot><th>average</th><td>383</td></tfoot> </table> javascript let table = document.query
selector('table'); table.deletetfoot(); result specifications specification status comment html living standardthe definition of 'htmltableelement: deletetfoot' in that specification. living standard ...
HTMLTableElement.deleteTHead() - Web APIs
the htmltableelement.deletethead() removes the <thead> element from a given <table>. syntax htmltableelement.deletethead(); example this example uses javascript to delete a table's header. html <table> <thead><th>name</th><th>occupation</th></thead> <tr><td>bob</td><td>plumber</td></tr> <tr><td>jim</td><td>roofer</td></tr> </table> javascript let table = document.query
selector('table'); table.deletethead(); result specifications specification status comment html living standardthe definition of 'htmltableelement: deletethead' in that specification. living standard ...
HTMLTemplateElement.content - Web APIs
the htmltemplateelement.content property returns a <template> element's template contents (a documentfragment). syntax var documentfragment = templateelement.content example var templateelement = document.query
selector("#foo"); var documentfragment = templateelement.content.clonenode(true); specifications specification status comment html living standardthe definition of 'htmltemplateelement interface' in that specification. living standard html5the definition of 'htmltemplateelement interface' in that specification. recommendation initial definition ...
IDBFactory.open() - Web APIs
number or not a number. example example of calling open with the current specification's version parameter: var request = window.indexeddb.open("todolist", 4); in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. for a full working example, see our to-do notifications app (view example live.) var note = document.query
selector("ul"); // in the following line, you should include the prefixes // of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use "var indexeddb = ..." if you're not in a function. // moreover, you may need references to some window.idb* objects: window.idbtransaction = window.idbtransaction || window...
IDBVersionChangeEvent.newVersion - Web APIs
s. syntax var newversion = idbversionchangeevent.newversion value a 64-bit integer. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. these events are fired via the custom idbversionchangeevent interface. for a full working example, see our to-do notifications app (view example live.) var note = document.query
selector("ul"); // in the following line, you should include the prefixes of // implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use "var indexeddb = ..." if you're not in a function. // moreover, you may need references to some window.idb* objects: window.idbtransaction = window.idbtransaction || window...
IDBVersionChangeEvent - Web APIs
roperties from its parent, method. example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases. upon a version change (after an upgradedneeded event), the success event will implement the idbversionchangeevent interface. for a full working example, see our to-do notifications app (view example live.) var note = document.query
selector("ul"); // in the following line, you should include the prefixes of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window.webkitindexeddb || window.msindexeddb; // don't use "var indexeddb = ..." if you're not in a function. // moreover, you may need references to some window.idb* objects: window.idbtransaction = window.idbtransaction || window.we...
IIRFilterNode.getFrequencyResponse() - Web APIs
ay[2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput = new float32array(5); var phaseresponseoutput = new float32array(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>iir filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.query
selector('.freq-response-output'); finally, after creating our filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var feedforwardcoefficients = [0.1, 0.2, 0.3, 0.4, 0.5]; var feedbackcoefficients = [0.5, 0.4, 0.3, 0.2, 0.1]; var iirfilter = audioctx.createiirfil...
ImageCapture() constructor - Web APIs
the stream from a webcam. return value a new imagecapture object which can be used to capture still frames from the specified video track. example the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor. navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.query
selector('video').srcobject = mediastream const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => console.log(error)); specifications specification status comment mediastream image capturethe definition of 'imagecapture' in that specification. working draft initial definition. ...
InputEvent.data - Web APIs
ing simple example we've set up an event listener on the input event so that when any change is made to the contents of the <input> element (either by typing or pasting), the text that was added is retrieved via the inputevent.data property and reported in the paragraph below the input. <p>some text to copy and paste.</p> <input type="text"> <p class="result"></p> var editable = document.query
selector('input') var result = document.query
selector('.result'); editable.addeventlistener('input', (e) => { result.textcontent = "inputted text: " + e.data; }); specifications specification status comment input events level 2the definition of 'data' in that specification. working draft initial definition. ...
InputEvent.dataTransfer - Web APIs
rovided to see the effects. <p><span style="font-weight: bold; color: blue">whoa, bold blue text!</span></p> <p><span style="font-style: italic; color: red">exciting: italic red text!</span></p> <p>boring normal text ;-(</p> <hr> <p contenteditable="true">go on, try pasting some content into this editable paragraph and see what happens!</p> <p class="result"></p> var editable = document.query
selector('p[contenteditable]'); var result = document.query
selector('.result') var datatransferobj; editable.addeventlistener('input', (e) => { result.textcontent = e.datatransfer.getdata('text/html'); }); specifications specification status comment input events level 2the definition of 'datatransfer' in that specification. working draft initial definition. brow...
InputEvent.inputType - Web APIs
le="true" style="margin: 20px;padding: 20px;border:2px dashed red;"> <p>some sample text. try inserting line breaks, or deleting text in different ways, or pasting different content in.</p> <hr> <ul> <li>a sample</li> <li>bulleted</li> <li>list.</li> </ul> <p>another paragraph.</p> </div> javascript const log = document.getelementbyid('log'); const editable = document.query
selector('div[contenteditable]'); editable.addeventlistener('input', loginputtype); function loginputtype(event) { log.textcontent = `input type: ${event.inputtype}`; } result try editing the text inside the <div> and see what happens. note: see also masayuki nakano's inputevent test suite for a more detailed example. specifications specification status comment ui even...
IntersectionObserver - Web APIs
er to stop observing a particular target element. examples var intersectionobserver = new intersectionobserver(function(entries) { // if intersectionratio is 0, the target is out of view // and we do not need to do anything. if (entries[0].intersectionratio <= 0) return; loaditems(10); console.log('loaded new items'); }); // start observing intersectionobserver.observe(document.query
selector('.scrollerfooter')); specifications specification status comment intersection observerthe definition of 'intersectionobserver' in that specification. working draft ...
KeyboardEvent.charCode - Web APIs
ypress event. do not use this property, as it is deprecated. use the key property instead. syntax var code = event.charcode; return value a number that represents the unicode value of the character key that was pressed. example html <p>type anything into the input box below to log a <code>charcode</code>.</p> <input type="text" /> <p id="log"></p> javascript let input = document.query
selector('input'); let log = document.query
selector('#log'); input.addeventlistener('keypress', function(e) { log.innertext = `key pressed: ${string.fromcharcode(e.charcode)}\ncharcode: ${e.charcode}`; }); result notes in a keypress event, the unicode value of the key pressed is stored in either the keycode or charcode property, but never both. if the key pressed generates a character (e.g., 'a'...
KeyframeEffect - Web APIs
urns a new keyframeeffect object instance, and also allows you to clone an existing keyframe effect object instance. properties keyframeeffect.target gets and sets the element, or originating element of the pseudo-element, being animated by this object. this may be null for animations that do not target a specific element or pseudo-element. keyframeeffect.pseudoelement gets and sets the
selector of the pseudo-element being animated by this object. this may be null for animations that do not target a pseudo-element. keyframeeffect.iterationcomposite gets and sets the iteration composite operation for resolving the property value changes of this keyframe effect. keyframeeffect.composite gets and sets the composite operation property for resolving the property value changes between this...
KeyframeEffectOptions - Web APIs
tex(-200px) rotate(20deg). accumulate is similar but a little smarter: blur(2) and blur(5) become blur(7), not blur(2) blur(5). replace overwrites the previous value with the new one. iterationcomposite optional determines how values build from iteration to iteration in this animation. can be set to accumulate or replace (see above). defaults to replace. pseudoelement optional the
selector of the pseudo-element to be targeted, if any. defaults to null. delay optional the number of milliseconds to delay the start of the animation. defaults to 0. direction optional whether the animation runs forwards (normal), backwards (reverse), switches direction after each iteration (alternate), or runs backwards and switches direction after each iteration (alternate-reverse). defaults to "...
Location - Web APIs
00%; width:100%; left:50%; margin-left:-50%; font-size:40%; line-height:1.5; background:black;} [title]:hover:before, :target:before {background:black; color:yellow;} [title] [title]:before {margin-top:1.5em;} [title] [title] [title]:before {margin-top:3em;} [title]:hover, :target {position:relative; z-index:1; outline:50em solid rgba(255,255,255,.8);} javascript [].foreach.call(document.query
selectorall('[title][id]'), function (node) { node.addeventlistener("click", function(e) { e.preventdefault(); e.stoppropagation(); window.location.hash = '#' + $(this).attr('id'); }); }); [].foreach.call(document.query
selectorall('[title]'), function (node) { node.addeventlistener("click", function(e) { e.preventdefault(); e.stoppropagation(); window.location.hash = ''; })...
MathMLElement - Web APIs
ndlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement methods this interface has no methods, but inherits methods from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement examples mathml <math xmlns="http://www.w3.org/1998/math/mathml"> <msqrt> <mi>x</mi> </msqrt> </math> javascript document.query
selector('msqrt').constructor.name; // mathmlelement specifications specification status comment mathmlelement interface ...
MediaElementAudioSourceNode.mediaElement - Web APIs
node was first created, either using the mediaelementaudiosourcenode() constructor or the audiocontext.createmediaelementsource() method. syntax audiosourceelement = mediaelementaudiosourcenode.mediaelement; value an htmlmediaelement representing the element which contains the source of audio for the node. examples const audioctx = new window.audiocontext(); const audioelem = document.query
selector('audio'); let options = { mediaelement: audioelem } let source = new mediaelementaudiosourcenode(audioctx, options); console.log(source.mediaelement); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode.mediaelement' in that specification. working draft ...
MediaQueryList.addListener() - Web APIs
callback function you want to run when the media query status changes. in the original implementation, the callback was a non-standard mediaquerylistlistener object. in the new implementation the standard event mechanism is used, the callback is a standard function, and the event object is a mediaquerylistevent, which inherits from event. return value void. ...
MediaQueryList.media - Web APIs
ylist interface is a domstring representing a serialized media query. syntax var media = mediaquerylist.media; value a domstring representing a serialized media query. examples this example runs the media query (max-width: 600px) and displays the value of the resulting mediaquerylist's media property in a <span>. javascript let mql = window.matchmedia('(max-width: 600px)'); document.query
selector(".mq-value").innertext = mql.media; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the result's media property. html <span class="mq-value"></span> a simple <span> to receive the output. css .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border...
MediaQueryList - Web APIs
the document's viewport changes such that its width moves across the 400px boundary in either direction. also available using the onchange event handler property. examples this simple example creates a mediaquerylist and then sets up a listener to detect when the media query status changes, running a custom function when it does to change the appearence of the page. ...
MediaSession.playbackState - Web APIs
browsing context doesn't currently know the current playback state, or the playback state is not available at this time. paused the browser's media session is currently paused. playback may be resumed. playing the browser's media session is currently playing media, which can be paused. ...
MediaSession - Web APIs
) {}); navigator.mediasession.setactionhandler('seekbackward', function() {}); navigator.mediasession.setactionhandler('seekforward', function() {}); navigator.mediasession.setactionhandler('previoustrack', function() {}); navigator.mediasession.setactionhandler('nexttrack', function() {}); } the following example sets up event handlers for pausing and playing: var audio = document.query
selector("#player"); audio.src = "song.mp3"; navigator.mediasession.setactionhandler('play', play); navigator.mediasession.setactionhandler('pause', pause); function play() { audio.play(); navigator.mediasession.playbackstate = "playing"; } function pause() { audio.pause(); navigator.mediasession.playbackstate = "paused"; } specifications specification status comment ...
MediaSource.MediaSource() - Web APIs
e mediasource() constructor of the mediasource interface constructs and returns a new mediasource object with no associated source buffers. syntax var mediasource = new mediasource(); parameters none. ...
MediaSource - Web APIs
ime type is supported by the current user agent — this is, if it can successfully create sourcebuffer objects for that mime type. examples the following simple example loads a video with xmlhttprequest, playing it as soon as it can. ...
active - Web APIs
is the user's local camera and microphone is requested using getusermedia(). when that stream becomes available (that is, when the returned promise is fulfilled, a button on the page is updated based on whether or not the stream is currently active. var promise = navigator.mediadevices.getusermedia({ audio: true, video: true }); promise.then(function(stream) { var startbtn = document.query
selector('#startbtn'); startbtn.disabled = stream.active; };) specifications specification status comment media capture and streamsthe definition of 'active' in that specification. candidate recommendation initial definition. ...
MediaStream.getAudioTracks() - Web APIs
er, this has since been merged into the main mediastreamtrack interface. example this example gets a webcam's audio and video in a stream using getusermedia(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream. navigator.mediadevices.getusermedia({audio: true, video: true}) .then(mediastream => { document.query
selector('video').srcobject = mediastream; // stop the audio stream after 5 seconds settimeout(() => { const tracks = mediastream.getaudiotracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition of 'getaudiotracks()' in that specification. candidate recommendation initial definition. ...
MediaStream.getTracks() - Web APIs
e mediastream interface returns a sequence that represents all the mediastreamtrack objects in this stream's track set, regardless of mediastreamtrack.kind. syntax var mediastreamtracks = mediastream.gettracks() parameters none. return value an array of mediastreamtrack objects. example navigator.mediadevices.getusermedia({audio: false, video: true}) .then(mediastream => { document.query
selector('video').srcobject = mediastream; // stop the stream after 5 seconds settimeout(() => { const tracks = mediastream.gettracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition of 'gettracks()' in that specification. candidate recommendation initial definition. browser compatib...
MediaStream.getVideoTracks() - Web APIs
list of video streams; however, this has since been merged into the main mediastreamtrack interface. example the following example, extracted from chrome's image capture / photo resolution sample, uses getvideotracks() to retrieve a track for passing to the imagecapture() constructor. var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.query
selector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) specifications specification status comment media capture and streamsthe definition of 'getvideotracks()' in that specification. candidate recommendation initial definition. ...
MediaStream Image Capture API - Web APIs
in the mediastreamtrack array is the one to use. you can use the properties of the mediastreamtrack objects to select the one you need. const track = mediastream.getvideotracks()[0]; at this point, you might want to configure the device capabilities before capturing an image. you can do this by calling applyconstraints() on the track object before doing anything else. let zoom = document.query
selector('#zoom'); const capabilities = track.getcapabilities(); // check whether zoom is supported or not. if(!capabilities.zoom) { return; } track.applyconstraints({ advanced : [{ zoom: zoom.value }] }); finally, pass the mediastreamtrack object to the imagecapture() constructor. though a mediastream holds several types of tracks and provides multiple methods for retrieving them, the imagecapture co...
MediaStream Recording API - Web APIs
ded media will not necessarily be individually playable. the media needs to be reassembled before playback. if anything goes wrong during recording, an error event is sent to the mediarecorder. you can listen for error events by setting up a onerror event handler. example here, we use an html canvas as source of the mediastream, and stop recording after 9 seconds. var canvas = document.query
selector("canvas"); // optional frames per second argument. var stream = canvas.capturestream(25); var recordedchunks = []; console.log(stream); var options = { mimetype: "video/webm; codecs=vp9" }; mediarecorder = new mediarecorder(stream, options); mediarecorder.ondataavailable = handledataavailable; mediarecorder.start(); function handledataavailable(event) { console.log("data-available"); if (...
Media Session API - Web APIs
etactionhandler('nexttrack', function() { /* code excerpted. */ }); } some user agents disable autoplay for media elements on mobile devices and require a user gesture to start media. the following example adds a pointerup event to an on-page play button, which is then used to kick off the media session code: playbutton.addeventlistener('pointerup', function(event) { var audio = document.query
selector('audio'); // user interacted with the page. let's play audio... audio.play() .then(_ => { /* set up media session controls, as shown above. */ }) .catch(error => { console.log(error) }); }); specifications specification status comment media session standard draft initial definition. ...
MessagePort: message event - Web APIs
event handler property onmessage examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.query
selector('#message'); const channelmessagebutton = document.query
selector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessage('init', targetorigin, [channel.port2]); the target can receive the port and start listening for messages on it using code like this: window.addeventlistener('message', (event) => { ...
MessagePort: messageerror event - Web APIs
vent handler property onmessageerror examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.query
selector('#message'); const channelmessagebutton = document.query
selector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessage('init', targetorigin, [channel.port2]); the target can receive the port and start listening for messages and message errors on it using code like this: window.addeventlistener('mess...
Microsoft API extensions - Web APIs
layoutchanged msfirstpaint pinned sites apis mssitemodeevent mssitemodejumplistitemremoved msthumbnailclick other apis x-ms-aria-flowfrom x-ms-acceleratorkey x-ms-format-detection mscaching mscachingenabled mscapslockwarningoff event.msconverturl() mselementresize document.mselementsfromrect() msisstatichtml navigator.mslaunchuri() mslaunchuricallback element.msmatches
selector() msprotocols msputpropertyenabled mswriteprofilermark ...
MouseEvent.altKey - Web APIs
he option key. syntax var altkeypressed = instanceofmouseevent.altkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the altkey property when you trigger a click event. html <p>click anywhere to test the <code>altkey</code> property.</p> <p id="log"></p> javascript let log = document.query
selector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the alt key is pressed: ${e.altkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.altkey' in that specification. obsolete no change from document object model (dom) level 2 ...
MouseEvent.buttons - Web APIs
obsolete initial definition ui eventsthe definition of 'mouseevent.buttons' in that specification. working draft current working draft ...
MouseEvent.clientX - Web APIs
e a double floating point value, as redefined by the cssom view module. originally, this property was defined as a long integer. see the "browser compatibility" section for details. example this example displays your mouse's coordinates whenever you trigger the mousemove event. html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.query
selector('#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result specifications specification status comment css object model (cssom) view modulethe definition of 'clientx' in that specification. working draft redefines ...
MouseEvent.clientY - Web APIs
e a double floating point value, as redefined by the cssom view module. originally, this property was defined as a long integer. see the "browser compatibility" section for details. example this example displays your mouse's coordinates whenever you trigger the mousemove event. html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.query
selector('#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result specifications specification status comment css object model (cssom) view modulethe definition of 'clienty' in that specification. working draft redefines ...
MouseEvent.ctrlKey - Web APIs
ntrol key. syntax var ctrlkeypressed = instanceofmouseevent.ctrlkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the ctrlkey property when you trigger a click event. html <p>click anywhere to test the <code>ctrlkey</code> property.</p> <p id="log"></p> javascript let log = document.query
selector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the ctrl key is pressed: ${e.ctrlkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.ctrlkey' in that specification. obsolete no change from document object model (dom) level...
MouseEvent.metaKey - Web APIs
key (⊞). syntax var metakeypressed = instanceofmouseevent.metakey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the metakey property when you trigger a click event. html <p>click anywhere to test the <code>metakey</code> property.</p> <p id="log"></p> javascript let log = document.query
selector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the meta key is pressed: ${e.metakey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.metakey' in that specification. obsolete no change from document object model (dom) level...
MouseEvent.pageX - Web APIs
u can also see an example that demonstrates how to access the mouse position information in every available coordinate system. let's take a look at a simple example that shows you the mouse's position relative to the page's origin. since this example is presented in an <iframe>, that top-left corner is the top-left corner of the frame, not the browser window. ...
MouseEvent.screenX - Web APIs
rn value a double floating point value. early versions of the spec defined this as an integer referring to the number of pixels. see the "browser compatibility" section for details. example this example displays your mouse's coordinates whenever you trigger the mousemove event. ...
MouseEvent.screenY - Web APIs
rn value a double floating point value. early versions of the spec defined this as an integer referring to the number of pixels. see the "browser compatibility" section for details. example this example displays your mouse's coordinates whenever you trigger the mousemove event. html <p>move your mouse to see its position.</p> <p id="screen-log"></p> javascript let screenlog = document.query
selector('#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result specifications specification status comment css object model (cssom) view modulethe definition of 'screeny' in that specification. working draft redefines ...
MouseEvent.shiftKey - Web APIs
occurs. syntax var shiftkeypressed = instanceofmouseevent.shiftkey return value a boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. example this example logs the shiftkey property when you trigger a click event. html <p>click anywhere to test the <code>shiftkey</code> property.</p> <p id="log"></p> javascript let log = document.query
selector('#log'); document.addeventlistener('click', logkey); function logkey(e) { log.textcontent = `the shift key is pressed: ${e.shiftkey}`; } result specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'mouseevent.shiftkey' in that specification. obsolete no change from document object model (dom) le...
MutationObserver.MutationObserver() - Web APIs
s matching the configuration of the observation request specified when calling observe() to begin watching the dom. the kind of change that took place (either a change to the list of children, or a change to an attribute) is detected by looking at the mutation.type property. creating and starting the observer this code actually sets up the observation process. const targetnode = document.query
selector("#someelement"); const observeroptions = { childlist: true, attributes: true, // omit (or set to false) to observe only changes to the parent node subtree: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); the desired subtree is located by finding an element with the id someelement. a set of options for the observer is also establish...
MutationObserver.disconnect() - Web APIs
n detected, but not yet reported to the observer, are discarded. usage notes if the element being observed is removed from the dom, and then subsequently released by the browser's garbage collection mechanism, the mutationobserver is likewise deleted. example this example creates an observer, then disconnects from it, leaving it available for possible reuse. const targetnode = document.query
selector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* some time later... */ observer.disconnect(); specifications specification status comment domthe definition of 'mutationobserver.disconnect()' in that specification. living standard ...
MutationObserver.observe() - Web APIs
cribing the changes that occur, you should be able to "undo" the changes, rewinding the dom back to its initial state. example in this example, we demonstrate how to call the method observe() on an instance of mutationobserver, once it has been set up, passing it a target element and a mutationobserverinit options object. ...
MutationObserver.takeRecords() - Web APIs
change applied to the observed portion of the document's dom tree. note: the queue of mutations which have occurred, but not been delivered to the observer's callback is left empty after calling takerecords(). example in this example, we demonstrate how to handle any undelivered mutationrecords by calling takerecords() just before disconnecting the observer. const targetnode = document.query
selector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takerecords(); observer.disconnect(); if (mutations) { callback(mutations); } the code in li...
MutationObserverInit.attributeOldValue - Web APIs
oard (afk) or offline. function callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mutation.oldvalue + ")"); break; } }); } var targetnode = document.query
selector("#target"); var observer = new mutationobserver(callback); observer.observe(targetnode, { attributes: true, attributeoldvalue: true }); the callback() function—which will be passed into the observe() method when starting the observer, looks at each item in the list of mutationrecord objects. for any items representing an attribute change (which can be detected by the value of mutationreco...
MutationObserverInit.attributes - Web APIs
oard (afk) or offline. function callback(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mutation.oldvalue + ")"); break; } }); } var targetnode = document.query
selector("#target"); var observer = new mutationobserver(callback); observer.observe(targetnode, { attributes: true, attributeoldvalue: true }); the callback() function—which will be passed into the observe() method when starting the observer, looks at each item in the list of mutationrecord objects. for any items representing an attribute change (which can be detected by the value of mutationreco...
Navigator.clipboard - Web APIs
om the permissions api using the "clipboard-read" and/or "clipboard-write" permissions. syntax theclipboard = navigator.clipboard; value the clipboard object used to access the system clipboard. examples the following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard. navigator.clipboard.readtext().then( cliptext => document.query
selector(".cliptext").innertext = cliptext); this snippet replaces the contents of the element whose class is "cliptext" with the text contents of the clipboard. perhaps this code is being used in a browser extension that displays the current clipboard contents, automatically updating periodically or when specific events fire. if the clipboard is empty or doesn't contain text, the "cliptext" element's c...
PannerNode.distanceModel - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
PannerNode.maxDistance - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
PannerNode.panningModel - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
PannerNode.setOrientation() - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
PannerNode.setPosition() - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
PannerNode.setVelocity() - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
PannerNode - Web APIs
ctx.currenttime); listener.forwardy.setvalueattime(0, audioctx.currenttime); listener.forwardz.setvalueattime(-1, audioctx.currenttime); listener.upx.setvalueattime(0, audioctx.currenttime); listener.upy.setvalueattime(1, audioctx.currenttime); listener.upz.setvalueattime(0, audioctx.currenttime); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.query
selector('.play'); var stop = document.query
selector('.stop'); var boombox = document.query
selector('.boom-box'); var listenerdata = document.query
selector('.listener-data'); var pannerdata = document.query
selector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.po...
PasswordCredential - Web APIs
nt. <form id="form" method="post"> <input type="text" name="id" autocomplete="username" /> <input type="password" name="password" autocomplete="current-password" /> <input type="hidden" name="csrf_token" value="*****" /> </form> then, a reference to this form element, using it to create a passwordcredential object, and storing it in the browser's password system. var form = document.query
selector('#form'); var creds = new passwordcredential(form); // store the credentials. navigator.credentials.store(creds) .then(function(creds) { // do something with the credentials if you need to. }); specifications specification status comment credential management level 1 working draft initial definition. ...
PasswordCredential.additionalData - Web APIs
ample the following example creates a formdata object with an appended csrf token. it then stores the form object in the additionaldata parameter, before sending it to server in a call to fetch. //the options object was previously created. navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new formdata(); var csrf_token = document.query
selector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionaldata = form; fetch('https://www.example.com', { method: 'post', credentials: creds }); }; }); specifications specification status comment credential management level 1 working draft initial definition. ...
Using the Permissions API - Web APIs
ions starting in firefox 47, you can now revoke existing permissions, using the permissions.revoke() method. this works in exactly the same way as the permissions.query() method, except that it causes an existing permission to be reverted back to its default state when the promise successfully resolves (which is usually prompt). see the following code in our demo: var revokebtn = document.query
selector('.revoke'); ... revokebtn.onclick = function() { revokepermission(); } ... function revokepermission() { navigator.permissions.revoke({name:'geolocation'}).then(function(result) { report(result.state); }); } the revoke() function has been disabled by default starting in firefox 51, since its design has been brought into question in the web applications security working group. ...
PushManager.getSubscription() - Web APIs
rker registration to check for a subscription navigator.serviceworker.ready.then(function(serviceworkerregistration) { // do we already have a push message subscription? serviceworkerregistration.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages. ...
Response.url - Web APIs
fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response url to the console. ...
Response - Web APIs
(run example live) we use a simple fetch() call to grab an image and display it in an <img> element. the fetch() call returns a promise, which resolves to the response object associated with the resource fetch operation. you'll notice that since we are requesting an image, we need to run body.blob (response implements body) to give the response its correct mime type. ...
SVGAElement.target - Web APIs
iple possible targets for the ending resource, like when the parent document is a mlti-frame html or xhtml document. syntax mylink.target = 'value'; value an svganimatedstring indicating the ending resource target that opens the document when the link is activated. sample values can be found here example the code is taken from the "svgaelement example code" ... var linkref = document.query
selector('a'); linkref.target ='_blank'; ... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'target' in that specification. recommendation browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://gi...
SVGAElement - Web APIs
is a domstring that reflects the type attribute, indicating the mime type of the linked resource. methods this interface has no methods but inherits methods from its parent, svggraphicselement. example in the example below, the target attribute of the <a> element is set to _blank and when the link is clicked, it logs to notify whether the condition is met or not. ...
SVGAnimationElement: beginEvent event - Web APIs
h="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.query
selector('svg'); let animateelem = document.query
selector('animatemotion'); let list = document.query
selector('ul'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('repeatevent', (e) => { let listitem = document.createelement('li'); let msg = ...
SVGAnimationElement: endEvent event - Web APIs
e>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <button>stop animation</button> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.query
selector('svg'); let animateelem = document.query
selector('animatemotion'); let list = document.query
selector('ul'); let btn = document.query
selector('button'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('endevent', () => { let listitem = doc...
SVGAnimationElement: repeatEvent event - Web APIs
h="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y: scroll; padding: 10px 30px; } let svgelem = document.query
selector('svg'); let animateelem = document.query
selector('animatemotion'); let list = document.query
selector('ul'); animateelem.addeventlistener('beginevent', () => { let listitem = document.createelement('li'); listitem.textcontent = 'beginevent fired'; list.appendchild(listitem); }) animateelem.addeventlistener('repeatevent', (e) => { let listitem = document.createelement('li'); let msg = '...
SVGFEDisplacementMapElement - Web APIs
placementmapelement.in1 read only an svganimatedstring corresponding to the in attribute of the given element. svgfedisplacementmapelement.in2 read only an svganimatedstring corresponding to the in2 attribute of the given element. svgfedisplacementmapelement.scale read only an svganimatednumber corresponding to the scale attribute of the given element. svgfedisplacementmapelement.xchannel
selector read only an svganimatedenumeration corresponding to the xchannelselect attribute of the given element. it takes one of the svg_channel_* constants defined on this interface. svgfedisplacementmapelement.ychannel
selector read only an svganimatedenumeration corresponding to the ychannelselect attribute of the given element. it takes one of the svg_channel_* constants defined on this interface.
getBBox() - Web APIs
world!</text> <text x="8" y="32" transform="translate(0 20) scale(1.25 1)">hello world again!</text> </g> <!-- shows bbox in green --> <rect id="rect_1" stroke="#00ff00" stroke-width="3" fill="none"> </rect> <!-- shows boundingclientrect in red --> <rect id="rect_2" stroke="#ff0000" stroke-width="3" fill="none"></rect> </svg> javascript var rectbbox = document.query
selector('#rect_1'); var rectboundingclientrect = document.query
selector('#rect_2'); var groupelement = document.query
selector('#group_text_1'); var bboxgroup = groupelement.getbbox(); rectbbox.setattribute('x', bboxgroup.x); rectbbox.setattribute('y', bboxgroup.y); rectbbox.setattribute('width', bboxgroup.width); rectbbox.setattribute('height', bboxgroup.height); var boundingclientrectgroup = groupelem...
Selection.addRange() - Web APIs
a range object that will be added to the selection. example currently only firefox supports multiple selection ranges, other browsers will not add new ranges to the selection if it already contains one. ...
Selection.deleteFromDocument() - Web APIs
delete selected text by clicking a button. upon clicking the button, the window.getselection() method gets the selected text, and the deletefromdocument() method removes it. html <p>try highlighting some of the text in this paragraph. once you do, you can remove the selected content by clicking the button below.</p> <button>delete selected text</button> javascript let button = document.query
selector('button'); button.addeventlistener('click', deleteselection); function deleteselection() { let selection = window.getselection(); selection.deletefromdocument(); } result specifications specification status comment selection apithe definition of 'selection.deletefromdocument()' in that specification. working draft current ...
Selection.selectAllChildren() - Web APIs
llchildren(parentnode) parameters parentnode all children of parentnode will be selected. parentnode itself is not part of the selection. example html <main> <button>select footer</button> <p>welcome to my website.</p> <p>i hope you enjoy your visit.</p> </main> <footer> <address>webmaster@example.com</address> <p>© 2019</p> </footer> javascript const button = document.query
selector('button'); const footer = document.query
selector('footer'); button.addeventlistener('click', (e) => { window.getselection().selectallchildren(footer); }); result specifications specification status comment selection apithe definition of 'selection.selectallchildren()' in that specification. working draft current definition ...
Selection.setBaseAndExtent() - Web APIs
for="aoffset">anchor offset</label> <input id="aoffset" name="aoffset" type="number" value="0"> </p> <p> <label for="foffset">focus offset</label> <input id="foffset" name="foffset" type="number" value="0"> </p> <p><button>capture selection</button></p> </div> <p><strong>output</strong>: <span class="output"></span></p> the javascript looks like so: var one = document.query
selector('.one'); var two = document.query
selector('.two'); var aoffset = document.getelementbyid('aoffset'); var foffset = document.getelementbyid('foffset'); var button = document.query
selector('button'); var output = document.query
selector('.output'); var selection; button.onclick = function() { try { selection = document.getselection(); selection.setbaseandextent(one, aoffset.value, two...
ServiceWorkerContainer.getRegistration() - Web APIs
parameters scope optional a unique identifier for a service worker registration — the scope url of the registration object you want to return. this is usually a relative url. return value a promise that resolves to a serviceworkerregistration object or undefined. example navigator.serviceworker.getregistration('/app').then(function(registration) { if(registration){ document.query
selector('#status').textcontent = 'serviceworkerregistration found.'; } }); specifications specification status comment service workersthe definition of 'serviceworkercontainer: getregistration' in that specification. working draft initial definition. ...
ServiceWorkerContainer.getRegistrations() - Web APIs
ay. the method returns a promise that resolves to an array of serviceworkerregistration. syntax serviceworkercontainer.getregistrations().then(function(serviceworkerregistrations) { ... }); parameters none. return value a promise that resolves to an array of serviceworkerregistration objects. example navigator.serviceworker.getregistrations().then(function(registrations) { document.query
selector('#status').textcontent = 'serviceworkerregistrations found.'; }); specifications specification status comment service workersthe definition of 'getregistrations()' in that specification. working draft initial definition. ...
Using Service Workers - Web APIs
ase return a 200 ok status or not — and then call resolve on success, or reject on failure. the rest of the contents of this function is fairly standard xhr stuff, so we won’t worry about that for now. ...
ShadowRoot.delegatesFocus - Web APIs
oot interface returns a boolean that indicates whether delegatesfocus was set when the shadow was attached (see element.attachshadow()). this is currently an experimental non-standard feature, available only in chrome. syntax var df = shadowroot.delegatesfocus value a boolean value — true if the shadow root does delegate focus, false if it doesn't. examples let customelem = document.query
selector('my-shadow-dom-element'); let shadow = customelem.shadowroot; ... // does it delegate focus? let hostelem = shadow.delegatesfocus; specifications this feature is not currently in a specification. ...
ShadowRoot.host - Web APIs
the host read-only property of the shadowroot returns a reference to the dom element the shadowroot is attached to. syntax const someelement = shadowroot.host value a dom element. examples let customelem = document.query
selector('my-shadow-dom-element'); let shadow = customelem.shadowroot; ... // return the original host element some time later let hostelem = shadow.host; specifications specification status comment domthe definition of 'shadowroot.host' in that specification. living standard ...
ShadowRoot.innerHTML - Web APIs
the innerhtml property of the shadowroot interface sets or returns a reference to the dom tree inside the shadowroot. syntax var domstring = shadowroot.innerhtml shadowroot.innerhtml = domstring value a domstring. examples let customelem = document.query
selector('my-shadow-dom-element'); let shadow = customelem.shadowroot; shadow.innerhtml = '<strong>this element should be more important!</strong>'; specifications this property is not defined by any specifications yet; see this open spec issue to specify it. ...
ShadowRoot.mode - Web APIs
is "closed", the shadow root’s implementation internals are inaccessible and unchangeable from javascript—in the same way the implementation internals of, for example, the <video> element are inaccessible and unchangeable from javascript. syntax var mode = shadowroot.mode value a value defined in the shadowrootmode enum — either open or closed. examples let customelem = document.query
selector('my-shadow-dom-element'); let shadow = customelem.shadowroot; // another way to check whether the shadow root is open; it will return null if not if(shadow) { // if it is open, close it to stop people stealing our secrets! shadow.mode = 'closed'; } specifications specification status comment domthe definition of 'shadowroot.mode' in that specification. living sta...
Slottable: assignedSlot - Web APIs
ottable element by including it inside the element with a slot attribute with the value my-text. here is one such example: <my-paragraph> <span slot="my-text">let's have some different text!</span> </my-paragraph> in our javascript file we get a reference to the <span> shown above, then log a reference to the original <slot> element the <span> was inserted in. let slottedspan = document.query
selector('my-paragraph span') console.log(slottedspan.assignedslot); // logs '<slot name="my-text">' specifications specification status comment domthe definition of 'assignedslot' in that specification. living standard initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the...
SourceBuffer - Web APIs
fied range from the sourcebuffer. returns a promise which is fulfilled once all matching segments have been removed. examples the following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can. ...
SpeechRecognition.abort() - Web APIs
| navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.query
selector('.output'); var bg = document.query
selector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } abortbtn.onclick = function() { recognition.abort(); console.log('speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('speech recognition has stopped.'); } specificati...
SpeechRecognition.start() - Web APIs
| navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.query
selector('.output'); var bg = document.query
selector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } abortbtn.onclick = function() { recognition.abort(); console.log('speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('speech recognition has stopped.'); } specificati...
SpeechRecognition.stop() - Web APIs
| navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.query
selector('.output'); var bg = document.query
selector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } abortbtn.onclick = function() { recognition.abort(); console.log('speech recognition aborted.'); } recognition.onspeechend = function() { recognition.stop(); console.log('speech recognition has stopped.'); } specificati...
SpeechRecognition - Web APIs
tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; var diagnostic = document.query
selector('.output'); var bg = document.query
selector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color; bg.style.backgroundcolor = color; } specifications specification status...
SpeechSynthesisErrorEvent.error - Web APIs
set in speechsynthesisutterance.voice was not available. text-too-long the contents of the speechsynthesisutterance.text attribute was too long to synthesize. invalid-argument the content of the speechsynthesisutterance.rate, speechsynthesisutterance.pitch or speechsynthesisutterance.volume property was not valid. examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisErrorEvent - Web APIs
erits properties from its parent interface, event. speechsynthesiserrorevent.error read only returns an error code indicating what has gone wrong with a speech synthesis attempt. methods speechsynthesiserrorevent extends the speechsynthesisevent interface, which inherits methods from its parent interface, event. examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
esisutterance interface returns a new speechsynthesisutterance object instance. syntax var utterthis = new speechsynthesisutterance(text); parameters text a domstring containing the text that will be synthesized when the utterance is spoken.. examples the following snippet is excerpted from our speech synthesizer demo. var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.lang - Web APIs
d sets the language of the utterance. if unset, the app's (i.e. the <html> lang value) lang will be used, or the user-agent default if that is unset too. syntax var mylang = speechsynthesisutteranceinstance.lang; speechsynthesisutteranceinstance.lang = 'en-us'; value a domstring representing a bcp 47 language tag. examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.onboundary - Web APIs
the onboundary property of the speechsynthesisutterance interface represents an event handler that will run when the spoken utterance reaches a word or sentence boundary (when the boundary event fires.) syntax speechsynthesisutteranceinstance.onboundary = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === sele...
SpeechSynthesisUtterance.onend - Web APIs
the onend property of the speechsynthesisutterance interface represents an event handler that will run when the utterance has finished being spoken (when the end event fires.) syntax speechsynthesisutteranceinstance.onend = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.vo...
SpeechSynthesisUtterance.onerror - Web APIs
the onerror property of the speechsynthesisutterance interface represents an event handler that will run when an error occurs that prevents the utterance from being succesfully spoken (when the error event fires.) syntax speechsynthesisutteranceinstance.onerror = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name ...
SpeechSynthesisUtterance.onmark - Web APIs
the onmark property of the speechsynthesisutterance interface represents an event handler that will run when the spoken utterance reaches a named ssml mark tag (when the mark event fires.) syntax speechsynthesisutteranceinstance.onmark = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { ...
SpeechSynthesisUtterance.onpause - Web APIs
the onpause property of the speechsynthesisutterance interface represents an event handler that will run when the utterance is paused part way through (when the pause event fires.) this occurs when the speechsynthesis.pause() method is invoked. syntax speechsynthesisutteranceinstance.onpause = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.onresume - Web APIs
speechsynthesisutterance interface represents an event handler that will run when a paused utterance is resumed (when the resume event fires.) this occurs when the speechsynthesis.resume() method is invoked on a paused speech synthesis instance. syntax speechsynthesisutteranceinstance.onresume = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.onstart - Web APIs
the onstart property of the speechsynthesisutterance interface represents an event handler that will run when the utterance has begun to be spoken (when the start event fires.) this occurs when the speechsynthesis.speak() method is invoked. syntax speechsynthesisutteranceinstance.onstart = function() { ... }; examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.pitch - Web APIs
float representing the pitch value. it can range between 0 (lowest) and 2 (highest), with 1 being the default pitch for the current platform or voice. some speech synthesis engines or voices may constrain the minimum and maximum rates further. if ssml is used, this value will be overridden by prosody tags in the markup. examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.rate - Web APIs
correspond to a normal speaking rate. other values act as a percentage relative to this, so for example 2 is twice as fast, 0.5 is half as fast, etc. some speech synthesis engines or voices may constrain the minimum and maximum rates further. if ssml is used, this value will be overridden by prosody tags in the markup. examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.text - Web APIs
ped away by devices that don't support ssml. syntax var mytext = speechsynthesisutteranceinstance.text; speechsynthesisutteranceinstance.text = 'hello i am speaking'; value a domstring representing the text to the synthesised. the maximum length of the text that can be spoken in each utterance is 32,767 characters. examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.voice - Web APIs
if not set by the time the utterance is spoken, the voice used will be the most suitable default voice available for the utterance's lang setting. syntax var myvoice = speechsynthesisutteranceinstance.voice; speechsynthesisutteranceinstance.voice = speechsynthesisvoiceinstance; value a speechsynthesisvoice object. examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SpeechSynthesisUtterance.volume - Web APIs
not set, the default value 1 will be used. syntax var myvolume = speechsynthesisutteranceinstance.volume; speechsynthesisutteranceinstance.volume = 0.5; value a float that represents the volume value, between 0 (lowest) and 1 (highest.) if ssml is used, this value will be overridden by prosody tags in the markup. examples var synth = window.speechsynthesis; var inputform = document.query
selector('form'); var inputtxt = document.query
selector('input'); var voiceselect = document.query
selector('select'); var voices = synth.getvoices(); ... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) ...
SubmitEvent() - Web APIs
puts. examples this code snippet locates a form in the current document, and then an html <button> within the form with the class submit on it. next, a new submitevent is created, configured with its submitter set to the identified button (or null if the button wasn't found). then the event is sent to the form, telling the form that it's been submitted by the button. const form = document.query
selector("form"); const formtrigger = form.query
selector("button.submit"); const submitevent = new submitevent("submit", { submitter: formtrigger }); form.dispatchevent(submitevent); this is a somewhat contrived example, as you can do nearly all of this much more easily, but this gives you deep control over the process that can be useful. specifications specification status comment ...
SubmitEvent.submitter - Web APIs
ubmitter is null. examples in this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.query
selector("form"); form.addeventlistener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processorder(form, handler); } else { showalertmessage("an unknown or unaccepted payment type was selected. please try again.", "ok"); } }); the handler id is obtained by using the submit event's submitter property to get the submit button, from w...
SubmitEvent - Web APIs
interface, event. examples in this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors. each of the submit elements' id is used to identify which payment processor the button corresponds to. let form = document.query
selector("form"); form.addeventlistener("submit", (event) => { let submitter = event.submitter; let handler = submitter.id; if (handler) { processorder(form, handler); } else { showalertmessage("an unknown or unaccepted payment type was selected. please try again.", "ok"); } }); the handler id is obtained by using the submit event's submitter property to get the submit button, from w...
SubtleCrypto.unwrapKey() - Web APIs
,156,8,96,85,32,189,118, 66,114,126,64,203,97,235,13,18,102,192,51,59,5,122,171,96,129,40,32,154,4, 191,234,75,184,112,201,244,110,50,216,44,88,139,175,58,112,7,52,25,64,112, 40,148,187,39,234,96,151,16,158,114,113,109,164,47,108,94,148,35,232,221, 33,110,126,170,25,234,45,165,180,210,193,120,247,155,127]; /* the unwrapped signing key. */ let signingkey; const signbutton = document.query
selector(".pkcs8 .sign-button"); /* convert an array of byte values to an arraybuffer. */ function bytestoarraybuffer(bytes) { const bytesasarraybuffer = new arraybuffer(bytes.length); const bytesuint8 = new uint8array(bytesasarraybuffer); bytesuint8.set(bytes); return bytesasarraybuffer; } /* get some key material to use as input to the derivekey method. the key material is a password supplied ...
Text.splitText() - Web APIs
value of index_size_err is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text; a domexception with a value of no_modification_allowed_err is thrown if the node is read-only. example in this example, the text of a <p> is split into two text nodes, and a <u> is inserted between them. ...
TextEncoder.prototype.encode() - Web APIs
turns a uint8array containing the text given in parameters encoded with the specific method for that textencoder object. syntax b1 = encoder.encode(string); parameters string is a usvstring containing the text to encode. return value a uint8array object. examples <p class="source">this is a sample paragraph.</p> <p class="result">encoded result: </p> const sourcepara = document.query
selector('.source'); const resultpara = document.query
selector('.result'); const string = sourcepara.textcontent; const textencoder = new textencoder(); let encoded = textencoder.encode(string); resultpara.textcontent += encoded; specifications specification status comment encodingthe definition of 'textencoder.prototype.encode()' in that specification. living standard ...
TextTrack.mode - Web APIs
t the cue's end position. example in this example, we configure the text track's cues so that every time a cue is finished, the video automatically pauses playback. this is done by setting the pauseonexit property on each cue to true. however, to ensure that the track's cues are available, we first set mode to showing. window.addeventlistener("load", event => { let trackelem = document.query
selector("track"); let track = trackelem.track; track.mode = "showing"; for (let index=0; index < track.cues.length; index++) { let cue = track.cues[index]; cue.pauseonexit = true; }; }); specifications specification status comment html living standardthe definition of 'mode' in that specification. living standard ...
TextTrackList: addtrack event - Web APIs
the addtrack event is fired when a track is added to a texttracklist. bubbles no cancelable no interface trackevent event handler property onaddtrack examples using addeventlistener(): const mediaelement = document.query
selector('video, audio'); mediaelement.texttracks.addeventlistener('addtrack', (event) => { console.log(`text track: ${event.track.label} added`); }); using the onaddtrack event handler property: const mediaelement = document.query
selector('video, audio'); mediaelement.texttracks.onaddtrack = (event) => { console.log(`text track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification. living standard ...
TextTrackList: change event - Web APIs
the change event is fired when a text track is made active or inactive, or a texttracklist is otherwise changed. bubbles no cancelable no interface event event handler property onchange examples using addeventlistener(): const mediaelement = document.query
selectorall('video, audio')[0]; mediaelement.texttracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); using the onchange event handler property: const mediaelement = document.query
selector('video, audio'); mediaelement.texttracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; specifications specification status html living standardthe definition of 'change' in that specification. living...
TextTrackList.length - Web APIs
lue of 0 indicates that there are no text tracks in the media. syntax var trackcount = texttracklist.length; value a number indicating how many text tracks are included in the texttracklist. each track can be accessed by treating the texttracklist as an array of objects of type texttrack. example this snippet gets the number of text tracks in the first media element found in the dom by query
selector(). var mediaelem = document.query
selector("video, audio"); var numtexttracks = 0; if (mediaelem.texttracks) { numtexttracks = mediaelem.texttracks.length; } note that this sample checks to be sure htmlmediaelement.texttracks is defined, to avoid failing on browsers without support for texttrack. specifications specification status comment html living standardth...
TextTrackList.onaddtrack - Web APIs
d to the element; one addtrack event will occur for each video track in the media resource. example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the videotrack object representing the newly-added track. in this scenario, that function's role is to add the new track to a list of video tracks available to choose from. document.query
selector("video").texttracks.onaddtrack = function(event) { addtotracklist(event.track); }; specifications specification status comment html living standardthe definition of 'texttracklist: onaddtrack' in that specification. living standard ...
TextTrackList.onchange - Web APIs
otracklist. note: you can also add a handler for the change event using addeventlistener(). syntax texttracklist.onchange = eventhandler; example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. var tracklist = document.query
selector("video, audio").texttracks; tracklist.onchange = function(event) { .... /* do something */ }; specifications specification status comment html living standardthe definition of 'texttracklist: onchange' in that specification. living standard ...
TextTrackList.onremovetrack - Web APIs
yntax texttracklist.onremovetrack = eventhandler; value set onremovetrack to a function that accepts as input a trackevent object which indicates in its track property which text track has been removed from the media element. example this simple example just fetches the current number of text tracks in the first media element whenever a track is removed from the media element. document.query
selectorall("video, audio")[0].texttracks.onremovetrack = function(event) { mytrackcount = document.query
selectorall("video, audio")[0].texttracks.length; }; the current number of text tracks remaining in the media element is obtained from texttracklist property length. specifications specification status comment html living standardthe definition of 'texttracklist: onrem...
TextTrackList - Web APIs
ia element, texttracklist lets you set event handlers on the addtrack and removetrack events, so that you can detect when tracks are added to or removed from the media element's stream. see onaddtrack and onremovetrack for details and examples. examples getting a video element's text track list to get a media element's texttracklist, use its texttracks property. var texttracks = document.query
selector("video").texttracks; monitoring track count changes in this example, we have an app that displays information about the number of channels available. to keep it up to date, handlers for the addtrack and removetrack events are set up. texttracks.onaddtrack = updatetrackcount; texttracks.onremovetrack = updatetrackcount; function updatetrackcount(event) { trackcount = texttracks.length; dra...
TrackEvent - Web APIs
f the media track types: audiotrack, videotrack, or texttrack). methods trackevent has no methods of its own; however, it is based on event, so it provides the methods available on event objects. example this example sets up a function, handletrackevent(), which is callled for any addtrack or removetrack event on the first <video> element found in the document. ...
VRStageParameters - Web APIs
property. properties vrstageparameters.sittingtostandingtransform read only contains a matrix that transforms the sitting-space view matrices of vrframedata to standing-space. vrstageparameters.sizex read only returns the width of the play-area bounds in meters. vrstageparameters.sizey read only returns the depth of the play-area bounds in meters. ...
VTTCue - Web APIs
presenting the alignment of all the lines of text within the cue box. vttcue.text returns a domstring with the contents of the cue. methods getcueashtml() returns the cue text as a documentfragment. ...
VideoTrack - Web APIs
urns null if the track was not created by a sourcebuffer or the sourcebuffer has been removed from the mediasource.sourcebuffers attribute of its parent media source. usage notes to get a videotrack for a given media element, use the element's videotracks property, which returns a videotracklist object from which you can get the individual tracks contained in the media: var el = document.query
selector("video"); var tracks = el.videotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach(). this first example gets the first video track on the media: var firsttrack = tracks[0]; the next example scans through all of the media's video tracks, activating the first video track that is in the user's preferred language (taken from a variabl...
VideoTrackList: addtrack event - Web APIs
the addtrack event is fired when a track is added to a videotracklist. bubbles no cancelable no interface trackevent event handler property onaddtrack examples using addeventlistener(): const videoelement = document.query
selector('video'); videoelement.videotracks.addeventlistener('addtrack', (event) => { console.log(`video track: ${event.track.label} added`); }); using the onaddtrack event handler property: const videoelement = document.query
selector('video'); videoelement.videotracks.onaddtrack = (event) => { console.log(`video track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification. living standard ...
VideoTrackList.length - Web APIs
indicates that there are no video tracks in the media. syntax var trackcount = videotracklist.length; value a number indicating how many video tracks are included in the videotracklist. each track can be accessed by treating the videotracklist as an array of objects of type videotrack. example this snippet gets the number of video tracks in the first <video> element found in the dom by query
selector(). var videoelem = document.query
selector("video"); var numvideotracks = 0; if (videoelem.videotracks) { numvideotracks = videoelem.videotracks.length; } note that this sample checks to be sure htmlmediaelement.videotracks is defined, to avoid failing on browsers without support for videotrack. specifications specification status comment html living standardthe...
VideoTrackList.onaddtrack - Web APIs
d to the element; one addtrack event will occur for each video track in the media resource. example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the videotrack object representing the newly-added track. in this scenario, that function's role is to add the new track to a list of video tracks available to choose from. document.query
selector("video").videotracks.onaddtrack = function(event) { addtotracklist(event.track); }; specifications specification status comment html living standardthe definition of 'videotracklist: onaddtrack' in that specification. living standard ...
VideoTrackList.onchange - Web APIs
). syntax videotracklist.onchange = eventhandler; value set onchange to a function that should be called whenever a track is made active. example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track. ...
VideoTrackList.onremovetrack - Web APIs
syntax videotracklist.onremovetrack = eventhandler; value set onremovetrack to a function that accepts as input a trackevent object which indicates in its track property which video track has been removed from the media element. example this simple example just fetches the current number of video tracks in the media element whenever a track is removed from the media element. document.query
selector("my-video").videotracks.onremovetrack = function(event) { mytrackcount = document.query
selector("my-video").videotracks.length; }; the current number of video tracks remaining in the media element is obtained from videotracklist property length. specifications specification status comment html living standardthe definition of 'videotracklist: onremovetrack' in th...
VideoTrackList: removetrack event - Web APIs
the removetrack event is fired when a track is removed from a videotracklist. bubbles no cancelable no interface trackevent event handler property onremovetrack examples using addeventlistener(): const videoelement = document.query
selector('video'); videoelement.videotracks.addeventlistener('removetrack', (event) => { console.log(`video track: ${event.track.label} removed`); }); using the onremovetrack event handler property: const videoelement = document.query
selector('video'); videoelement.videotracks.onremovetrack = (event) => { console.log(`video track: ${event.track.label} removed`); }; specifications specification status html living standardthe definition of 'removetrack' in that specification. livin...
VideoTrackList - Web APIs
ement, videotracklist lets you set event handlers on the addtrack and removetrack events, so that you can detect when tracks are added to or removed from the media element's stream. see onaddtrack and onremovetrack for details and examples. examples getting a media element's video track list to get a media element's videotracklist, use its videotracks property. var videotracks = document.query
selector("video").videotracks; monitoring track count changes in this example, we have an app that displays information about the number of channels available. to keep it up to date, handlers for the addtrack and removetrack events are set up. videotracks.onaddtrack = updatetrackcount; videotracks.onremovetrack = updatetrackcount; function updatetrackcount(event) { trackcount = videotracks.length; ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
utton starts the game, continuing to present the game onscreen as usual. the second button will be used to start the game in immersive-vr mode. note the inclusion of a use-webxr class on the vr mode button. this is important, which we'll explore shortly. ...
WebGLRenderingContext - Web APIs
" + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.enable(gl.scissor_test); gl.scissor(30, 10, 60, 60); gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }); }, false); the source code of this exampl...
Boilerplate 1 - Web APIs
r does not seem to support html5 canvas.</canvas> css body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } javascript function getrenderingcontext() { var canvas = document.query
selector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { var paragraph = document.query
selector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.dr...
Canvas size and WebGL - Web APIs
" + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.enable(gl.scissor_test); gl.scissor(30, 10, 60, 60); gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }); }, false); the source code of this exampl...
Clearing by clicking - Web APIs
-size : inherit; margin : auto; padding : 0.6em; } window.addeventlistener("load", function setupwebgl (evt) { "use strict" // cleaning after ourselves. the event handler removes // itself, because it only needs to run once. window.removeeventlistener(evt.type, setupwebgl, false); // adding the same click event handler to both canvas and // button. var canvas = document.query
selector("#canvas-view"); var button = document.query
selector("#color-switcher"); canvas.addeventlistener("click", switchcolor, false); button.addeventlistener("click", switchcolor, false); // a variable to hold the webglrenderingcontext. var gl; // the click event handler. function switchcolor () { // referring to the externally defined gl variable. // if undefined, try to obtain ...
Clearing with colors - Web APIs
tupwebgl) so that we can refer to the // function object within the function itself. window.addeventlistener("load", function setupwebgl (evt) { "use strict" // cleaning after ourselves. the event handler removes // itself, because it only needs to run once. window.removeeventlistener(evt.type, setupwebgl, false); // references to the document elements. var paragraph = document.query
selector("p"), canvas = document.query
selector("canvas"); // getting the webgl rendering context. var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); // if failed, inform user of failure. otherwise, initialize // the drawing buffer (the viewport) and clear the context // with a solid color. if (!gl) { paragraph.innerhtml = "failed to get webgl context.
Detect WebGL - Web APIs
]</p> <button>press here to detect webglrenderingcontext</button> body { text-align : center; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } // run everything inside window load event handler, to make sure // dom is fully loaded and styled before trying to manipulate it. window.addeventlistener("load", function() { var paragraph = document.query
selector("p"), button = document.query
selector("button"); // adding click event handler to button. button.addeventlistener("click", detectwebglcontext, false); function detectwebglcontext () { // create canvas element. the canvas is not added to the // document itself, so it is never displayed in the // browser window. var canvas = document.createelement("canvas"); // get web...
Simple color animation - Web APIs
background-color : black; } button { display : inline-block; font-size : inherit; margin : auto; padding : 0.6em; } window.addeventlistener("load", function setupanimation (evt) { "use strict" window.removeeventlistener(evt.type, setupanimation, false); // a variable to hold a timer that drives the animation. var timer; // click event handlers. var button = document.query
selector("#animation-onoff"); var verb = document.query
selector("strong"); function startanimation(evt) { button.removeeventlistener(evt.type, startanimation, false); button.addeventlistener("click", stopanimation, false); verb.innerhtml="stop"; // setup animation loop by redrawing every second. timer = setinterval(drawanimation, 1000); // give immediate feedback to user after ...
Getting started with WebGL - Web APIs
html fragment below declares a canvas that our sample will draw into. <body> <canvas id="glcanvas" width="640" height="480"></canvas> </body> preparing the webgl context the main() function in our javascript code, is called when our script is loaded. its purpose is to set up the webgl context and start rendering content. // // start here // function main() { const canvas = document.query
selector("#glcanvas"); // initialize the gl context const gl = canvas.getcontext("webgl"); // only continue if webgl is available and working if (gl === null) { alert("unable to initialize webgl. your browser or machine may not support it."); return; } // set clear color to black, fully opaque gl.clearcolor(0.0, 0.0, 0.0, 1.0); // clear the color buffer with specified clear color...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
ctions first, the signaling channel needs to be opened and the rtcpeerconnection needs to be created. the stun server listed here is obviously not a real one; you'll need to replace stun.myserver.tld with the address of a real stun server. const constraints = { audio: true, video: true }; const config = { iceservers: [{ urls: "stun:stun.mystunserver.tld" }] }; const selfvideo = document.query
selector("video.selfview"); const remotevideo = document.query
selector("video.remoteview"); const signaler = new signalingchannel(); const pc = new rtcpeerconnection(config); this code also gets the <video> elements using the classes "selfview" and "remoteview"; these will contain, respectively, the local user's self-view and the view of the incoming stream from the remote peer. connecting to a remote...
Signaling and video calling - Web APIs
a call the code which handles the "userlist" message calls handleuserlistmsg(). here we set up the handler for each connected user in the user list displayed to the left of the chat panel. this function receives a message object whose users property is an array of strings specifying the user names of every connected user. ...
Using DTMF with WebRTC - Web APIs
see initialization below. initialization when the page loads, we do some basic setup: we fetch references to the dial button and the log output box elements, and we use addeventlistener() to add an event listener to the dial button so that clicking it calls the connectanddial() function to begin the connection process. window.addeventlistener("load", function() { logelement = document.query
selector(".log"); dialbutton = document.query
selector("#dial"); dialbutton.addeventlistener("click", connectanddial, false); }); starting the connection process when the dial button is clicked, connectanddial() is called. this starts building the webrtc connection in preparation for sending the dtmf codes. function connectanddial() { callerpc = new rtcpeerconnection(); hasaddtrack = (callerp...
WebRTC Statistics API - Web APIs
this object contains a map of named dictionaries based on rtcstats and its affiliated types. this example specifically looks for the report whose type is inbound-rtp and whose kind is video. ...
Writing a WebSocket server in C# - Web APIs
> <style> textarea { vertical-align: bottom; } #output { overflow: auto; } #output > p { overflow-wrap: break-word; } #output span { color: blue; } #output span.error { color: red; } </style> <h2>websocket test</h2> <textarea cols=60 rows=6></textarea> <button>send</button> <div id=output></div> <script> // http://www.websocket.org/echo.html var button = document.query
selector("button"), output = document.query
selector("#output"), textarea = document.query
selector("textarea"), // wsuri = "ws://echo.websocket.org/", wsuri = "ws://127.0.0.1/", websocket = new websocket(wsuri); button.addeventlistener("click", onclickbutton); websocket.onopen = function (e) { writetoscreen("connected"); dosend("websocket ro...
Web Video Text Tracks Format (WebVTT) - Web APIs
elow: webvtt 04:02.500 --> 04:05.000 j’ai commencé le basket à l'âge de 13, 14 ans 04:05.001 --> 04:07.800 sur les <i.foreignphrase><lang en>playground</lang></i>, ici à montpellier in the above example it can be observed that we can use the identifier and pseudo class name for defining the language of caption, where <i> tag is for italics. the type of pseudo class is determined by the
selector it is using and working is similar in nature as it works in html. following css pseudo classes can be used: lang (lanugage): e.g., p:lang(it). link: e.g., a:link. nth-last-child: e.g., p:nth-last-child(2). nth-child(n): e.g., p:nth-child(2). where p and a are the tags which are used in html for paragraph and link, respectively and they can be replaced by identifiers which are used for cue...
Using IIR filters - Web APIs
o let's fill our array with frequency values that get larger further on in the array items. now let's get our response data: iirfilter.getfrequencyresponse(myfrequencyarray, magresponseoutput, phaseresponseoutput); we can use this data to draw a filter frequency plot. we'll do so on a 2d canvas context. ...
Window.devicePixelRatio - Web APIs
n or zoom level changes in this example, we'll set up a media query and watch it to see when the device resolution changes, so that we can check the value of devicepixelratio to handle any updates we need to. javascript the javascript code creates the media query that monitors the device resolution and checks the value of devicepixelratio any time it changes. let pixelratiobox = document.query
selector(".pixel-ratio"); let mqstring = `(resolution: ${window.devicepixelratio}dppx)`; const updatepixelratio = () => { let pr = window.devicepixelratio; let prstring = (pr * 100).tofixed(0); pixelratiobox.innertext = `${prstring}% (${pr.tofixed(2)})`; } updatepixelratio(); matchmedia(mqstring).addlistener(updatepixelratio); the string mqstring is set up to be the media query itself. the media...
Window: error event - Web APIs
css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: .5rem; } img { width: 0; height: 0; } js const log = document.query
selector('.event-log-contents'); window.addeventlistener('error', (event) => { log.textcontent = log.textcontent + `${event.type}: ${event.message}\n`; console.log(event) }); const scripterror = document.query
selector('#script-error'); scripterror.addeventlistener('click', () => { const badcode = 'const s;'; eval(badcode); }); result specifications specification status ...
Window: load event - Web APIs
g-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } js const log = document.query
selector('.event-log-contents'); const reload = document.query
selector('#reload'); reload.addeventlistener('click', () => { log.textcontent =''; window.settimeout(() => { window.location.reload(true); }, 200); }); window.addeventlistener('load', (event) => { log.textcontent = log.textcontent + 'load\n'; }); document.addeventlistener('readystatechange', (event) => { log.textcontent =...
Window.matchMedia() - Web APIs
vicepixelratio. examples this example runs the media query (max-width: 600px) and displays the value of the resulting mediaquerylist's matches property in a <span>; as a result, the output will say "true" if the viewport is less than or equal to 600 pixels wide, and will say "false" if the window is wider than that. javascript let mql = window.matchmedia('(max-width: 600px)'); document.query
selector(".mq-value").innertext = mql.matches; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the results' matches property, so that it indicates whether or not the document matches the media query at the moment the page was loaded. html <span class="mq-value"></span> a simple <span> to receive the output. ...
Worker - Web APIs
he onrejectionhandled event handler property. unhandledrejection fires when a promise rejects with no handler to catch the rejection. also available using the onunhandledrejection event handler property. example the following code snippet creates a worker object using the worker() constructor, then uses the worker object: var myworker = new worker('/worker.js'); var first = document.query
selector('input#number1'); var second = document.query
selector('input#number2'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } for a full example, see ourbasic dedicated worker example (run dedicated worker). specifications specification status comment html living standardthe definition of 'worker...
WritableStream.WritableStream() - Web APIs
sage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
WritableStream.getWriter() - Web APIs
sage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
WritableStream - Web APIs
sage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
sage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
WritableStreamDefaultWriter.close() - Web APIs
sage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
WritableStreamDefaultWriter.write() - Web APIs
sage(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
WritableStreamDefaultWriter - Web APIs
(), passing the newly created stream and a string. inside this function it calls the stream's getwriter() method, which returns an instance of writablestreamdefaultwriter. a foreach() call is used to write each chunk of the string to the stream. finally, write() and close() return promises that are processed to deal with success or failure of chunks and streams. ...
XMLHttpRequest: abort event - Web APIs
click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.query
selector('.xhr.success'); const xhrbuttonerror = document.query
selector('.xhr.error'); const xhrbuttonabort = document.query
selector('.xhr.abort'); const log = document.query
selector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addev...
XMLHttpRequest: error event - Web APIs
click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.query
selector('.xhr.success'); const xhrbuttonerror = document.query
selector('.xhr.error'); const xhrbuttonabort = document.query
selector('.xhr.abort'); const log = document.query
selector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addev...
XMLHttpRequest: load event - Web APIs
click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.query
selector('.xhr.success'); const xhrbuttonerror = document.query
selector('.xhr.error'); const xhrbuttonabort = document.query
selector('.xhr.abort'); const log = document.query
selector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addev...
XMLHttpRequest: loadend event - Web APIs
click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.query
selector('.xhr.success'); const xhrbuttonerror = document.query
selector('.xhr.error'); const xhrbuttonabort = document.query
selector('.xhr.abort'); const log = document.query
selector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addev...
XMLHttpRequest: loadstart event - Web APIs
click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.query
selector('.xhr.success'); const xhrbuttonerror = document.query
selector('.xhr.error'); const xhrbuttonabort = document.query
selector('.xhr.abort'); const log = document.query
selector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addev...
XMLHttpRequest: progress event - Web APIs
click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.query
selector('.xhr.success'); const xhrbuttonerror = document.query
selector('.xhr.error'); const xhrbuttonabort = document.query
selector('.xhr.abort'); const log = document.query
selector('.event-log'); function handleevent(e) { log.textcontent = log.textcontent + `${e.type}: ${e.loaded} bytes transferred\n`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addev...
XPathEvaluator.createExpression() - Web APIs
_error is raised. example the following example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.query
selector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.createexpression()' in that specification. recommendation initial definition ...
XPathEvaluator.evaluate() - Web APIs
ted by the xpathevaluator, a domexception of type not_supported_err is raised. example the following example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var evaluator = new xpathevaluator(); var result = evaluator.evaluate("//div", document, null, xpathresult.ordered_node_snapshot_type); document.query
selector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.evaluate()' in that specification. recommendation initial definition ...
XPathEvaluator - Web APIs
possible. example the following example shows the use of the xpathevaluator interface. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.query
selector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator' in that specification. recommendation initial definition ...
XPathExpression.evaluate() - Web APIs
ed_err is raised. example the following example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.query
selector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexpression.evaluate()' in that specification. recommendation initial definition ...
XPathExpression - Web APIs
document. example the following example shows the use of the xpathexpression interface. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression(xpath); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.query
selector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexpression' in that specification. recommendation initial definition ...
XPathResult.booleanValue - Web APIs
lt.resulttype is not boolean_type, an xpathexception of type type_err is thrown. example the following example shows the use of the booleanvalue property. html <div>xpath example</div> <p>text is 'xpath example': <output></output></p> javascript var xpath = "//div/text() = 'xpath example'"; var result = document.evaluate(xpath, document, null, xpathresult.boolean_type, null); document.query
selector("output").textcontent = result.booleanvalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.booleanvalue' in that specification. recommendation initial definition ...
XPathResult.invalidIteratorState - Web APIs
n value a boolean value indicating whether the iterator has become invalid. example the following example shows the use of the invaliditeratorstate property. html <div>xpath example</div> <p>iterator state: <output></output></p> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); // invalidates the iterator state document.query
selector("div").remove(); document.query
selector("output").textcontent = result.invaliditeratorstate ? "invalid" : "valid"; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.invaliditeratorstate' in that specification. recommendation initial definition ...
XPathResult.iterateNext() - Web APIs
the following example shows the use of the iteratenext() method. html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); var node = null; var tagnames = []; while(node = result.iteratenext()) { tagnames.push(node.localname); } document.query
selector("output").textcontent = tagnames.join(", "); result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.iteratenext()' in that specification. recommendation initial definition ...
XPathResult.numberValue - Web APIs
in case xpathresult.resulttype is not number_type, an xpathexception of type type_err is thrown. example the following example shows the use of the numbervalue property. html <div>xpath example</div> <div>number of <div>s: <output></output></div> javascript var xpath = "count(//div)"; var result = document.evaluate(xpath, document, null, xpathresult.number_type, null); document.query
selector("output").textcontent = result.numbervalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.numbervalue' in that specification. recommendation initial definition ...
XPathResult.resultType - Web APIs
e 9 a result node-set containing the first node in the document that matches the expression. example the following example shows the use of the resulttype property. html <div>xpath example</div> <div>is xpath result a node set: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); document.query
selector("output").textcontent = result.resulttype >= xpathresult.unordered_node_iterator_type && result.resulttype <= xpathresult.first_ordered_node_type; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.resulttype' in that specification. recommendation initial definition ...
XPathResult.singleNodeValue - Web APIs
type type_err is thrown. example the following example shows the use of the singlenodevalue property. html <div>xpath example</div> <div>tag name of the element having the text content 'xpath example': <output></output></div> javascript var xpath = "//*[text()='xpath example']"; var result = document.evaluate(xpath, document, null, xpathresult.first_ordered_node_type, null); document.query
selector("output").textcontent = result.singlenodevalue.localname; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.singlenodevalue' in that specification. recommendation initial definition ...
XPathResult.snapshotLength - Web APIs
hot_type or ordered_node_snapshot_type, an xpathexception of type type_err is thrown. example the following example shows the use of the snapshotlength property. html <div>xpath example</div> <div>number of matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); document.query
selector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.snapshotlength' in that specification. recommendation initial definition ...
XPathResult.stringValue - Web APIs
esult.resulttype is not string_type, an xpathexception of type type_err is thrown. example the following example shows the use of the stringvalue property. html <div>xpath example</div> <div>text content of the <div> above: <output></output></div> javascript var xpath = "//div/text()"; var result = document.evaluate(xpath, document, null, xpathresult.string_type, null); document.query
selector("output").textcontent = result.stringvalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.stringvalue' in that specification. recommendation initial definition ...
XRRenderState.baseLayer - Web APIs
rrenderstate.baselayer; value a xrwebgllayer object which is used as the source of the world's contents when rendering each frame of the scene. see the examples below to see how to use updaterenderstate() to set the current xrwebgllayer used for rendering the scene. examples you can set the xrwebgllayer used for rendering by calling updaterenderstate(), like this: let canvas = document.query
selector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); setnewwebgllayer(); function setnewwebgllayer(gl) { if (!gl) { /* webgl not available */ return; } xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl); }); }; here, the canvas obtained in the first line is the canvas into which webgl is going to draw. that context is passed into new xr...
Using the link role - Accessibility
e.target : e.srcelement; if (ref) { window.open(ref.getattribute('data-href'), '_blank'); } } } spanelem.addeventlistener('click', navigatelink); spanelem.addeventlistener('keydown', navigatelink); re...
Using the slider role - Accessibility
input. <label for="fader">volume</label> <input type="range" id="fader" min="1" max="100" value="50" step="1" aria-valuemin="1" aria-valuemax="100" aria-valuenow="50" oninput="outputupdate(value)"> <output for="fader" id="volume">50</output> the following code snippet allows you to return the output as it is updated by user input: function outputupdate(vol) { document.query
selector('#volume').value = vol; } example 2: text values sometimes, a slider is used to choose a value that is not, semantically, a number. in these cases, the aria-valuetext attribute is used to provide the appropriate text name for the currently selected value. in the example below, the slider is used to select a day of the week. <label id="day-label">days</label> <div class="day-slider"> <div id...
x-ms-aria-flowfrom - Accessibility
allowing assistive technology to override the general default of reading in document source order. the property serves to define element relationships utilizing aria relationship attributes and the aria-flowto property. this proprietary property is specific to internet explorer and microsoft edge. syntax x-ms-aria-flowfrom="elementid"; value the x-ms-aria-flowfrom property value uses an id
selector to define which previous element the reading order will flow from. example <div tabindex="0" class="foo" id="element2" role="option" aria-posinset="1" aria-setsize="15" aria-flowto="element8" x-ms-aria-flowfrom="element5"> see also aria relationship attributes microsoft api extensions ...
ARIA: alert role - Accessibility
s often more appropriate as part of a larger user interaction such as inside an event handler or form validation. with javascript, developers control the adding and removing of alerts as appropriate. <button type="button" onclick="triggeralert">trigger alert</button> <p class="alert">the alert will trigger when the button is pressed.</p> function triggeralert() { var alertel = document.query
selector('.alert'); alertel.addattribute("role", "alert"); } accessibility concerns the alert role should read out content that has changed, or bring the user's attention to it immediately, so it should not be used for static content or used regularly. alerts, by definition, are disruptive. lots of alerts at once or unnecessary alerts willl create a bad user experience. specifications sp...
Web applications and ARIA FAQ - Accessibility
, and doesn't affect native browser functionality with respect to the dom or styling. from the browser's point of view, the native html defines the semantic meaning and behavior of an element, with aria attributes acting as a layer on top to help support the at api. though on its own aria will not change any styles, as with any html attributes, css can take advantage of aria attributes as element
selectors. this may provide a convenient mechanism to style aria-enabled widgets. .tab-panel[aria-hidden="true"] { display: none; } .tab-panel[aria-hidden="false"] { display: block; } what about validation? the new attributes introduced in aria, such as role and those prefixed with aria-, aren't officially part of the html 4 or xhtml 4 specifications. as a result, pages that include aria may ...
Web Accessibility: Understanding Colors and Luminance - Accessibility
} em { color: rgb(255, 0, 0, 1); } em { color: rgba(100%, 0%, 0%, 100%); } conversions are not casual. see the stack exchange article, "formula to determine the brightness of rgb color". there are many online tools that can convert rgb to hsl for you, with both the rgb hexidecimal and css function syntax. a great example of a tool that converts colors for you is tom jewett's "mini color
selector" with hsl, rgb, hex options for checking contrast in the browser. luminance and contrast contrast contrast between colors ("hues") is a critical component, but the use of color ("hues") alone is not enough to create accessible content. as mentioned before, any calculation of contrast must include luminance in the calculation. in addition, the "shape" of the text itself will matter. thin...
:-moz-broken - CSS: Cascading Style Sheets
the :-moz-broken css pseudo-class is a mozilla extension that matches elements representing broken image links. note: this
selector is mainly intended to be used by theme developers. syntax :-moz-broken examples html <img src="broken.jpg" alt="this image is broken. :-("> css :-moz-broken { background: bisque; padding: 8px; } result specifications not part of any standard. ...
:-moz-focusring - CSS: Cascading Style Sheets
er agent has focus ring drawing enabled and how the element was focused. whether the user agent has focus ring drawing enabled can depend on operating system settings and other factors, so the precise behavior of this pseudo-class will vary from platform to platform. this feature is not defined in any specification yet, though it was discussed in the working group and it was decided to add it to
selectors 4 or 5. note: developers tend to use :-moz-focusring to differentiate between the focus state when the user focuses an element via a mouse click versus keyboard tabbing. it is also potentially useful if you are creating a custom element and you want to change its style based on its behavior. syntax :-moz-focusring examples html <input /> css input { margin: 5px; } :-moz-focusring {...
:-moz-loading - CSS: Cascading Style Sheets
the :-moz-loading css pseudo-class is a mozilla extension that matches elements that can't be displayed because they have not started loading, such as images that haven't started to arrive yet. note that images that are in the process of loading are not matched by this pseudo-class. note: this
selector is mainly intended to be used by theme developers. syntax :-moz-loading examples setting a background for images that are loading :-moz-loading { background-color: #aaa; background-image: url(loading-animation.gif) center no-repeat; } specifications not part of any standard. ...
:-moz-suppressed - CSS: Cascading Style Sheets
the :-moz-suppressed css pseudo-class is a mozilla extension that matches elements representing images that were suppressed because loading images from the specified site has been blocked. note: this
selector is mainly intended to be used by theme developers. syntax :-moz-suppressed examples styling elements that have been blocked :-moz-suppressed { background: yellow; padding: 8px; } specifications not part of any standard. ...
:-moz-user-disabled - CSS: Cascading Style Sheets
the :-moz-user-disabled css pseudo-class is a mozilla extension that matches elements representing images that were not loaded because images have been entirely disabled by the user's preferences. note: this
selector is mainly intended to be used by theme developers. syntax :-moz-user-disabled examples styling user-disabled elements :-moz-user-disabled { background-color: lightgray; padding: 8px; } specifications not part of any standard. ...
::-webkit-file-upload-button - CSS: Cascading Style Sheets
the ::-webkit-file-upload-button css pseudo-element represents the button of an <input> of type="file". this pseudo-element is non-standard and only supported in webkit/blink compatible browsers like chrome, opera and safari (indicated by the -webkit prefix). syntax
selector::-webkit-file-upload-button examples html <form> <label for="fileupload">upload file</label><br> <input type="file" id="fileupload"> </form> css input, label { display: block; } input[type=file]::-webkit-file-upload-button { border: 1px solid grey; background: #fffaaa; } below is the example for you to try. the screenshot to the left shows what the button will look like if you are without access to chrome, opera or safari. screenshotlive sample specifications not part of any standard. ...
::first-letter (:first-letter) - CSS: Cascading Style Sheets
e definition of '::first-letter' in that specification. working draft generalizes allowed properties to typesetting, text decoration, inline layout properties, opacity, and box-shadow. css text decoration module level 3the definition of 'text-shadow with ::first-letter' in that specification. candidate recommendation allows the use of text-shadow with ::first-letter.
selectors level 3the definition of '::first-letter' in that specification. recommendation introduction of the two-colon syntax. definition of edge-case behavior, such as in list items or with specific languages (e.g., the dutch digraph ij). css level 2 (revision 1)the definition of '::first-letter' in that specification. recommendation no change. css level 1the definition of ...
::first-line (:first-line) - CSS: Cascading Style Sheets
tly where ::first-letter can occur. generalizes allowed properties to typesetting, text decoration, and inline layout properties and opacity. defines the inheritance of ::first-letter. css text decoration module level 3the definition of 'text-shadow with ::first-line' in that specification. candidate recommendation allows the use of text-shadow with ::first-letter.
selectors level 3the definition of '::first-line' in that specification. recommendation introduction of the two-colon syntax. css level 2 (revision 1)the definition of '::first-line' in that specification. recommendation no change. css level 1the definition of '::first-line' in that specification. recommendation initial definition, using the one-colon syntax. ...
::grammar-error - CSS: Cascading Style Sheets
the ::grammar-error css pseudo-element represents a text segment which the user agent has flagged as grammatically incorrect. allowable properties only a small subset of css properties can be used in a rule with ::grammar-error in its
selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::grammar-error examples simple document grammar check in this example, eventual supporting browsers should highlight any flagged grammatical errors with the styles shown. html <p>my friends is coming to the party tonight.</p> css ::grammar-error { text-decoration: underline red; color: red; } result specifications specification status comment ...
::marker - CSS: Cascading Style Sheets
the ::marker css pseudo-element selects the marker box of a list item, which typically contains a bullet or number. it works on any element or pseudo-element set to display: list-item, such as the <li> and <summary> elements. ::marker { color: blue; font-size: 1.2em; } allowable properties only certain css properties can be used in a rule with ::marker as a
selector: all font properties the white-space property color text-combine-upright, unicode-bidi and direction properties the content property all animation and transition properties the specification states that additional css properties may be supported in future. syntax ::marker examples html <ul> <li>peaches</li> <li>apples</li> <li>plums</li> </ul> css ul li::marker { color: red; font-size: 1.5em; } res...
::spelling-error - CSS: Cascading Style Sheets
the ::spelling-error css pseudo-element represents a text segment which the user agent has flagged as incorrectly spelled. allowable properties only a small subset of css properties can be used in a rule with ::spelling-error in its
selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::spelling-error examples simple document spell check in this example, eventual supporting browsers should highlight any flagged spelling errors with the styles shown. html <p contenteditable spellcheck="true">my friends are coegdfgfddffbgning to the party tonight.</p> css ::spelling-error { text-decoration: wavy red; } result specifications specification s...
:active - CSS: Cascading Style Sheets
<form> <label for="my-button">my button: </label> <button id="my-button" type="button">try clicking me or my label!</button> </form> css form :active { color: red; } form button { background: white; } result specifications specification status comment html living standardthe definition of ':active' in that specification. living standard
selectors level 4the definition of ':active' in that specification. working draft no change.
selectors level 3the definition of ':active' in that specification. recommendation no change. css level 2 (revision 1)the definition of ':active' in that specification. recommendation no change. css level 1the definition of ':active' in that specification. recommenda...
:blank - CSS: Cascading Style Sheets
note: the :blank
selector is considered at risk, as the csswg keeps changing it. see csswg issue #1967. the :blank css pseudo-class selects empty user input elements (eg. <input> or <textarea>). syntax :blank examples simple :blank example in eventual supporting browsers, the :blank pseudo-class will enable developers to highlight in some way input controls that are not required, but still have no content filled in, perhaps as a reminder to users. html <textarea></textarea> css textarea:blank { border: 3px solid red; } result specifications specification status comment
selectors level 4the definition of ':blank' in that specification. working draft initial definition. ...
:enabled - CSS: Cascading Style Sheets
ss input:enabled { color: #2b2; } input:disabled { color: #aaa; } result specifications specification status comment html living standardthe definition of ':enabled' in that specification. living standard no change. html5the definition of ':enabled' in that specification. recommendation defines the semantics for html and forms.
selectors level 4the definition of ':enabled' in that specification. working draft no change.
selectors level 3the definition of ':enabled' in that specification. recommendation defines the pseudo-class, but not the associated semantics. ...
:first - CSS: Cascading Style Sheets
margins, orphans, widows, and page breaks of the document. furthermore, you may only use absolute-length units when defining the margins. all other properties will be ignored. syntax :first examples html <p>first page.</p> <p>second page.</p> <button>print!</button> css @page :first { margin-left: 50%; margin-top: 50%; } p { page-break-after: always; } javascript document.query
selector("button").addeventlistener('click', () => { window.print(); }); result press the "print!" button to print the example. the words on the first page should be somewhere around the center, while other pages will have their contents at the default position. specifications specification status comment css paged media module level 3the definition of ':first' in that...
:focus - CSS: Cascading Style Sheets
just remove the focus outline (visible focus indicator) without replacing it with a focus outline that will pass wcag 2.1 sc 1.4.11 non-text contrast. quick tip: never remove css outlines specifications specification status comment html living standardthe definition of ':focus' in that specification. living standard defines html-specific semantics.
selectors level 4the definition of ':focus' in that specification. working draft no change.
selectors level 3the definition of ':focus' in that specification. recommendation no change. css level 2 (revision 1)the definition of ':focus' in that specification. recommendation initial definition. ...
:hover - CSS: Cascading Style Sheets
s over a thumbnail. see this demo for a possible cue. note: for an analogous effect, but based on the :checked pseudo-class (applied to hidden radioboxes), see this demo, taken from the :checked reference page. specifications specification comment feedback html living standardthe definition of ':hover' in that specification. whatwg html github issues
selectors level 4the definition of ':hover' in that specification. allows :hover to be applied to any pseudo-element. css working group drafts github issues
selectors level 3the definition of ':hover' in that specification. css level 2 (revision 1)the definition of ':hover' in that specification. initial definition. ...
:invalid - CSS: Cascading Style Sheets
alid pseudo-class, which applies in a subset of cases for :invalid. specifications specification status comment html living standardthe definition of ':invalid' in that specification. living standard no change. html5the definition of ':invalid' in that specification. recommendation defines the semantics of html and constraint validation.
selectors level 4the definition of ':invalid' in that specification. working draft initial definition. ...
:link - CSS: Cascading Style Sheets
href="#ordinary-target">this is an ordinary link.</a><br> <a href="">you've already visited this link.</a><br> <a>placeholder link (won't get styled)</a> css a:link { background-color: gold; color: green; } result specifications specification status comment html living standardthe definition of ':link' in that specification. living standard
selectors level 4the definition of ':link' in that specification. working draft no change.
selectors level 3the definition of ':link' in that specification. recommendation no change. css level 2 (revision 1)the definition of ':link' in that specification. recommendation lift the restriction to only apply it for <a> element. css level 1the definition of ':link' ...
:root - CSS: Cascading Style Sheets
the :root css pseudo-class matches the root element of a tree representing the document. in html, :root represents the <html> element and is identical to the
selector html, except that its specificity is higher. /* selects the root element of the document: <html> in the case of html */ :root { background: yellow; } syntax :root examples declaring global css variables :root can be useful for declaring global css variables: :root { --main-color: hotpink; --pane-padding: 5px 42px; } specifications specification status comment
selectors level 4the definition of ':root' in that specification. working draft no change.
selectors level 3the definition of ':root' in that specification. recommendation initial definition. ...
:state() - CSS: Cascading Style Sheets
the :state css pseudo-class represents any custom element with the specified custom state in elementinternals.states. custom-element:state(foo) { /* styles to apply when `custom-element` is in the `foo` state */ } syntax syntax not found in db! examples fill in a simple example that nicely shows a typical usage of the
selector, then perhaps some more complex examples. my code block and/or include a list of links to useful code samples that live elsewhere: x y z specifications specification status comment unknownthe definition of 'the :state()
selector' in that specification. unknown initial definition. ...
@document - CSS: Cascading Style Sheets
teral period, you would first need to escape it using regular expression rules (to \.), then escape that string using css rules (to \\.). @document is currently only supported in firefox; if you wanted to replicate using such functionality in your own non-firefox browser, you could try using this polyfill by @an-error94, which uses a combination of a user script, data-* attributes, and attribute
selectors. note: there is a -moz-prefixed version of this property — @-moz-document. this has been limited to use only in user and ua sheets in firefox 59 in nightly and beta — an experiment designed to mitigate potential css injection attacks (see bug 1035091). formal syntax @document [ <url> | url-prefix(<string>) | domain(<string>) | media-document(<string>) | regexp(<string>) ]# { <group-ru...
@font-face - CSS: Cascading Style Sheets
type truetype font/ttf opentype font/otf web open font format font/woff web open font format 2 font/woff2 notes web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless http access controls are used to relax this restriction. @font-face cannot be declared within a css
selector. for example, the following will not work: .classname { @font-face { font-family: myhelvetica; src: local("helvetica neue bold"), local("helveticaneue-bold"), url(mgopenmodernabold.ttf); font-weight: bold; } } formal syntax @font-face { [ font-family: <family-name>; ] | [ src: <src>; ] | [ unicode-range: <unicode-range>; ] | [ font-variant: <font-v...
Coordinate systems - CSS: Cascading Style Sheets
he script in two sections. first, the code that logs the coordinates to the screen. this code will be called by the event handler for the various mouse events we watch. displaying the coordinates as we'll see in the html, the inner box (the one we're watching for events on) contains several paragraphs; one for each of the four coordinate systems we'll be reporting on. let inner = document.query
selector(".inner"); let log = document.query
selector(".log"); function setcoords(e, type) { let idx = type + "x"; let idy = type + "y"; document.getelementbyid(idx).innertext = e[idx]; document.getelementbyid(idy).innertext = e[idy]; } a reference to the <div> inside the inner box which contains the paragraphs that will show the coordinate information is fetched into log. the setcoords() func...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
f property to target a single item. the align-self property accepts all of the same values as align-items plus a value of auto, which will reset the value to that which is defined on the flex container. in this next live example, the flex container has align-items: flex-start, which means the items are all aligned to the start of the cross axis. i have targeted the first item using a first-child
selector and set that item to align-self: stretch; another item has been selected using its class of selected and given align-self: center. you can change the value of align-items or change the values of align-self on the individual items to see how this works. changing the main axis so far we have looked at the behaviour when our flex-direction is row, and while working in a language written top to b...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
ments, you can see that that item has disappeared from the layout, allowing the two sub-children to be laid out as if they were direct children of the flex container. you can try removing the display: contents line to see it return. note that this only removes the box from the layout; the sub-children don’t become direct children in any other way. you can see that as i have used a direct child
selector to add the background and borders to the flex items, this has not been applied to our nested children. they have been laid out as flex items, but as they are not direct children they do not get the other styling. warning: current implementations in most browsers will remove any element with display: contents from the accessibility tree (but descendants will remain). this will cause the element ...
Breadcrumb Navigation - CSS: Cascading Style Sheets
breadcrumb navigation helps the user to understand their location in the website by providing a breadcrumb trail back to the start page. requirements the items typically display inline with a separator to indicate a hierarchy between individual pages. recipe download this example note: the example above uses two
selectors to insert content before every li except the first one. this could also be achieved using one
selector only: .breadcrumb li:not(:first-child)::before { content: "→"; } this solution uses a more complex
selector, but requires less rules. feel free to choose the solution that you prefer. choices made this pattern is laid out using a simple flex layout demonstrating how a line of css can give us our navigation. the separators are added using css generated cont...
Visual formatting model - CSS: Cascading Style Sheets
boxes in the box tree. the part of the string before the paragraph element is wrapped in an anonymous box, then we have the <p>, which generates a box, and then another anonymous box. something to consider about these anonymous boxes is that they inherit styles from their direct parent, but you cannot change how they look by targeting the anonymous box. in my examples, i am using a direct child
selector to target the children of the container. this does not change the anonymous boxes, as they are not a child of the parent block. inline anonymous boxes are created when a string is split by an inline element, for example, a sentence that includes a section wrapped with <em></em>. this splits the sentence into three inline boxes — an anonymous inline box before the emphasized section, the sectio...
animation - CSS: Cascading Style Sheets
ransform: scalex(0); } to { transform: scalex(1); } } .a1 { animation: 3s ease-in 1s 2 reverse both paused slidein; } .a2 { animation: 3s linear 1s slidein; } .a3 { animation: 3s slidein; } .animation { background: #3f87a6; width: 100%; height: calc(100% - 1.5em); transform-origin: left center; } window.addeventlistener('load', function () { var animation = array.from(document.query
selectorall('.animation')); var button = array.from(document.query
selectorall('button')); function togglebutton (btn, type) { btn.classlist.remove('play', 'pause', 'restart'); btn.classlist.add(type); btn.title = type.touppercase(type); } function playpause (i) { var btn = button[i]; var anim = animation[i]; if (btn.classlist.contains('play')) { anim.style.anim...
border-image-slice - CSS: Cascading Style Sheets
6/bb98f533ef.png); border-image-slice: 30; border-image-repeat: round; } li { display: flex; place-content: center; } javascript const widthslider = document.getelementbyid('width'); const sliceslider = document.getelementbyid('slice'); const widthoutput = document.getelementbyid('width-output'); const sliceoutput = document.getelementbyid('slice-output'); const divelem = document.query
selector('div > div'); widthslider.addeventlistener('input', () => { const newvalue = widthslider.value + 'px'; divelem.style.borderwidth = newvalue; widthoutput.textcontent = newvalue; }) sliceslider.addeventlistener('input', () => { const newvalue = sliceslider.value; divelem.style.borderimageslice = newvalue; sliceoutput.textcontent = newvalue; }) result specifications speci...
<easing-function> - CSS: Cascading Style Sheets
background-image: radial-gradient(circle at 10px 10px, rgba(25,255,255,0.8),rgba(25,255,255,0.4)); border-radius: 50%; top: 25px; animation: 1.5s infinite alternate; } @keyframes move-right { from { left: 10%; } to { left: 90%; } } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } javascript const selectelem = document.query
selector('select'); const startbtn = document.query
selector('button'); const divelem = document.query
selector('div > div'); startbtn.addeventlistener('click', () => { if(startbtn.textcontent === 'start animation') { divelem.style.animationname = 'move-right'; startbtn.textcontent = 'stop animation'; divelem.style.animationtimingfunction = selectelem.value; } else { divelem.style.anima...
env() - CSS: Cascading Style Sheets
x) env(safe-area-inset-right, 20px) env(safe-area-inset-bottom, 20px) env(safe-area-inset-left, 20px); } in addition, unlike custom properties, which cannot be used outside of declarations, the env() function can be used in place of any part of a property value, or any part of a descriptor (e.g. in media query rules). as the spec evolves, it may also be usable in other places such as
selectors. originally provided by the ios browser to allow developers to place their content in a safe area of the viewport, the safe-area-inset-* values defined in the specification can be used to help ensure content is visible even to viewers using non‑rectangular displays. syntax /* using the four safe area inset values with no fallback values */ env(safe-area-inset-top); env(safe-area-inset-right...
<filter-function> - CSS: Cascading Style Sheets
und: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png) no-repeat center; } li { display: flex; align-items: center; justify-content: center; margin-bottom: 20px; } input { width: 60% } output { width: 5%; text-align: center; } select { width: 40%; margin-left: 2px; } javascript const selectelem = document.query
selector('select'); const divelem = document.query
selector('div'); const slider = document.query
selector('input'); const output = document.query
selector('output'); const curvalue = document.query
selector('p code'); selectelem.addeventlistener('change', () => { setslider(selectelem.value); setdiv(selectelem.value); }); slider.addeventlistener('input', () => { setdiv(selectelem.value); }); function...
font-style - CSS: Cascading Style Sheets
x-height: 150px; overflow: scroll; } .sample { font: 2rem 'amstelvaralpha', sans-serif; } html, body { max-height: 100vh; max-width: 100vw; overflow: hidden; } body { display: flex; flex-direction: column; } header { margin-bottom: 1.5rem; } .container { flex-grow: 1; } .container > p { margin-top: 0; margin-bottom: 0; } javascript let slantlabel = document.query
selector('label[for="slant"]'); let slantinput = document.query
selector('#slant'); let sampletext = document.query
selector('.sample'); function update() { let slant = `oblique ${slantinput.value}deg`; slantlabel.textcontent = `font-style: ${slant};`; sampletext.style.fontstyle = slant; } slantinput.addeventlistener('input', update); update(); accessibility concerns large sections of text set ...
font-weight - CSS: Cascading Style Sheets
y: auto; } .sample { text-transform: uppercase; font: 1.5rem 'mutatorsans', sans-serif; } html, body { max-height: 100vh; max-width: 100vw; overflow: hidden; } body { display: flex; flex-direction: column; } header { margin-bottom: 1.5rem; } .container { flex-grow: 1; } .container > p { margin-top: 0; margin-bottom: 0; } javascript let weightlabel = document.query
selector('label[for="weight"]'); let weightinput = document.query
selector('#weight'); let sampletext = document.query
selector('.sample'); function update() { weightlabel.textcontent = `font-weight: ${weightinput.value};`; sampletext.style.fontweight = weightinput.value; } weightinput.addeventlistener('input', update); update(); accessibility concerns people experiencing low vision conditions ma...
<length> - CSS: Cascading Style Sheets
5); background-color: orange; display: flex; align-items: center; margin-top: 10px; } .result code { position: absolute; margin-left: 20px; } .results { margin-top: 10px; } .input-container { position: absolute; display: flex; justify-content: flex-start; align-items: center; height: 50px; } label { margin: 0 10px 0 20px; } javascript const inputdiv = document.query
selector('.inner'); const inputelem = document.query
selector('input'); const resultsdiv = document.query
selector('.results'); inputelem.addeventlistener('change', () => { inputdiv.style.width = inputelem.value; const result = document.createelement('div'); result.classname = 'result'; result.style.width = inputelem.value; result.innerhtml = `<code>width: ${inputelem.value}</code>`; resultsdi...
paint() - CSS: Cascading Style Sheets
custom properties are accessible to the paintworklet. specifications specification status comment css painting api level 1the definition of 'paint notation' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to c...
revert - CSS: Cascading Style Sheets
raphs red then all paragraphs will still be red in all sections. revert is just a value. it is still possible to override revert value using specificity. the revert keyword is different from and should not be confused with initial, which uses the initial value defined on a per-property basis by the css specifications. in contrast, user-agent stylesheets set default values on the basis of css
selectors. for example, the initial value for the display property is inline, whereas a normal user-agent stylesheet sets the default display value of <div>s to block, of <table>s to table, etc. examples revert vs unset although revert and unset are similar they differ for some properties for some elements. so in the below example, we set custom font-weight in a global stylesheet, but then try to un...
<transform-function> - CSS: Cascading Style Sheets
sform: rotatey(90deg) translatez(50px); } .left { background: rgba(0,0,210,.7); transform: rotatey(-90deg) translatez(50px); } .top { background: rgba(210,210,0,.7); transform: rotatex(90deg) translatez(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotatex(-90deg) translatez(50px); } .select-form { margin-top: 50px; } javascript const selectelem = document.query
selector('select'); const example = document.query
selector('#example-element'); selectelem.addeventlistener('change', () => { if(selectelem.value === 'choose a function') { return; } else { example.style.transform = `rotate3d(1, 1, 1, 30deg) ${selectelem.value}`; settimeout(function() { example.style.transform = 'rotate3d(1, 1, 1, 30deg)'; }, 2000) } }) result specificatio...
Used value - CSS: Cascading Style Sheets
">..</p> <div id="width-inherit"> <p>explicit width: inherit.</p> <p class="show-used-width">..</p> </div> </div> </div> css #no-width { width: auto; } #width-50 { width: 50%; } #width-inherit { width: inherit; } /* make results easier to see */ div { border: 1px solid red; padding: 8px; } javascript function updateusedwidth(id) { var div = document.query
selector(`#${id}`); var par = div.query
selector('.show-used-width'); var wid = window.getcomputedstyle(div)["width"]; par.textcontent = `used width: ${wid}.`; } function updateallusedwidths() { updateusedwidth("no-width"); updateusedwidth("width-50"); updateusedwidth("width-inherit"); } updateallusedwidths(); window.addeventlistener('resize', updateallusedwidths); result difference from...
var() - CSS: Cascading Style Sheets
the value of a custom property (sometimes called a "css variable") instead of any part of a value of another property. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the var() function cannot be used in property names,
selectors or anything else besides property values. (doing so usually produces invalid syntax, or else a value whose meaning has no connection to the variable.) syntax the first argument to the function is the name of the custom property to be substituted. an optional second argument to the function serves as a fallback value. if the custom property referenced by the first argument is invalid, the funct...
CSS: Cascading Style Sheets
ery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to html. css building blocks this module carries on where css first steps left off — now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. this module looks at the cascade and inheritance, all the
selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. the aim here is to provide you with a toolkit for writing competent css and help you understand all the essential theory, before moving on to more specific disciplines like text styling and css layout. styling text with the basics of the css language covered, the next css topic for you to conc...
Constraint validation - Developer guides
size constraint validation. visual styling of constraint validation apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled. controlling the look of elements the look of elements can be controlled via css pseudo-classes. :required and :optional css pseudo-classes the :required and :optional pseudo-classes allow writing
selectors that match form elements that have the required attribute, or that don't have it. :placeholder-shown css pseudo-class see :placeholder-shown :valid :invalid css pseudo-classes the :valid and :invalid pseudo-classes are used to represent <input> elements whose content validates and fails to validate respectively according to the input's type setting. these classes allow the user to style vali...
HTML5 Parser - Developer guides
assigned to the svg namespace in the dom. <math>…</math> is assigned to the mathml namespace in the dom. foreignobject and annotation-xml (and various less important elements) establish a nested html scope, so you can nest svg, mathml and html as you’d expect to be able to nest them. the parser case-corrects markup so <svg viewbox='0 0 10 10'> works in html source. the dom methods and css
selectors behave case-sensitively, so you need to write your dom calls and css
selectors using the canonical case, which is camelcase for various parts of svg such as viewbox. the syntax <foo/> opens and immediately closes the foo element if it is a mathml or svg element (i.e. not an html element). attributes are tokenized the same way they are tokenized in html, so you can omit quotes in the same situa...
Using HTML sections and outlines - Developer guides
oved all the other html except the <article> element, the content would still make sense to a reader. <article> <h1>how to become an mdn contributor</h1> <p> do you want to help protect the web?.... </p> </article> nesting elements inside an article the <article> element can have other semantic elements such as headers, asides, and footers. this is often useful if you want to add css
selectors to the class property of the element to style the document. <article> <header> <h1>how to become an mdn contributor</h1> </header> <p> do you want to help protect the web?.... </p> <aside> <blockquote> amazing quote from article </blockquote> </aside> <footer> <p> author info, publication date </p> </footer> </article> nesting articles and se...
HTML attribute: rel - HTML: Hypertext Markup Language
ikely need, it helps reduce latency and thereby improves performance when the user does access the resources as the browser preemptively performed dns resolution for the origin of the specified resource. see dns-prefetch described in resource hints. external relevant to <form>, <a>, and <area>, it indicates the referenced document is not part of the current site. this can be used with attribute
selectors to style external links in a way that indicates to the user that they will be leaving the current site. help relevant to <form>, <link>, <a>, and <area>, the help keyword indicates that the linked to content provides context-sensitive help, providing information for the parent of the element defining the hyperlink, and its children. when used within <link>, the help is for the whole document. ...
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
nt to your html document. a fallback text is provided if a browser is unable to render the canvas, or if can't read a canvas. <canvas width="300" height="300"> an alternative text describing what your canvas displays. </canvas> javascript then in the javascript code, call htmlcanvaselement.getcontext() to get a drawing context and start drawing onto the canvas: const canvas = document.query
selector('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); result accessibility concerns alternative content the <canvas> element on its own is just a bitmap and does not provide information about any drawn objects. canvas content is not exposed to accessibility tools as semantic html is. in general, you should avoid using canvas in an accessibl...
<code>: The Inline Code element - HTML: Hypertext Markup Language
code>selectall()</code> highlights all the text in the input field so the user can, for example, copy or delete the text.</p> the output generated by this html looks like this: notes to represent multiple lines of code, wrap the <code> element within a <pre> element. the <code> element by itself only represents a single phrase of code or line of code. a css rule can be defined for the code
selector to override the browser's default font face. preferences set by the user might take precedence over the specified css. specifications specification status comment html living standardthe definition of '<code>' in that specification. living standard html5the definition of '<code>' in that specification. recommendation html 4.01 specific...
<dialog>: The Dialog element - HTML: Hypertext Markup Language
<button value="cancel">cancel</button> <button id="confirmbtn" value="default">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <output aria-live="polite"></output> javascript var updatebutton = document.getelementbyid('updatedetails'); var favdialog = document.getelementbyid('favdialog'); var outputbox = document.query
selector('output'); var selectel = document.query
selector('select'); var confirmbtn = document.getelementbyid('confirmbtn'); // "update details" button opens the <dialog> modally updatebutton.addeventlistener('click', function onopen() { if (typeof favdialog.showmodal === "function") { favdialog.showmodal(); } else { alert("the <dialog> api is not supported by this browser"); } }); // "favo...
<input type="radio"> - HTML: Hypertext Markup Language
one</label> <input type="radio" id="contactchoice3" name="contact" value="mail"> <label for="contactchoice3">mail</label> </div> <div> <button type="submit">submit</button> </div> </form> <pre id="log"> </pre> then we add some javascript to set up an event listener on the submit event, which is sent when the user clicks the "submit" button: var form = document.query
selector("form"); var log = document.query
selector("#log"); form.addeventlistener("submit", function(event) { var data = new formdata(form); var output = ""; for (const entry of data) { output = output + entry[0] + "=" + entry[1] + "\r"; }; log.innertext = output; event.preventdefault(); }, false); try this example out and see how there's never more than one result for the contact group.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
"screen and (min-width: 600px)"> <link href="highres.css" rel="stylesheet" media="screen and (min-resolution: 300dpi)"> stylesheet load events you can determine when a style sheet has been loaded by watching for a load event to fire on it; similarly, you can detect if an error has occurred while processing a style sheet by watching for an error event: <script> var mystylesheet = document.query
selector('#my-stylesheet'); mystylesheet.onload = function() { // do something interesting; the sheet has been loaded } mystylesheet.onerror = function() { console.log("an error occurred loading the stylesheet!"); } </script> <link rel="stylesheet" href="mystylesheet.css" id="my-stylesheet"> note: the load event fires once the stylesheet and all of its imported content has been loaded and parsed...
<tr>: The Table Row element - HTML: Hypertext Markup Language
s. first, the overall styling of the header: thead > tr { background-color: rgb(228, 240, 245); } thead > tr:nth-of-type(2) { border-bottom: 2px solid black; } this sets the background color of all <tr> elements in the table's heading (as specified using <thead>). then we set the bottom border of the top header to be a two-pixel wide line. notice, however, that we're using the :nth-of-type
selector to apply border-bottom to the second row in the heading. why? because the heading is made of two rows that are spanned by some of the cells. that means there are actually two rows there; applying the style to the first row would not give us the expected result. the "joined" and "canceled" headers let's style these two header cells with green and red hues to represent the "good" of a new member ...
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
", "menlo", "monaco", "courier", monospace; } html <p>enter the following at the telnet command prompt: <code>set localecho</code><br /> the telnet client should display: <tt>local echo is on</tt></p> result usage notes the <tt> element is, by default, rendered using the browser's default non-proportional font. you can override this using css by creating a rule using the tt
selector, as seen in the example overriding the default font above. user-configured changes to the default monospace font setting may take precedence over your css. although this element wasn't officially deprecated in html 4.01, its use was discouraged in favor of the semantic elements and/or css. the <tt> element is obsolete in html 5. specifications specification status comment ...
class - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Global attributes - HTML: Hypertext Markup Language
f each sentence defaults to a capital letter; all other letters default to lowercase words, the first letter of each word defaults to a capital letter; all other letters default to lowercase characters, all letters should default to uppercase class a space-separated list of the classes of the element. classes allows css and javascript to select and access specific elements via the class
selectors or functions like the method document.getelementsbyclassname(). contenteditable an enumerated attribute indicating if the element should be editable by the user. if so, the browser modifies its widget to allow editing. the attribute must take one of the following values: true or the empty string, which indicates that the element must be editable; false, which indicates that the element m...
HTML documentation index - HTML: Hypertext Markup Language
lobal attribute is an enumerated attribute that controls whether and how text input is automatically capitalized as it is entered/edited by the user. 10 class global attributes, html, reference the class global attribute is a space-separated list of the case-sensitive classes of the element. classes allow css and javascript to select and access specific elements via the class
selectors or functions like the dom method document.getelementsbyclassname. 11 contenteditable editing, global attributes, html, reference, text editing, contenteditable, text entry, text input the contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. if so, the browser modifies its widget to allow editing. 12 ...
CSP: style-src - HTTP
import url("https://not-example.com/styles/print.css") print; </style> as well as styles loaded using the link header: link: <https://not-example.com/styles/stylesheet.css>;rel=stylesheet inline style attributes are also blocked: <div style="display:none">foo</div> as well as styles that are applied in javascript by setting the style attribute directly, or by setting csstext: document.query
selector('div').setattribute('style', 'display:none;'); document.query
selector('div').style.csstext = 'display:none;'; however, styles properties that are set directly on the element's style property will not be blocked, allowing users to safely manipulate styles via javascript: document.query
selector('div').style.display = 'none'; these types of manipulations can be prevented by disallowing javascript...
TypeError: Reduce of empty array with no initial value - JavaScript
a filter (array.prototype.filter(), typedarray.prototype.filter()) which will remove all elements of the list. thus leaving none to be used as the initial value. var ints = [0, -1, -2, -3, -4, -5]; ints.filter(x => x > 0) // removes all elements .reduce((x, y) => x + y) // no more elements to use for the initial value. similarly, the same issue can happen if there is a typo in a
selector, or an unexpected number of elements in a list: var names = document.getelementsbyclassname("names"); var name_list = array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); valid cases these problems can be solved in two different ways. one way is to actually provide an initialvalue as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or...
Array.prototype.map() - JavaScript
[2, 8, 18] // numbers is still [1, 4, 9] using map generically this example shows how to use map on a string to get an array of bytes in the ascii encoding representing the character values: let map = array.prototype.map let a = map.call('hello world', function(x) { return x.charcodeat(0) }) // a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] using map generically query
selectorall this example shows how to iterate through a collection of objects collected by query
selectorall. this is because query
selectorall returns a nodelist (which is a collection of objects). in this case, we return all the selected options' values on the screen: let elems = document.query
selectorall('select option:checked') let values = array.prototype.map.call(elems, function(obj) { return obj...
Set - JavaScript
, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} // (key and value are the same here) for (let [key, value] of myset.entries()) console.log(key) // convert set object to an array object, with array.from let myarr = array.from(myset) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // the following will also work if run in an html document myset.add(document.body) myset.has(document.query
selector('body')) // true // converting between set and array myset2 = new set([1, 2, 3, 4]) myset2.size // 4 [...myset2] // [1, 2, 3, 4] // intersect can be simulated via let intersection = new set([...set1].filter(x => set2.has(x))) // difference can be simulated via let difference = new set([...set1].filter(x => !set2.has(x))) // iterate set entries with foreac...
for...of - JavaScript
in these cases, the iterator is closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { console.log(o); break; // closes iterator, execution continues ...
Autoplay guide for media and Web Audio APIs - Web media technologies
attribute than for other means of playing media automatically. it also lets the browser take responsibility for starting playback, letting it optimize the timing of that taking place. example: playing video this simple example plays the first <video> element found in the document. play() won't let the playback begin unless the document has permission to automatically play media. document.query
selector("video").play(); example: handling play() failures it's much easier to detect a failure to autoplay media when you use the play() method to start it. play() returns a promise which is resolved once the media successfully begins to play, and is rejected when playback fails to begin (such as if autoplay is denied). when autoplay fails, you likely will want to offer a way for the user to manually ...
Populating the page: how browsers work - Web Performance
ing path is processing css and building the cssom tree. the css object model is similar to the dom. the dom and cssom are both trees. they are independent data structures. the browser converts the css rules into a map of styles it can understand and work with. the browser goes through each rule set in the css, creating a tree of nodes with parent, child, and sibling relationships based on the css
selectors. as with html, the browser needs to convert the received css rules into something it can work with. hence, it repeats the html-to-object process, but for the css. the cssom tree includes styles from the user agent style sheet. the browser begins with the most general rule applicable to a node and recursively refines the computed styles by applying more specific rules. in other words, it cascad...
Add to Home screen - Progressive web apps (PWAs)
add-button { position: absolute; top: 1px; left: 1px; } javascript for handling the install at the bottom of our index.js file, we added some javascript to handle the installation. first of all, we declare a deferredprompt variable (which we'll explain later on), get a reference to our install button, and set it to display: none initially: let deferredprompt; const addbtn = document.query
selector('.add-button'); addbtn.style.display = 'none'; we hide the button initially because the pwa will not be available for install until it follows the a2hs criteria. when this happens, supporting browsers will fire a beforeinstallprompt event. we can then use a handler like the one below to handle the installation: window.addeventlistener('beforeinstallprompt', (e) => { // prevent chrome 67 and e...
Progressive loading - Progressive web apps (PWAs)
g/slug.jpg' alt='name'> those images will be loaded via javascript after the site finishes building the html structure. the placeholder image is scaled the same way the original images are, so it will take up the same space and not cause the layout to repaint as the images load. loading via javascript the app.js file processes the data-src attributes like so: let imagestoload = document.query
selectorall('img[data-src]'); const loadimages = (image) => { image.setattribute('src', image.getattribute('data-src')); image.onload = () => { image.removeattribute('data-src'); }; }; the imagestoload variable contains references to all the images, while the loadimages function moves the path from data-src to src. when each image is actually loaded, we remove its data-src attribute as it's not...
Mobile first - Progressive web apps (PWAs)
izr stores the results of all its feature tests as classes on the html element. for example, the modernizr in our example app is testing for multiple background image and rgba support. when they are not supported, the <html> tag looks like this: <html class=" js no-rgba no-multiplebgs"> when these are present, we can serve alternative styling rules to provide sensible fallbacks using descendant
selectors — see the following in my code. .no-multiplebgs body { background: white; } .no-rgba .main > p { background: white; } this is not hugely pretty, but it does make the main content area more readable on browsers that don't support either or both of these features. modernizr also puts its feature detect results in a javascript modenizr object too, so that you can run javascript code selec...
baseFrequency - SVG: Scalable Vector Graphics
then that value is used for both x and y. negative values are forbidden. example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="2" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannel
selector="r" ychannel
selector="g"/> </filter> <circle cx="100" cy="100" r="100" style="filter: url(#displacementfilter)"/> </svg> specifications specification status comment filter effects module level 1the definition of 'basefrequency' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition ...
numOctaves - SVG: Scalable Vector Graphics
e yes <integer> defines the number of octaves. negative values are forbidden. example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence basefrequency="0.05" numoctaves="3" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannel
selector="r" ychannel
selector="g"/> </filter> <circle cx="100" cy="100" r="100" style="filter: url(#displacementfilter)"/> </svg> specifications specification status comment filter effects module level 1the definition of 'numoctaves' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of ...
SVG Attribute reference - SVG: Scalable Vector Graphics
to transform transform-origin type u u1 u2 underline-position underline-thickness unicode unicode-bidi unicode-range units-per-em v v-alphabetic v-hanging v-ideographic v-mathematical values vector-effect version vert-adv-y vert-origin-x vert-origin-y viewbox viewtarget visibility w width widths word-spacing writing-mode x x x-height x1 x2 xchannel
selector xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y y y1 y2 ychannel
selector z z zoomandpan svg attributes by category generic attributes core attributes id, lang, tabindex, xml:base, xml:lang, xml:space style attributes class, style conditional processing attributes externalresourcesrequired, required...
<a> - SVG: Scalable Vector Graphics
lect only svg <a> elements, and not also html’s. see warning below */ svg|a:link, svg|a:visited { cursor: pointer; } svg|a text, text svg|a { fill: blue; /* even for text, svg uses fill over color */ text-decoration: underline; } svg|a:hover, svg|a:active { outline: dotted 1px blue; } since this element shares its tag name with html's <a> element, selecting a with css or query
selector may apply to the wrong kind of element. try the @namespace rule to distinguish the two. attributes download instructs browsers to download a url instead of navigating to it, so the user will be prompted to save it as a local file. value type: <string> ; default value: none; animatable: no href the url or url fragment the hyperlink points to. value type: <url> ; default value: none; an...
<feTurbulence> - SVG: Scalable Vector Graphics
interface this element implements the svgfeturbulenceelement interface. example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="2" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannel
selector="r" ychannel
selector="g"/> </filter> <circle cx="100" cy="100" r="100" style="filter: url(#displacementfilter)"/> </svg> specifications specification status comment filter effects module level 1the definition of '<feturbulence>' in that specification. working draft no change scalable vector graphics (svg) 1.1 (second edition)the definition...
Specification Deviations - SVG: Scalable Vector Graphics
will implement these attributes on all svg elements as of firefox 3. in general this change will not be visible to svg authors (the elements for which the svg specification does not define the 'class' and 'style' attribute are elements that are not displayed directly). however, there are two exceptions. extending the 'class' attribute to apply to all svg elements will allow svg authors to use the
selectors api to select any svg element based on class. this seems like a good thing. requiring svg authors to know which elements can and cannot take a 'class' attribute would just put an extra burden on them. extending the 'style' attribute to apply to all svg elements should only really be visible to svg authors if they call viewcss.getcomputedstyle on the element or one of its descendants. since these...
SVG and CSS - SVG: Scalable Vector Graphics
se pointer is over any one of them, without changing the way the outer petals work. see a solution to this challenge. simplified structure the svg structure shown above could be written much more concise by referencing the individual parts of the flower via <use> elements. this behavior is standardized, though only a few browsers support the :hover pseudo-class and other more complex css
selectors on elements referenced via <use> elements, at the moment. there is some discussion about what rules apply to such referenced elements. see below how the structure then looks like. <svg width="600px" height="600px" viewbox="-300 -300 600 600" xmlns="http://www.w3.org/2000/svg"> <title>svg demonstration</title> <desc>mozilla css getting started - svg demonstration</desc> <defs> <...
Securing your site - Web security
omplete nor does following its suggestions guarantee your site will be fully secure. user information security how to turn off form autocompletion form fields support autocompletion in gecko; that is, their values can be remembered and automatically brought back the next time the user visits your site. for certain types of data, you may wish to disable this feature. privacy and the :visited
selector this article discusses changes made to the getcomputedstyle() method that eliminates the ability for malicious sites to figure out the user's browsing history. hash passwords using a secure algorithm (owasp) storing passwords in plain text can lead to attackers knowing and leaking the exact password of your site's users, potentially putting the users at risk. the same issues can arise if you u...
Types of attacks - Web security
post endpoints should not interchangeably accept get requests with parameters in the query string. a csrf token should be inc...
Web security
me>, <iframe>, <object>, <embed>, or <applet>. user information security insecure passwords serving login forms over http is especially dangerous because of the wide variety of attacks that can be used against them to extract a user’s password. network eavesdroppers could steal a user's password by sniffing the network, or by modifying the served page in transit. privacy and the :visited
selector before about 2010, the css :visited
selector allowed websites to uncover a user's browsing history and figure out what sites the user had visited. to mitigate this problem, browsers have limited the amount of information that can be obtained from visited links. security-related glossary terms block cipher mode of operation certificate authority challenge-response authenticat...