Search completed in 2.53 seconds.
3451 results for "tel":
Your results are loading. Please wait...
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
the bytelengthqueuingstrategy() constructor creates and returns a bytelengthqueuingstrategy object instance.
... syntax var bytelengthqueuingstrategy = new bytelengthqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property.
... return value an instance of the bytelengthqueuingstrategy object.
...And 2 more matches
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
<input> elements of type tel are used to let the user enter and edit a telephone number.
... unlike <input type="email"> and <input type="url"> , the input value is not automatically validated to a particular format before the form can be submitted, because formats for telephone numbers vary so much around the world.
... despite the fact that inputs of type tel are functionally identical to standard text inputs, they do serve useful purposes; the most quickly apparent of these is that mobile browsers — especially on mobile phones — may opt to present a custom keypad optimized for entering phone numbers.
...And 39 more matches
HTMLSelectElement - Web APIs
the htmlselectelement interface represents a <select> html element.
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmlselectelement" target="_top"><rect x="321" y="65" width="170" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="406" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlselectelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interf...
... htmlselectelement.autofocus a boolean reflecting the autofocus html attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control.
...And 31 more matches
HTMLObjectElement - Web APIs
the htmlobjectelement interface provides special properties and methods (beyond those on the htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <object> element, representing external resources.
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmlobjectelement" target="_top"><rect x="321" y="65" width="170" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="406" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlobjectelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits pr...
... htmlobjectelement.align is a domstring representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context.
...And 30 more matches
HTMLScriptElement - Web APIs
html <script> elements expose the htmlscriptelement interface, which provides special properties and methods for manipulating the behavior and execution of <script> elements (beyond the inherited htmlelement interface).
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmlscriptelement" target="_top"><rect x="321" y="65" width="170" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="406" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlscriptelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits pr...
... htmlscriptelement.type is a domstring representing the mime type of the script.
...And 16 more matches
HTMLFieldSetElement - Web APIs
the htmlfieldsetelement interface provides special properties and methods (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating the layout and presentation of <fieldset> elements.
...ale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmlfieldsetelement" target="_top"><rect x="301" y="65" width="190" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="396" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlfieldsetelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits ...
... htmlfieldsetelement.disabled a boolean reflecting the disabled html attribute, indicating whether the user can interact with the control.
...And 15 more matches
HTMLOutputElement - Web APIs
the htmloutputelement interface provides properties and methods (beyond those inherited from htmlelement) for manipulating the layout and presentation of <output> elements.
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmloutputelement" target="_top"><rect x="321" y="65" width="170" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="406" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmloutputelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interf...
... htmloutputelement.defaultvalue a domstring representing the default value of the element, initially the empty string.
...And 15 more matches
HTMLInputElement - Web APIs
the htmlinputelement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.
...andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmlinputelement" target="_top"><rect x="331" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlinputelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties properties...
...this attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.
...And 14 more matches
SVGTextContentElement - Web APIs
the svgtextcontentelement interface is implemented by elements that support rendering child text content.
... it is inherited by various text-related interfaces, such as svgtextelement, svgtspanelement, svgtrefelement, svgaltglyphelement and svgtextpathelement.
...roke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggraphicselement</text></a><polyline points="301,89 291,84 291,94 301,89" stroke="#d4dde4" fill="none"/><line x1="291" y1="89" x2="261" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgtextcontentelement" target="_top"><rect x="51" y="65" width="210" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="156" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextcontentelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants ...
...And 13 more matches
nsITelemetry
toolkit/components/telemetry/nsitelemetry.idlscriptable a service to gather performance data that can be tracked over time to allow generating histograms.
... 1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) implemented by: @mozilla.org/base/telemetry;1 as a service: let telemetry = components.classes["@mozilla.org/base/telemetry;1"] .getservice(components.interfaces.nsitelemetry); method overview jsval gethistogrambyid(in acstring id); jsval snapshothistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); jsval getkeyedhistogrambyid(in acstring id); void capturestack(in acstring name); jsval snapshotcapturedstacks([optional] in boolean clear); nsisupports getloadedmodules(); jsval snapshotkeyedhistograms(in uint32_t adataset, in boolea...
...n asubsession, in boolean aclear); void sethistogramrecordingenabled(in acstring id, in boolean enabled); void asyncfetchtelemetrydata(in nsifetchtelemetrydatacallback acallback); double mssinceprocessstart(); void scalaradd(in acstring aname, in jsval avalue); void scalarset(in acstring aname, in jsval avalue); void scalarsetmaximum(in acstring aname, in jsval avalue); jsval snapshotscalars(in uint32_t adataset, [optional] in boolean aclear); void keyedscalaradd(in acstring aname, in astring akey, in jsval avalue); void keyedscalarset(in acstring aname, in astring akey, in jsval avalue); void keyedscalarsetmaximum(in acstring aname, in astring akey, in jsval avalue); jsval snapshotkeyedscalar...
...And 11 more matches
Document.getElementById() - Web APIs
the document method getelementbyid() returns an element object representing the element whose id property matches the specified string.
... syntax var element = document.getelementbyid(id); parameters id the id of the element to locate.
... example html <html> <head> <title>getelementbyid example</title> </head> <body> <p id="para">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button> </body> </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, how...
...And 9 more matches
SVGFESpotLightElement - Web APIs
the svgfespotlightelement interface corresponds to the <fespotlight> element.
...le mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgelement</text></a><polyline points="481,25 491,20 491,30 481,25" stroke="#d4dde4" fill="none"/><line x1="491" y1="25" x2="499" y2="25" stroke="#d4dde4"/><line x1="499" y1="25" x2="499" y2="90" stroke="#d4dde4"/><line x1="499" y1="90" x2="482" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgfespotlightelement" target="_top"><rect x="271" y="65" width="210" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="376" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfespotlightelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this in...
... svgfespotlightelement.x read only an svganimatednumber corresponding to the x attribute of the given element.
...And 9 more matches
Document.getElementsByTagName() - Web APIs
the getelementsbytagname method of document interface returns an htmlcollection of elements with the given tag name.
...the returned htmlcollection is live, meaning that it updates itself automatically to stay in sync with the dom tree without having to call document.getelementsbytagname() again.
... syntax var elements = document.getelementsbytagname(name); elements is a live htmlcollection (but see the note below) of found elements in the order they appear in the tree.
...And 8 more matches
SVGRadialGradientElement - Web APIs
the svgradialgradientelement interface corresponds to the <radialgradient> element.
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgelement</text></a><polyline points="481,25 491,20 491,30 481,25" stroke="#d4dde4" fill="none"/><line x1="491" y1="25" x2="499" y2="25" stroke="#d4dde4"/><line x1="499" y1="25" x2="499" y2="90" stroke="#d4dde4"/><line x1="499" y1="90" x2="482" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svggradientelement" target="_top"><rect x="301" y="65" width="180" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggradientelement</text></a><polyline points="301,89 291,84 291,94 301,89" stroke="#d4dde4" fill="none"/><line x1="291" y1="8...
...9" x2="261" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgradialgradientelement" target="_top"><rect x="21" y="65" width="240" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="141" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgradialgradientelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggradientelement.
...And 8 more matches
SVGRectElement - Web APIs
the svgrectelement interface provides access to the properties of <rect> elements, as well as methods to manipulate them.
...ill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="171" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggeometryelement</text></a><polyline points="81,89 71,84 71,94 81,89" stroke="#d4dde4" fill="none"/><line x1="71" y1="89" x2="41" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgrectelement" target="_top"><rect x="-99" y="65" width="140" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="-29" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgrectelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface...
... svgrectelement.x read only returns an svganimatedlength corresponding to the x attribute of the given <rect> element.
...And 8 more matches
Element.getElementsByTagName() - Web APIs
the element.getelementsbytagname() method returns a live htmlcollection of elements with the given tag name.
...therefore, there is no need to call element.getelementsbytagname() with the same element and arguments repeatedly if the dom changes in between calls.
... when called on an html element in an html document, getelementsbytagname lower-cases the argument before searching for it.
...And 7 more matches
HTMLOListElement - Web APIs
the htmlolistelement interface provides special properties (beyond those defined on the regular htmlelement interface it also has available to it by inheritance) for manipulating ordered list elements.
...andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmlolistelement" target="_top"><rect x="331" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlolistelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits pro...
... htmlolistelement.reversed is a boolean value reflecting the reversed and defining if the numbering is descending, that is its value is true, or ascending (false).
...And 7 more matches
SVGLinearGradientElement - Web APIs
the svglineargradientelement interface corresponds to the <lineargradient> element.
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgelement</text></a><polyline points="481,25 491,20 491,30 481,25" stroke="#d4dde4" fill="none"/><line x1="491" y1="25" x2="499" y2="25" stroke="#d4dde4"/><line x1="499" y1="25" x2="499" y2="90" stroke="#d4dde4"/><line x1="499" y1="90" x2="482" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svggradientelement" target="_top"><rect x="301" y="65" width="180" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggradientelement</text></a><polyline points="301,89 291,84 291,94 301,89" stroke="#d4dde4" fill="none"/><line x1="291" y1="8...
...9" x2="261" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svglineargradientelement" target="_top"><rect x="21" y="65" width="240" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="141" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svglineargradientelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svggradientelement.
...And 7 more matches
Document.getElementsByClassName() - Web APIs
the getelementsbyclassname method of document interface returns an array-like object of all child elements which have all of the given class name(s).
...you may also call getelementsbyclassname() on any element; it will return only elements which are descendants of the specified root element with the given class name(s).
... syntax var elements = document.getelementsbyclassname(names); // or: var elements = rootelement.getelementsbyclassname(names); elements is a live htmlcollection of found elements.
...And 6 more matches
Document.getElementsByName() - Web APIs
the getelementsbyname() method of the document object returns a nodelist collection of elements with a given name in the document.
... syntax var elements = document.getelementsbyname(name); elements is a live nodelist collection, meaning it automatically updates as new elements with the same name are added to/removed from the document.
... example <!doctype html> <html lang="en"> <title>example: using document.getelementsbyname</title> <input type="hidden" name="up"> <input type="hidden" name="down"> <script> var up_names = document.getelementsbyname("up"); console.log(up_names[0].tagname); // displays "input" </script> </html> notes the name attribute can only be applied in (x)html documents.
...And 6 more matches
Element.getElementsByClassName() - Web APIs
the element method getelementsbyclassname() returns a live htmlcollection which contains every descendant element which has the specified class name or names.
... the method getelementsbyclassname() on the document interface works essentially the same way, except it acts on the entire document, starting at the document root.
... syntax var elements = element.getelementsbyclassname(names); parameters names a domstring containing one or more class names to match on, separated by whitespace.
...And 6 more matches
HTMLSelectElement.add() - Web APIs
the htmlselectelement.add() method adds an element to the collection of option elements for this select element.
... exceptions a domerror of the type hierarchyrequesterror if the item passed to the method is an ancestor of the htmlselectelement.
... append to an existing collection var sel = document.getelementbyid("existinglist"); var opt = document.createelement("option"); opt.value = "3"; opt.text = "option: value 3"; sel.add(opt, null); /* takes the existing following select object: <select id="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> and changes it to: <select id="existinglist"> <option value="1">...
...And 6 more matches
JS_SetElement
syntax /* added in spidermonkey 31 */ bool js_setelement(jscontext *cx, js::handleobject obj, uint32_t index, js::handlevalue v); bool js_setelement(jscontext *cx, js::handleobject obj, uint32_t index, js::handleobject v); bool js_setelement(jscontext *cx, js::handleobject obj, uint32_t index, js::handlestring v); bool js_setelement(jscontext *cx, js::handleobject obj, uint32_t index, int32_t v); bool js_setelement(jscontext *cx, js::handleobject obj, uint32_t index, uint32_t v); bool js_setelement(jscontext *cx, js::handleobject obj, uint32_t index, double v); /* obsolete since jsapi 29 */ bool js_setelement(jscontext *cx, js::handleobjec...
...js_setelement ordinarily leaves *vp unchanged, but a jsclass.addproperty hook or non-default setter may modify it.
... obsolete since jsapi 29 description js_setelement assigns a value to a numeric property of an object.
...And 5 more matches
Document.getElementsByTagNameNS() - Web APIs
syntax elements = document.getelementsbytagnamens(namespace, name) elements is a live nodelist (but see the note below) of found elements in the order they appear in the tree.
...see the note in browser compatibility section in element.getelementsbytagnamens for details.
... example in the following example getelementsbytagnamens starts from a particular parent element, and searches topdown recursively through the dom from that parent element, looking for child elements matching the tag name parameter.
...And 5 more matches
Element.insertAdjacentElement() - Web APIs
the insertadjacentelement() method of the element interface inserts a given element node at a given position relative to the element it is invoked upon.
... syntax targetelement.insertadjacentelement(position, element); parameters position a domstring representing the position relative to the targetelement; must match (case-insensitively) one of the following strings: 'beforebegin': before the targetelement itself.
... 'afterbegin': just inside the targetelement, before its first child.
...And 5 more matches
HTMLInputElement.setSelectionRange() - Web APIs
the htmlinputelement.setselectionrange() method sets the start and end positions of the current text selection in an <input> or <textarea> element.
... this method updates the htmlinputelement.selectionstart, selectionend, and selectiondirection properties in one call.
... note that accordingly to the whatwg forms spec selectionstart, selectionend properties and setselectionrange method apply only to inputs of types text, search, url, tel and password.
...And 5 more matches
HTMLUListElement - Web APIs
the htmlulistelement interface provides special properties (beyond those defined on the regular htmlelement interface it also has available to it by inheritance) for manipulating unordered list elements.
...andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmlulistelement" target="_top"><rect x="331" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlulistelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits pro...
... htmlulistelement.type is a domstring value reflecting the type and defining the kind of marker to be used to display.
...And 5 more matches
SVGForeignObjectElement - Web APIs
the svgforeignobjectelement interface provides access to the properties of <foreignobject> elements, as well as methods to manipulate them.
...ke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggraphicselement</text></a><polyline points="301,89 291,84 291,94 301,89" stroke="#d4dde4" fill="none"/><line x1="291" y1="89" x2="261" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgforeignobjectelement" target="_top"><rect x="31" y="65" width="230" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="146" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgforeignobjectelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this i...
... svgforeignobjectelement.x read only an svganimatedlength corresponding to the x attribute of the given <foreignobject> element.
...And 5 more matches
Debug.writeln - Archive of obsolete content
the debug.writeln function sends strings to the script debugger, followed by a newline character.
... syntax debug.writeln([str1 [, str2 [, ...
... remarks the debug.writeln function sends strings, followed by a newline character, to the immediate window of the microsoft script debugger at run time.
...And 4 more matches
ByteLengthQueuingStrategy - Web APIs
the bytelengthqueuingstrategy interface of the the streams api provides a built-in byte length queuing strategy that can be used when constructing streams.
... constructor bytelengthqueuingstrategy() creates a new bytelengthqueuingstrategy object instance.
... methods bytelengthqueuingstrategy.size() returns the given chunk’s bytelength property.
...And 4 more matches
HTMLBaseFontElement - Web APIs
the htmlbasefontelement interface provides special properties (beyond the regular htmlelement interface it also has available to it by inheritance) for manipulating <basefont> elements.
...this latest specification requires that this element implements htmlunknownelement rather than htmlbasefontelement.
... htmlbasefontelement.color is a domstring representing the text color using either a named color or a color specified in the hexadecimal #rrggbb format.
...And 4 more matches
HTMLDListElement - Web APIs
the htmldlistelement interface provides special properties (beyond those of the regular htmlelement interface it also has available to it by inheritance) for manipulating definition list (<dl>) elements.
...andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmldlistelement" target="_top"><rect x="331" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmldlistelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits pro...
... htmldlistelement.compact is a boolean indicating that spacing between list items should be reduced.
...And 4 more matches
SVGFEOffsetElement - Web APIs
the svgfeoffsetelement interface corresponds to the <feoffset> element.
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgelement</text></a><polyline points="481,25 491,20 491,30 481,25" stroke="#d4dde4" fill="none"/><line x1="491" y1="25" x2="499" y2="25" stroke="#d4dde4"/><line x1="499" y1="25" x2="499" y2="90" stroke="#d4dde4"/><line x1="499" y1="90" x2="482" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgfeoffsetelement" target="_top"><rect x="301" y="65" width="180" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfeoffsetelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this inter...
... svgfeoffsetelement.in1 read only an svganimatedstring corresponding to the in attribute of the given element.
...And 4 more matches
SVGFEPointLightElement - Web APIs
the svgfepointlightelement interface corresponds to the <fepointlight> element.
...e mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgelement</text></a><polyline points="481,25 491,20 491,30 481,25" stroke="#d4dde4" fill="none"/><line x1="491" y1="25" x2="499" y2="25" stroke="#d4dde4"/><line x1="499" y1="25" x2="499" y2="90" stroke="#d4dde4"/><line x1="499" y1="90" x2="482" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgfepointlightelement" target="_top"><rect x="261" y="65" width="220" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="371" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfepointlightelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this i...
... svgfepointlightelement.x read only an svganimatednumber corresponding to the x attribute of the given element.
...And 4 more matches
SVGGradientElement - Web APIs
the svggradient interface is a base interface used by svglineargradientelement and svgradialgradientelement.
...ndale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgelement</text></a><polyline points="481,25 491,20 491,30 481,25" stroke="#d4dde4" fill="none"/><line x1="491" y1="25" x2="499" y2="25" stroke="#d4dde4"/><line x1="499" y1="25" x2="499" y2="90" stroke="#d4dde4"/><line x1="499" y1="90" x2="482" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svggradientelement" target="_top"><rect x="301" y="65" width="180" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggradientelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constants na...
... svggradientelement.gradientunits read only returns an svganimatedenumeration corresponding to the gradientunits attribute on the given element.
...And 4 more matches
Element.getElementsByTagNameNS() - Web APIs
the element.getelementsbytagnamens() method returns a live htmlcollection of elements with the given tag name belonging to the given namespace.
... it is similar to document.getelementsbytagnamens, except that its search is restricted to descendants of the specified element.
... syntax elements = element.getelementsbytagnamens(namespaceuri, localname) elements is a live htmlcollection of found elements in the order they appear in the tree.
...And 3 more matches
HTMLSelectElement.remove() - Web APIs
the htmlselectelement.remove() method removes the element at the specified index from the options collection for this select element.
... example var sel = document.getelementbyid("existinglist"); sel.remove(1); /* takes the existing following select object: <select id="existinglist" name="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> <option value="3">option: value 3</option> </select> and changes it to: <select id="existinglist" name="existinglist"> <option value="1">option: value 1</option> <option value="3">option: value 3</option> </select> */ specifications specification status comment html living standardthe defi...
...nition of 'htmlselectelement.remove()' in that specification.
...And 3 more matches
HTMLSelectElement.type - Web APIs
the htmlselectelement.type read-only property returns the form control's type.
... syntax var str = selectelt.type; the possible values are: "select-multiple" if multiple values can be selected.
... example switch (select.type) { case 'select-multiple': // multiple values may be selected break; case 'select-one': // only one value may be selected break; default: // non-standard value (or this isn't a select element) } specifications specification status comment html living standardthe definition of 'htmlselectelement' in that specification.
...And 3 more matches
HTMLSlotElement - Web APIs
the htmlslotelement interface of the shadow dom api enables access to the name and assigned nodes of an html <slot> element.
... properties htmlslotelement.name domstring: can be used to get and set the slot's name.
... methods htmlslotelement.assignednodes() returns a sequence of the nodes assigned to this slot, and if the flatten option is set to true, the assigned nodes of any other slots that are descendants of this slot.
...And 3 more matches
NonDocumentTypeChildNode.nextElementSibling - Web APIs
the nondocumenttypechildnode.nextelementsibling read-only property returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.
... syntax var nextnode = elementnodereference.nextelementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <script type="text/javascript"> var el = document.getelementbyid('div-01').nextelementsibling; console.log('siblings of div-01:'); while (el) { console.log(el.nodename); el = el.nextelementsibling; } </script> this example outputs the following into the console when it loads: siblings of div-01: div script polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can be used to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("nextelementsibling" in document.documentelement)){ object.defineproperty(elemen...
...t.prototype, "nextelementsibling", { get: function(){ var e = this.nextsibling; while(e && 1 !== e.nodetype) e = e.nextsibling; return e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/nextelementsibling/nextelementsibling.md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('nextelementsibling')) { return; } object.defineproperty(item, 'nextelementsibling', { configurable: true, enumerable: true, get: function () { var el = this; while (el = el.nextsibling) { if (el.nodetype === 1) { return el; } } return...
...And 3 more matches
SVGFEDistantLightElement - Web APIs
the svgfedistantlightelement interface corresponds to the <fedistantlight> element.
...mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgelement</text></a><polyline points="481,25 491,20 491,30 481,25" stroke="#d4dde4" fill="none"/><line x1="491" y1="25" x2="499" y2="25" stroke="#d4dde4"/><line x1="499" y1="25" x2="499" y2="90" stroke="#d4dde4"/><line x1="499" y1="90" x2="482" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgfedistantlightelement" target="_top"><rect x="241" y="65" width="240" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="361" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfedistantlightelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this...
... svgfedistantlightelement.azimuth read only an svganimatednumber corresponding to the azimuth attribute of the given element.
...And 3 more matches
JS_GetElement
syntax bool js_getelement(jscontext *cx, js::handleobject obj, uint32_t index, js::mutablehandlevalue vp); name type description cx jscontext * the context in which to perform the property lookup.
... description js_getelement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index.
... if the element exists, js_getelement sets *vp to the element's current value.
...And 2 more matches
CanvasRenderingContext2D.createLinearGradient() - Web APIs
the canvasrenderingcontext2d.createlineargradient() method of the canvas 2d api creates a gradient along the line connecting two given coordinates.
... syntax canvasgradient ctx.createlineargradient(x0, y0, x1, y1); the createlineargradient() method is specified by four parameters defining the start and end points of the gradient line.
... examples filling a rectangle with a linear gradient this example initializes a linear gradient using the createlineargradient() method.
...And 2 more matches
Document.rootElement - Web APIs
document.rootelement returns the element that is the root element of the document if it is an <svg> element, otherwise null.
... it is deprecated in favor of document.documentelement, which returns the root element for all documents.
... syntax const element = document.rootelement notes if the document is a non-empty svg document, then the rootelement will be an svgsvgelement, identical to the documentelement.
...And 2 more matches
Document.writeln() - Web APIs
WebAPIDocumentwriteln
syntax document.writeln(line); parameters line is string containing a line of text.
... example document.writeln("<p>enter password:</p>"); notes document.writeln is the same as document.write but adds a newline.
... note: document.writeln (like document.write) does not work in xhtml documents (you'll get a "operation is not supported" (ns_error_dom_not_supported_err) error on the error console).
...And 2 more matches
HTMLDataListElement - Web APIs
the htmldatalistelement interface provides special properties (beyond the htmlelement object interface it also has available to it by inheritance) to manipulate <datalist> elements and their content.
...ale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlelement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#d4dde4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#d4dde4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#d4dde4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/htmldatalistelement" target="_top"><rect x="301" y="65" width="190" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="396" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmldatalistelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits ...
...properties from its parent, htmlelement htmldatalistelement.options read only is a htmlcollection representing a collection of the contained option elements.
...And 2 more matches
HTMLFrameSetElement - Web APIs
the htmlframesetelement interface provides special properties (beyond those of the regular htmlelement interface they also inherit) for manipulating <frameset> elements.
... htmlframesetelement.cols is a domstring structured as a comma-seperated list specifing the width of each column inside a frameset.
... htmlframesetelement.rows is a domstring structured as a comma-seperated list specifing the height of each column inside a frameset.
...And 2 more matches
HTMLSelectElement.selectedOptions - Web APIs
the read-only htmlselectelement property selectedoptions contains a list of the <option> elements contained within the <select> element that are currently selected.
... syntax var selectedcollection = htmlselectelement.selectedoptions; value an htmlcollection which lists every currently selected htmloptionelement which is either a child of the htmlselectelement or of an htmloptgroupelement within the <select> element.
... javascript the javascript code that establishes the event handler for the button, as well as the event handler itself, looks like this: let orderbutton = document.getelementbyid("order"); let itemlist = document.getelementbyid("foods"); let outputbox = document.getelementbyid("output"); orderbutton.addeventlistener("click", function() { let collection = itemlist.selectedoptions; let output = ""; for (let i=0; i<collection.length; i++) { if (output === "") { output = "your order for the following items has been placed: "; } output += col...
...And 2 more matches
ParentNode.firstElementChild - Web APIs
the parentnode.firstelementchild read-only property returns the object's first child element, or null if there are no child elements.
...in this case, firstelementchild moved to parentnode.
... syntax var element = node.firstelementchild; example <ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> var foo = document.getelementbyid('foo'); // yields: first (1) console.log(foo.firstelementchild.textcontent); </script> polyfill for ie8, ie9 and safari // overwrites native 'firstelementchild' prototype.
...And 2 more matches
ParentNode.lastElementChild - Web APIs
the parentnode.lastelementchild read-only property returns the object's last child element or null if there are no child elements.
...in this case, lastelementchild moved to parentnode.
... syntax const element = node.lastelementchild example <ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> const foo = document.getelementbyid('foo'); console.log(foo.lastelementchild.textcontent); // logs: third (3) </script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari.
...And 2 more matches
SVGScriptElement - Web APIs
the svgscriptelement interface corresponds to the svg <script> element.
...,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgelement</text></a><polyline points="481,25 491,20 491,30 481,25" stroke="#d4dde4" fill="none"/><line x1="491" y1="25" x2="499" y2="25" stroke="#d4dde4"/><line x1="499" y1="25" x2="499" y2="90" stroke="#d4dde4"/><line x1="499" y1="90" x2="482" y2="90" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgscriptelement" target="_top"><rect x="321" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="401" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgscriptelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties svgscripte...
... svgscriptelement.crossorigin read only a domstring corresponding to the crossorigin attribute of the given <script> element.
...And 2 more matches
SVGTextElement - Web APIs
the svgtextelement interface corresponds to the <text> elements.
...roke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggraphicselement</text></a><polyline points="301,89 291,84 291,94 301,89" stroke="#d4dde4" fill="none"/><line x1="291" y1="89" x2="261" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgtextcontentelement" target="_top"><rect x="51" y="65" width="210" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="156" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextcontentelement</text></a><polyline points="51,89 41,84 41,94 51,89" stroke="#d4dde4" fill="none"/><line x1="41" y1="89" ...
...d4dde4" stroke-width="2px" /><text x="-114" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextpositioningelement</text></a><polyline points="-239,89 -249,84 -249,94 -239,89" stroke="#d4dde4" fill="none"/><line x1="-249" y1="89" x2="-279" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgtextelement" target="_top"><rect x="-419" y="65" width="140" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="-349" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interfa...
...And 2 more matches
Document.documentElement - Web APIs
document.documentelement returns the element that is the root element of the document (for example, the <html> element for html documents).
... syntax const element = document.documentelement example const rootelement = document.documentelement; const firsttier = rootelement.childnodes; // firsttier is a nodelist of the direct children of the root element // such as <head> and <body> for (const child of firsttier) { // do something with each direct child of the root element } notes for any non-empty html document, documentelement will always be an <html> element.
... for any non-empty xml document, documentelement will always be whatever element is the root element of the document.
... specifications specification status comment domthe definition of 'document.documentelement' in that specification.
HTMLScriptElement.referrerPolicy - Web APIs
the referrerpolicy property of the htmlscriptelement interface reflects the html referrerpolicy of the <script> element and fetches made by that script, defining which referrer is sent when fetching the resource.
... syntax refstr = scriptelem.referrerpolicy; scriptelem.referrerpolicy = refstr; value a domstring; one of the following: no-referrer the referer header will be omitted entirely.
... examples var scriptelem = document.createelement("script"); scriptelem.src = "/"; scriptelem.referrerpolicy = "unsafe-url"; document.body.appendchild(script); specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
... html living standardthe definition of 'htmlscriptelement: referrerpolicy' in that specification.
HTMLSelectElement.disabled - Web APIs
the htmlselectelement.disabled is a boolean that reflects the disabled html attribute, which indicates whether the control is disabled.
... syntax edit aselectelement.disabled = abool; example html <label> allow drinks?
... <input id="allow-drinks" type="checkbox"/> </label> <label for="drink-select">drink selection:</label> <select id="drink-select" disabled> <option value="1">water</option> <option value="2">beer</option> <option value="3">pepsi</option> <option value="4">whisky</option> </select> javascript var allowdrinkscheckbox = document.getelementbyid("allow-drinks"); var drinkselect = document.getelementbyid("drink-select"); allowdrinkscheckbox.addeventlistener("change", function(event) { if (event.target.checked) { drinkselect.disabled = false; } else { drinkselect.disabled = true; } }, false); result specifications specification status comment html living standardthe definition of 'disabled' in that specification.
... living standard html5the definition of 'htmlselectelement' in that specification.
HTMLSelectElement.form - Web APIs
the htmlselectelement.form read-only property returns a htmlformelement representing the form that this element is associated with.
... syntax edit aform = aselectelement.form.selectname; example html <form action="http://www.google.com/search" method="get"> <label>google: <input type="search" name="q"></label> <input type="submit" value="search..."> </form> javascript a property available on all form elements, "type" returns the type of the calling form element.
...the below code gives all select elements in a particular form a css class of "selectclass": <script type="text/javascript"> var form_element = document.getelementbyid('subscribe_form'); var vist = form_element.style; if (vist.display=='' || vist.display=='none') { vist.display = 'block'; } else { vist.display = 'none'; } </script> specifications specification status comment html living standardthe definition of 'form' in that specification.
... living standard html5the definition of 'htmlselectelement' in that specification.
HTMLSelectElement.item() - Web APIs
the htmlselectelement.item() method returns the element corresponding to the htmloptionelement whose position in the options list corresponds to the index given in the parameter, or null if there are none.
... in javascript, using the array bracket syntax with an unsigned long, like selectelt[index] is equivalent to selectelt.nameditem(index).
... examples html <form> <select id="myformcontrol" type="textarea"> <option id="o1">opt 1</option> <option id="o2">opt 2</option> </select> </form> javascript // returns the htmloptionelement representing #o2 elem1 = document.forms[0]['myformcontrol'][1]; specifications specification status comment html living standardthe definition of 'htmlselectelement.item()' in that specification.
... html5the definition of 'htmlselectelement.item()' in that specification.
HTMLSelectElement.namedItem() - Web APIs
the htmlselectelement.nameditem() method returns the htmloptionelement corresponding to the htmloptionelement whose name or id match the specified name, or null if no option matches.
... in javascript, using the array bracket syntax with a string, like selectelt["value"] is equivalent to selectelt.nameditem("value").
... example html <form> <select id="myformcontrol"> <option id="o1">opt 1</option> <option id="o2">opt 2</option> </select> </form> javascript elem1 = document.forms[0]['myformcontrol']['o1']; // returns the htmloptionelement representing #o1 specifications specification status comment html living standardthe definition of 'htmlselectelement.nameditem()' in that specification.
... html5the definition of 'htmlselectelement.nameditem()' in that specification.
HTMLSelectElement.setCustomValidity() - Web APIs
the htmlselectelement.setcustomvalidity() method sets the custom validity message for the selection element to the specified message.
... syntax selectelt.setcustomvalidity(string); parameters string is the domstring containing the error message.
... specifications specification status comment html living standardthe definition of 'htmlselectelement.setcustomvalidity()' in that specification.
... html5the definition of 'htmlselectelement.setcustomvalidity()' in that specification.
SVGSetElement - Web APIs
the svgsetelement interface corresponds to the <set> element.
...fff" stroke="#d4dde4" stroke-width="2px" /><text x="386" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svganimationelement</text></a><polyline points="291,89 281,84 281,94 291,89" stroke="#d4dde4" fill="none"/><line x1="281" y1="89" x2="251" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgsetelement" target="_top"><rect x="121" y="65" width="130" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="186" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgsetelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface ...
... specifications specification status comment svg animations level 2the definition of 'svgsetelement' in that specification.
... editor's draft no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgsetelement' in that specification.
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementtt
the obsolete html teletype text element (<tt>) creates inline text which is presented using the user agent's default monospace font face.
... this element was created for the purpose of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer.
... <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 overriding the default font you can override the browser's default font—if the browser permits you to do so, which it isn't required to do—using css: css tt { font-family: "lucida console", "menlo", "monaco", "courier", monospace; } html <p>ent...
...er 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.
DataView.prototype.byteLength - JavaScript
the bytelength accessor property represents the length (in bytes) of this view from the start of its arraybuffer or sharedarraybuffer.
... description the bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property.
...if the dataview is not specifying an offset or a bytelength, the bytelength of the referenced arraybuffer or sharedarraybuffer will be returned.
... examples using the bytelength property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.bytelength; // 8 (matches the bytelength of the buffer) var dataview2 = new dataview(buffer, 1, 5); dataview2.bytelength; // 5 (as specified when constructing the dataview) var dataview3 = new dataview(buffer, 2); dataview3.bytelength; // 6 (due to the offset of the constructed dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.bytelength' in that specification.
Intel Power Gadget
intel power gadget provides real-time graphs of various power-related measures and estimates, all taken from the intel rapl msrs.
... intel power gadget can also log these results to a file.
...unfortunately, the gecko profiler takes 1000 samples per second on desktop and is cpu intensive and so is likely to skew the rapl estimates significantly, so the api integration was removed.
ByteLengthQueuingStrategy.size() - Web APIs
the size() method of the bytelengthqueuingstrategy interface returns the given chunk’s bytelength property.
... syntax var size = bytelengthqueuingstrategy.size(chunk); parameters chunk a chunk of data being passed through the stream.
... examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ...
HTMLContentElement - Web APIs
the htmlcontentelement interface represents a <content> html element, which is used in shadow dom.
... htmlcontentelement.select is a domstring that reflects the select html attribute.
... htmlcontentelement.getdistributednodes() returns a static nodelist of the distributed nodes associated with this <content> element.
HTMLFontElement - Web APIs
htmlfontelement.color is a domstring that reflects the color html attribute, containing either a named color or a color specified in the hexadecimal #rrggbb format.
... htmlfontelement.face is a domstring that reflects the face html attribute, containing a comma-separated list of one or more font names.
... htmlfontelement.size is a domstring that reflects the size html attribute, containing either a font size number ranging from 1 to 7 or a relative size to the size attribute of the <basefont> element, for example -2 or +1.
HTMLInputElement.mozGetFileNameArray() - Web APIs
the htmlinputelement.mozgetfilenamearray() method returns an array of the names of the files that were selected by the user on an html input element.
... syntax inputelement.mozgetfilenamearray(alength, afilenames); parameters alength if specified, will receive the number of file names in the returned array.
... example var numfiles = 0; var filearray = {}; inputelement.mozgetfilenamearray(numfiles, filearray); ...
HTMLInputElement.mozSetFileNameArray() - Web APIs
the htmlinputelement.mozsetfilenamearray() method sets the names of the files that selected on an html input element.
... syntax inputelement.mozsetfilenamearray(afilenames, alength); parameters afilenames is the array of file names to apply to the element.
... example var filearray = {"/foo/bar.txt", "/foo/foosball.txt"}; inputelement.mozsetfilenamearray(filearray, filearray.length); ...
HTMLInputElement.select() - Web APIs
the htmlinputelement.select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
... html <input type="text" id="text-box" size="20" value="hello world!"> <button onclick="selecttext()">select text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.select(); } result notes calling element.select() will not necessarily focus the input, so it is often used with htmlelement.focus().
... in browsers where it is not supported, it is possible to replace it with a call to htmlinputelement.setselectionrange() with parameters 0 and the input's value length: <input onclick="this.select();" value="sample text" /> <!-- equivalent to --> <input onclick="this.setselectionrange(0, this.value.length);" value="sample text" /> specifications specification status comment html living standardthe definition of 'select' in that specification.
HTMLInputElement.setRangeText() - Web APIs
the htmlinputelement.setrangetext() method replaces a range of text in an <input> or <textarea> element with a new string.
... html <input type="text" id="text-box" size="30" value="this text has not been updated."> <button onclick="selecttext()">update text</button> javascript function selecttext() { const input = document.getelementbyid('text-box'); input.focus(); input.setrangetext('already', 14, 17, 'select'); } result specifications specification status comment html living standardthe definition of 'htmlinputelement.setselectionrange()' in that specification.
... living standard no change html5the definition of 'htmlinputelement.setselectionrange()' in that specification.
HTMLInputElement.stepDown() - Web APIs
the htmlinputelement.stepdown([n]) method decrements the value of a numeric type of <input> element by the value of the step attribute or up to n multiples of the step attribute if a number is passed as the parameter.
... htmlinputelement.stepdown() decrements the value by (step * n), where n defaults to 1 if not specified.
...by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="decrementer" min="-2" max="15"> </label> </p> <input type="button" value="decrement" id="thebutton"> javascript /* make the button call the function */ let button = document.getelementbyid('thebutton'); button.addeventlistener('click', function() { stepondown();} ); function stepondown() { let input = document.getelementbyid('thenumber'); let val = document.getelementbyid('decrementer').value; if (val) { /* increment with a parameter */ input.stepdown(val); } else { /* or without a parameter.
HTMLInputElement.webkitEntries - Web APIs
the read-only webkitentries property of the htmlinputelement interface contains an array of file system entries (as objects based on filesystementry) representing files and/or directories selected by the user using an <input> element of type file, but only if that selection was made using drag-and-drop: selecting a file in the dialog will leave the property empty (bug 1326031).
... syntax var entries = htmlinputelement.webkitentries; value an array of objects based on filesystementry, each representing one file which is selected in the <input> element.
... html <input id="files" type="file" multiple> javascript document.getelementbyid("files").addeventlistener("change", function(event) { event.target.webkitentries.foreach(function(entry) { /* do stuff with the entry */ }); }); each time a change event occurs, this code iterates over the selected files, obtaining their filesystementry-based objects and acting on them.
HTMLInputElement.webkitdirectory - Web APIs
the htmlinputelement.webkitdirectory is a property that reflects the webkitdirectory html attribute and indicates that the <input> element should let the user select directories instead of files.
... syntax htmlinputelement.webkitdirectory = boolvalue value a boolean; true if the <input> element should allow picking only directories or false if only files should be selectable.
... html content <input type="file" id="filepicker" name="filelist" webkitdirectory multiple /> <ul id="listing"></ul> javascript content document.getelementbyid("filepicker").addeventlistener("change", function(event) { let output = document.getelementbyid("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createelement("li"); item.innerhtml = files[i].webkitrelativepath; output.appendchild(item); }; }, false); result specifications specification status c...
HTMLObjectElement.setCustomValidity - Web APIs
the setcustomvalidity() method of the htmlobjectelement interface sets a custom validity message for the element.
... syntax htmlobjectelement.setcustomvalidity(message); parameters error the message to use for validity errors.
... function validate(inputid) { var input = document.getelementbyid(inputid); var validitystate_object = input.validity; if (validitystate_object.valuemissing) { input.setcustomvalidity('you gotta fill this out, yo!'); input.reportvalidity(); } else if (input.rangeunderflow) { input.setcustomvalidity('we need a higher number!'); input.reportvalidity(); } else if (input.rangeoverflow) { input.setcustomvalidity('thats too high!'); input.reportvalidity(); } else { input.s...
HTMLObjectElement.typeMustMatch - Web APIs
the htmlobjectelement.typemustmatch property is a boolean that reflects the typemustmatch attribute of the <object> element.
... it indicates if the resource linked by it must match the mime type given by htmlobjectelement.type in order for this resource to be used.
... syntax var mustmatch = obj.typemustmatch; obj.typemustmatch = mustmatch; example html <object id="obj" data="move.swf" type="application/x-shockwave-flash" typemustmatch></object> javascript let obj = document.getelementbyid('obj'); console.log(obj.typemustmatch); specifications specification status comment html5the definition of 'htmlobjectelement' in that specification.
HTMLObjectElement.willValidate - Web APIs
the willvalidate read-only property of the htmlobjectelement interface returns a boolean that indicates whether the element is a candidate for constraint validation.
... always false for htmlobjectelement objects.
... syntax var boolean = htmlobjectelement.willvalidate; value a boolean.
HTMLSelectElement.autofocus - Web APIs
the htmlselectelement.autofocus property is a boolean that reflects the autofocus html attribute, which indicates whether the associated <select> element will get input focus when the page loads, unless the user overrides it.
... setting this property doesn't set the focus to the associated <select> element: it merely tells the browser to focus to it when the element is inserted in the document.
... syntaxedit abool = aselectelement.autofocus; // get the value of autofocus aselectelement.autofocus = abool; // set the value of autofocus example html <select id="myselect" autofocus> <option>option 1</option> <option>option 2</option> </select> javascript // check if the autofocus attribute on the <select> var hasautofocus = document.getelementbyid('myselect').autofocus; specifications specification status comment html living standardthe definition of 'autofocus' in that specification.
HTMLSelectElement.checkValidity() - Web APIs
the htmlselectelement.checkvalidity() method checks whether the element has any constraints and whether it satisfies them.
... syntax var result = selectelt.checkvalidity(); specifications specification status comment html living standardthe definition of 'htmlselectelement.checkvalidity()' in that specification.
... html5the definition of 'htmlselectelement.checkvalidity()' in that specification.
HTMLSelectElement.selectedIndex - Web APIs
the htmlselectelement.selectedindex is a long that reflects the index of the first or last selected <option> element, depending on the value of multiple.
... syntax var index = selectelem.selectedindex; selectelem.selectedindex = index; example html <p id="p">selectedindex: 0</p> <select id="select"> <option selected>option a</option> <option>option b</option> <option>option c</option> <option>option d</option> <option>option e</option> </select> javascript var selectelem = document.getelementbyid('select') var pelem = document.getelementbyid('p') // when a new <option> is selected selectelem.addeventlistener('change', function() { var index = selectelem.selectedindex; // add that data to the <p> pelem.innerhtml = 'selectedindex: ' + index; }) specifications specification status comment html living standardthe definition of 'htmlselectelemen...
... html5the definition of 'htmlselectelement' in that specification.
Node.parentElement - Web APIs
the node.parentelement read-only property returns the dom node's parent element, or null if the node either has no parent, or its parent isn't a dom element.
... syntax parentelement = node.parentelement parentelement is the parent element of the current node.
... example if (node.parentelement) { node.parentelement.style.color = "red"; } specifications specification status comment domthe definition of 'parentelement' in that specification.
targetElement - Web APIs
the svganimationelement.targetelement property refers to the element which is being animated.
... syntax var targetelement = someelement.targetelement; specifications specification status comment svg animations level 2the definition of 'svganimationelement.targetelement' in that specification.
... scalable vector graphics (svg) 1.1 (second edition)the definition of 'svganimationelement.targetelement' in that specification.
SVGFontElement - Web APIs
the svgfontelement interface corresponds to the <font> elements.
... <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/svgfontelement" target="_top"><rect x="1" y="1" width="140" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="71" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfontelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface has...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontelement' in that specification.
SVGFontFaceFormatElement - Web APIs
the svgfontfaceformatelement interface corresponds to the <font-face-format> elements.
... <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 23.333333333333332%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 140" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/svgfontfaceformatelement" target="_top"><rect x="1" y="1" width="240" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="121" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgfontfaceformatelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this in...
... specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'svgfontfaceformatelement' in that specification.
SyntaxError: identifier starts immediately after numeric literal - JavaScript
the javascript exception "identifier starts immediately after numeric literal" occurs when an identifier started with a digit.
... message syntaxerror: unexpected identifier after numeric literal (edge) syntaxerror: identifier starts immediately after numeric literal (firefox) syntaxerror: unexpected number (chrome) error type syntaxerror what went wrong?
...the following fails: var 1life = 'foo'; // syntaxerror: identifier starts immediately after numeric literal var foo = 1life; // syntaxerror: identifier starts immediately after numeric literal alert(1.foo); // syntaxerror: identifier starts immediately after numeric literal you will need to rename your variable to avoid the leading number.
ArrayBuffer.prototype.byteLength - JavaScript
the bytelength accessor property represents the length of an arraybuffer in bytes.
... description the bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property.
... examples using bytelength var buffer = new arraybuffer(8); buffer.bytelength; // 8 specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.bytelength' in that specification.
SharedArrayBuffer.prototype.byteLength - JavaScript
the bytelength accessor property represents the length of an sharedarraybuffer in bytes.
... description the bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property.
... examples using bytelength var sab = new sharedarraybuffer(1024); sab.bytelength; // 1024 specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.bytelength' in that specification.
TypedArray.prototype.byteLength - JavaScript
the bytelength accessor property represents the length (in bytes) of a typed array.
... description the bytelength property is an accessor property whose set accessor function is undefined, meaning that you can only read this property.
... examples using the bytelength property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.bytelength; // 8 (matches the bytelength of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.bytelength; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.bytelength; // 6 (due to the offset of the constructed uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.bytelength' in that specification.
Telnet - MDN Web Docs Glossary: Definitions of Web-related terms
telnet is a command line tool and an underlying tcp/ip protocol for accessing remote computers.
... learn more telnet on wikipedia ...
HTMLFontElement.color - Web APIs
the obsolete htmlfontelement.color property is a domstring that reflects the color html attribute, containing either a named color or a color specified in the hexadecimal #rrggbb format.
...ame color string nameofcolor (case insensitive) green green green valid hex color string in rgb format: #rrggbb #008000 rgb using decimal values rgb(x,x,x) (x in 0-255 range) rgb(0,128,0) syntax colorstring = fontobj.color; fontobj.color = colorstring; examples // assumes there is <font id="f"> element in the html var f = document.getelementbyid("f"); f.color = "green"; specifications the <font> tag is not supported in html5 and as a result neither is <font>.color.
HTMLFontElement.face - Web APIs
the obsolete htmlfontelement.face property is a domstring that reflects the face html attribute, containing a comma-separated list of one or more font names.
...must follow one of the following html microsyntax: microsyntax description examples list of one or more valid font family names a list of font names, that have to be present on the local system courier,verdana syntax facestring = fontobj.face; fontobj.face = facestring; examples // assumes there is <font id="f"> element in the html var f = document.getelementbyid("f"); f.face = "arial"; specifications the <font> tag is not supported in html5 and as a result neither is <font>.face .
HTMLFontElement.size - Web APIs
the obsolete htmlfontelement.size property is a domstring that reflects the size html attribute.
... integer number in the range of 1-7 6 relative size string +x or -x, where x is the number relative to the value of the size attribute of the <basefont> element (the result should be in the same range of 1-7) +2 -1 syntax sizestring = fontobj.size; fontobj.size = sizestring; examples // assumes there is <font id="f"> element in the html var f = document.getelementbyid("f"); f.size = "6"; specifications the <font> tag is not supported in html5 and as a result neither is <font>.size .
HTMLInputElement.labels - Web APIs
the htmlinputelement.labels read-only property returns a nodelist of the <label> elements associated with the <input> element.
... example html <label id="label1" for="test">label 1</label> <input id="test"/> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const input = document.getelementbyid("test"); for(var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLInputElement.multiple - Web APIs
the htmlinputelement.multiple property indicates if an input can have more than one value.
... example // fileinput is a <input type=file multiple> let fileinput = document.getelementbyid('myfileinput'); if (fileinput.multiple == true) { for (let i = 0; i < fileinput.files.length; i++) { // loop fileinput.files } // only one file available } else { let file = fileinput.files.item(0); } ...
HTMLInputElement.stepUp() - Web APIs
the htmlinputelement.stepup() method increments the value of a numeric type of <input> element by the value of the step attribute, or the default step value if the step attribute is not explicitly set.
... by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="incrementer" min="0" max="25"> </label> </p> <input type="button" value="increment" id="thebutton"> javascript /* make the button call the function */ let button = document.getelementbyid('thebutton') button.addeventlistener('click', function() { steponup() }) function steponup() { let input = document.getelementbyid('thenumber') let val = document.getelementbyid('incrementer').value if (val) { /* increment with a parameter */ input.stepup(val) } else { /* or without a parameter.
HTMLObjectElement.checkValidity - Web APIs
the checkvalidity() method of the htmlobjectelement interface returns a boolean that always is true, because object objects are never candidates for constraint validation.
... syntax const valid = htmlobjectelement.checkvalidity(); parameters none.
HTMLObjectElement.contentDocument - Web APIs
the contentdocument read-only property of the htmlobjectelement interface returns a document representing the active document of the object element's nested browsing context, if any; otherwise null.
... syntax var document = htmlobjectelement.contentdocument; value a document.
HTMLObjectElement.contentWindow - Web APIs
the contentwindow read-only property of the htmlobjectelement interface returns a windowproxy representing the window proxy of the object element's nested browsing context, if any; otherwise null.
... syntax var windowproxy = htmlobjectelement.contentwindow; value a windowproxy.
HTMLObjectElement.data - Web APIs
the data property of the htmlobjectelement interface returns a domstring that reflects the data html attribute, specifying the address of a resource's data.
... syntax var data = htmlobjectelement.data; htmlobjectelement.data; value a domstring.
HTMLObjectElement.form - Web APIs
the form read-only property of the htmlobjectelement interface retuns a htmlformelement representing the object element's form owner, or null if there isn't one.
... syntax var htmlformelement = htmlobjectelement.form; value a htmlformelement.
HTMLObjectElement.height - Web APIs
the height property of the htmlobjectelement interface returns a domstring that reflects the height html attribute, specifying the displayed height of the resource in css pixels.
... syntax var string = htmlobjectelement.height; htmlobjectelement.height = string; value a domstring.
HTMLObjectElement.name - Web APIs
the name property of the htmlobjectelement interface returns a domstring that reflects the name html attribute, specifying the name of the browsing context.
... syntax var string = htmlobjectelement.name; htmlobjectelement.name = string; value a domstring.
HTMLObjectElement.type - Web APIs
the type property of the htmlobjectelement interface returns a domstring that reflects the type html attribute, specifying the mime type of the resource.
... syntax var string = htmlobjectelement.type htmlobjectelement.type = string; value a domstring.
HTMLObjectElement.useMap - Web APIs
the usemap property of the htmlobjectelement interface returns a domstring that reflects the usemap html attribute, specifying a <map> element to use.
... syntax var string = htmlobjectelement.usemap; htmlobjectelement.usemap = string; value a domstring.
HTMLObjectElement.validationMessage - Web APIs
the validationmessage read-only property of the htmlobjectelement interface returns a domstring representing a localized message that describes the validation constraints that the control does not satisfy (if any).
... syntax var string = htmlobjectelement.validationmessage; value a domstring.
HTMLObjectElement.validity - Web APIs
the validity read-only property of the htmlobjectelement interface returns a validitystate with the validity states that this element is in.
... syntax var validitystate = htmlobjectelement.validity; value a validitystate object.
HTMLObjectElement.width - Web APIs
the width property of the htmlobjectelement interface returns a domstring that reflects the width html attribute, specifying the displayed width of the resource in css pixels.
... syntax var string = htmlobjectelement.width; htmlobjectelement.width = string; value a domstring.
HTMLOutputElement.labels - Web APIs
the htmloutputelement.labels read-only property returns a nodelist of the <label> elements associated with the <output> element.
... example html <label id="label1" for="test">label 1</label> <output id="test">output</output> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const output = document.getelementbyid("test"); for(var i = 0; i < output.labels.length; i++) { console.log(output.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLSelectElement.labels - Web APIs
the htmlselectelement.labels read-only property returns a nodelist of the <label> elements associated with the <select> element.
... example html <label id="label1" for="test">label 1</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.labels.length; i++) { console.log(select.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLSelectElement.options - Web APIs
the htmlselectelement.options read-only property returns a htmloptionscollection of the <option> elements contained by the <select> element.
... example html <label for="test">label</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.options.length; i++) { console.log(select.options[i].label); // "option 1" and "option 2" } }); specifications specification status comment html living standardthe definition of 'options' in that specification.
HTMLSlotElement.assignedElements() - Web APIs
the assignedelements() property of the htmlslotelement interface returns a sequence of the elements assigned to this slot (and no other nodes).
... syntax var assignedelements = htmlslotelement.assignedelements(options) parameters options optional an object that sets options for the nodes to be returned.
HTMLSlotElement.assignedNodes() - Web APIs
the assignednodes() property of the htmlslotelement interface returns a sequence of the nodes assigned to this slot, and if the flatten option is set to true, the assigned nodes of any other slots that are descendants of this slot.
... syntax var assignednodes = htmlslotelement.assignednodes(options) parameters options optional an object that sets options for the nodes to be returned.
HTMLSlotElement.name - Web APIs
the name property of the htmlslotelement interface returns or sets the slot name.
... syntax var name = htmlslotelement.name htmlslotelement.name = name value a domstring.
HTMLSlotElement.assignedSlot - Web APIs
WebAPITextassignedSlot
the assignedslot property of the text interface returns the htmlslotelement object associated with the element.
... syntax var htmlslotelement = text.assignedslot value a htmlslotelement object.
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
absolutely positioned elements the alignment container is the positioned block, accounting for the offset values of top, left, bottom, and right.
... absolutely positioned elements the alignment container is the positioned block, accounting for the offset values of top, left, bottom, and right.
checkAdjacentElement - Archive of obsolete content
« xul reference home checkadjacentelement( dir ) return type: no return value deselects the currently selected radio button in the group and selects the one adjacent to it.
getElementsByAttribute - Archive of obsolete content
« xul reference home getelementsbyattribute( attrib, value ) return type: dom nodelist returns a nodelist of all the child elements of the element that have the attribute given by the first argument set to the value given by the second argument.
getElementsByAttributeNS - Archive of obsolete content
« xul reference home getelementsbyattributens(ns, attrib, value ) return type: dom nodelist returns an array of all the child elements of the element that have the attribute namespace given by the first argument, the attribute name given by the second argument, and the value given by the third argument.
dateLeadingZero - Archive of obsolete content
« xul reference dateleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the date when it is less than 10.
minuteLeadingZero - Archive of obsolete content
« xul reference minuteleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the minute when it is less than 10.
SMPTE (Society of Motion Picture and Television Engineers) - MDN Web Docs Glossary: Definitions of Web-related terms
the society of motion picture and television engineers (smpte) is the professional association of engineers and scientists that develop and define standards and technologies used to create, broadcast, store, and present entertainment media.
UpdateListener
an updatelistener receives messages from an update check for a single add-on, though it is possible to pass the same updatelistener to as many calls to findupdates() as you like.
Adding a new Telemetry probe
adding new telemetry probes is now documented in the mozilla source tree docs.
nsIAutoCompleteListener
xpfe/components/autocomplete/public/nsiautocompletelistener.idlscriptable this interface is deprecated.
HTMLContentElement.getDistributedNodes() - Web APIs
the htmlcontentelement.getdistributednodes() method returns a static nodelist of the distributed nodes associated with this <content> element.
HTMLContentElement.select - Web APIs
the htmlcontentelement.select property reflects the select attribute.
HTMLInputElement: invalid event - Web APIs
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.queryselector('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.
HTMLSlotElement: slotchange event - Web APIs
the slotchange event is fired on an htmlslotelement instance (<slot> element) when the node(s) contained in that slot change.
Index - Web APIs
WebAPIIndex
36 addresserrors.phone api, address, addresserrors, payment request, payment request api, phone, phone number, property, read-only, reference, telephone number, téléphone, validation, payment an object based on addresserrors includes a phone property when the address's phone property couldn't be validated.
...if no time is specified, then the sound stops playing immediately.
... 380 bytelengthqueuingstrategy api, bytelengthqueueingstrategy, experimental, interface, reference, streams the bytelengthqueuingstrategy interface of the the streams api provides a built-in byte length queuing strategy that can be used when constructing streams.
...And 188 more matches
Index - Archive of obsolete content
unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names.
... 206 rosetta c, dom, html, htmlscriptelement, javascript, non-javascript, programming languages no summary!
...the tool enables mozilla.org to be immediately notified of changes to the code that prevent mozilla from compiling and running (or compromise performance and footprint) so they can get someone to fix the problem or reverse the changes.
...And 30 more matches
Bytecode Descriptions
jsop::typeof and jsop::typeofexpr are the same except that--amazingly--jsop::typeof affects the behavior of an immediately preceding jsop::getname or jsop::getgname instruction!
...this is used for code like ++obj[index], which must do both a jsop::getelem and a jsop::setelem with the same property key.
...format: jof_atom, jof_prop, jof_propinit, jof_ic initelem, inithiddenelem stack: obj, id, val ⇒ obj define a data property on obj with property key id and value val.
...And 28 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
<input type="submit" name="submit"/> tel a control for entering a telephone number.
... displays a telephone keypad in some devices with dynamic keypads.
... <input type="tel" name="tel"/> html5 text the default value.
...And 26 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
not only does this make the code easier to read, it simplifies adding support for new clients: var elm = getelmbyid("myid"); function getelmbyid(aid){ var element = null; if (ismozilla || isie5) element = document.getelementbyid(aid); else if (isnetscape4) element = document.layers[aid]; else if (isie4) element = document.all[aid]; return element; } the above code still has the issue of browser sniffing, or detecting which browser the user is using.
...for example, rather than: if (ismozilla || isie5) you would use: if (document.getelementbyid) this would allow other browsers that support that w3c standard method, such as opera or safari, to work without any changes.
...conditionistrue : conditionisfalse; for example, to retrieve an element, you would use: function getelement(aid){ return (document.getelementbyid) ?
...And 22 more matches
Applying styles and colors - Web APIs
function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillstyle = 'rgb(' + math.floor(255 - 42.5 * i) + ', ' + math.floor(255 - 42.5 * j) + ', 0)'; ctx.fillrect(j * 25, i * 25, 25, 25); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); the result looks like this: screenshotlive s...
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.strokestyle = 'rgb(0, ' + math.floor(255 - 42.5 * i) + ', ' + math.floor(255 - 42.5 * j) + ')'; ctx.beginpath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, math.pi * 2, true); ctx.stroke(); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); the result looks like this: screenshotlive sample transparency in addition to drawing opaqu...
...by increasing the step count and in effect drawing more circles, the background would completely disappear from the center of the image.
...And 20 more matches
Multiple-column layout - Learn web development
cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet.
... curabitur vehicula tellus neque, ac ornare ex malesuada et.
...cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet.
...And 19 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
in vector images, they are used to model smooth curves that can be scaled indefinitely.
...not all http responses can be cached, these are the following constraints for an http response to be cached: 61 caldav caldav, glossary, infrastructure caldav (calendaring extensions to webdav) is a protocol standardized by the ietf and used to remotely access calendar data from a server.
...these tell a computer/software program what to do in a language which the computer understands.
...And 18 more matches
Introduction to CSS layout - Learn web development
cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet.
...curabitur vehicula tellus neque, ac ornare ex malesuada et.
... absolute positioning moves an element completely out of the page's normal layout flow, like it is sitting on its own separate layer.
...And 17 more matches
Floats - Learn web development
cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet.
...curabitur vehicula tellus neque, ac ornare ex malesuada et.
...cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet.
...And 14 more matches
Power profiling overview
this article covers important background information about power profiling, with an emphasis on intel processors used in desktop and laptop machines.
... intel processor basics processor layout the following diagram (from the intel power governor documentation) shows how machines using recent intel processors are constructed.
...these are part of the actual processor that you buy from intel.
...And 14 more matches
TypeScript support in Svelte - Learn web development
note that our application is fully functional and porting it to typescript is completely optional.
... repl unfortunately, typescript support is not yet available in the repl.
... steep learning curve: even though typescript is a superset of javascript and not a completely new language, there is a considerable learning curve, especially if you have no experience at all with static languages like java or c#.
...And 13 more matches
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
the content of the site tells the story of how technology affects our daily lives, especially in the realms of business, culture, and politics.
...i think that fact played a critical role in our team's willingness to try out something completely new.
... our engineering team actually needed the least convincing to convert over to a standards-based design, because they could also immediately envision the benefits to their workload and maintenance of the site.
...And 12 more matches
Index
many (if not most) of the operations performed by nss involve the use of x.509 certificates (often abbreviated as “cert”, unfortunately making it easy to confuse with the term “computer emergency response team“).
...a trust anchor is just another x.509 certificate that is already known and has been deliberately marked as trusted by a software vendor, administrators inside an organizational infrastructure, or the software user.
... because of nss's expectation to operate with an nss database, it's mandatory that you perform an initialization call, where you tell nss which database you will be using.
...And 12 more matches
JIT Optimization Strategies
optimization information is currently collected for the following operations: getproperty (obj.prop) setproperty (obj.prop = val) getelement (obj[elemname]) setelement (obj[elemname] = val) call (func(...)) at each operation site, ionmonkey tries a battery of strategies, from the most optimized but most restrictive to the least optimized but least restrictive.
... getelement getelem_typedobject attempts to optimized element accesses on array typed objects.
... getelem_dense attempts to optimize element accesses on densely packed array objects.
...And 12 more matches
window.location - Web APIs
WebAPIWindowlocation
example #6: using bookmarks without changing the hash property: <!doctype html> <html> <head> <meta charset="utf-8"/> <title>mdn example</title> <script> function shownode (onode) { document.documentelement.scrolltop = onode.offsettop; document.documentelement.scrollleft = onode.offsetleft; } function showbookmark (sbookmark, busehash) { if (arguments.length === 1 || busehash) { location.hash = sbookmark; return; } var obookmark = document.queryselector(sbookmark); if (obookmark) { shownode(obookmark); } } </script> <style> span.intlink { cursor: pointer; color: #0000ff; te...
...quisque in ante tellus, in placerat est.
...etiam congue, elit vitae egestas mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus.</p> <p>nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus.
...And 12 more matches
sslfnc.html
ssl_enable_fdx tells the ssl library whether the application will have two threads, one reading and one writing, or just one thread doing reads and writes alternately.
... ssl_v2_compatible_hello tells the ssl library whether or not to send ssl3 client hello messages in ssl2-compatible format.
... the ssl_enable_fdx option tells the ssl library whether the application will have two threads, one reading and one writing, or just one thread doing reads and writes alternately.
...And 11 more matches
Extension Versioning, Update and Compatibility - Archive of obsolete content
overriding compatibility checking for testing purposes you can tell the application to somewhat ignore compatibility checks when installing add-ons.
...the * actually represents an infinitely high number and so is really only sensibly used in the maxversion.
...ication the add-on is compatible with --> <em:targetapplication> <rdf:description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>1.5</em:minversion> <em:maxversion>2.0.0.*</em:maxversion> <!-- this is where this version of the add-on will be downloaded from --> <em:updatelink>https://www.mysite.com/foobar2.2.xpi</em:updatelink> <!-- a page describing what is new in this updated version --> <em:updateinfourl>http://www.mysite.com/updateinfo2.2.xhtml</em:updateinfourl> </rdf:description> </em:targetapplication> </rdf:description> </rdf:li> <rdf:li> <rdf:description> ...
...And 10 more matches
Positioning - Learn web development
an absolutely positioned element no longer exists in the normal document layout flow.
...so in this case, we are saying that the absolutely positioned element should sit 30px from the top of the "containing element", and 30px from the left.
... positioning contexts which element is the "containing element" of an absolutely positioned element?
...And 10 more matches
Index
MozillaTechXPCOMIndex
any time a new value is assigned into an nscomptr, the nscomptr automatically always releases its old referent, if any, and (unless you tell it you already have) addrefs the new.
...the following four sections tell the developer how to download and organize the gecko sdk and create a new project in which components like weblock can be created.
...however, with decode-on-draw, the set of decode notifications can come completely after the load notifications, and can come multiple times if the image is discardable.
...And 10 more matches
Key Values - Web APIs
(also known as suspend or sleep.) this turns off the display and puts the computer in a low power consumption mode, without completely powering off.
... tv control keys these key values represent buttons or keys present on television devices, or computers or phones which have tv support.
... keycode_tv_radio_service (232) "tvsatellite" satellite button.
...And 10 more matches
Color picker tool - CSS: Cascading Style Sheets
16px; position: absolute; opacity: 0; top: -10000px; left: 0; color: #777; float: left; transition: opacity 1s; } #zindex input { border: 1px solid #ddd; font-size: 16px; color: #777; } #zindex .ui-input-slider-info { width: 60px; } #zindex[data-active='true'] { top: 0; opacity: 1; } javascript content 'use strict'; var uicolorpicker = (function uicolorpicker() { function getelembyid(id) { return document.getelementbyid(id); } var subscribers = []; var pickers = []; /** * rgba color class * * hsv/hsb and hsl (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); ret...
...ue, subscribe : subscribe, unsubscribe : unsubscribe, setprecision : setprecision, setsensivity : setsensivity, getprecision : getprecision, createslider : createslider, }; })(); 'use strict'; window.addeventlistener("load", function() { colorpickertool.init(); }); var colorpickertool = (function colorpickertool() { /*========== get dom element by id ==========*/ function getelembyid(id) { return document.getelementbyid(id); } function allowdropevent(e) { e.preventdefault(); } /*========== make an element resizable relative to it's parent ==========*/ var uicomponent = (function uicomponent() { function makeresizable(elem, axis) { var valuex = 0; var valuey = 0; var action = 0; var resizestart = function resizestart(e) { e.stoppropagation...
....prototype.updatesaturation = function updatesaturation(color, value, steps) { var saturation = color.saturation + value * steps; if (saturation <= 0) { this.node.setattribute('data-hidden', 'true'); return; } this.node.removeattribute('data-hidden'); this.color.copy(color); this.color.setsaturation(saturation); this.updatebgcolor(); }; colorsample.prototype.updatelightness = function updatelightness(color, value, steps) { var lightness = color.lightness + value * steps; if (lightness <= 0) { this.node.setattribute('data-hidden', 'true'); return; } this.node.removeattribute('data-hidden'); this.color.copy(color); this.color.setlightness(lightness); this.updatebgcolor(); }; colorsample.prototype.updatebrightness = function up...
...And 10 more matches
widget - Archive of obsolete content
next, we write a content script that listens for click events on each icon and sends the corresponding message to the main add-on code: var play_button = document.getelementbyid("play-button"); play_button.onclick = function() { self.port.emit("play"); } var pause_button = document.getelementbyid("pause-button"); pause_button.onclick = function() { self.port.emit("pause"); } var stop_button = document.getelementbyid("stop-button"); stop_button.onclick = function() { self.port.emit("stop"); } we save this file in the add-on's data directory as "button-sc...
... first, in the content script, change self to addon, and wrap it in a function: function init() { var play_button = document.getelementbyid("play-button"); play_button.onclick = function() { addon.port.emit("play"); } var pause_button = document.getelementbyid("pause-button"); pause_button.onclick = function() { addon.port.emit("pause"); } var stop_button = document.getelementbyid("stop-button"); stop_button.onclick = function() { addon.port.emit("stop"); } } next, add a script tag to reference...
...the widget is immediately added to the add-on bar.
...And 9 more matches
jspage - Archive of obsolete content
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.queryselector)},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.queryselectorall)?6:5):4);},webkit:function(){return(navigator.taintenabled)?false:((browser.features.xpath)?((browser.features.query)?525:420):419); },gecko:function(){return(!document.getboxobjectfor&&window.mozinnerscreenx==null)?false:((document.getelementsbyclassname)?19:...
...ment.prototype=(browser.engine.webkit)?window["[[domelement.prototype]]"]:{}; }a.document.window=a;return $extend(a,window.prototype);},afterimplement:function(b,a){window[b]=window.prototype[b]=a;}});window.prototype={$family:{name:"window"}}; new window(window);var document=new native({name:"document",legacy:(browser.engine.trident)?null:window.document,initialize:function(a){$uid(a);a.head=a.getelementsbytagname("head")[0]; a.html=a.getelementsbytagname("html")[0];if(browser.engine.trident&&browser.engine.version<=4){$try(function(){a.execcommand("backgroundimagecache",false,true); });}if(browser.engine.trident){a.window.attachevent("onunload",function(){a.window.detachevent("onunload",arguments.callee);a.head=a.html=a.window=null; });}return $extend(a,document.prototype);},afterimplement:...
...{if(browser.engine.trident&&b){["name","type","checked"].each(function(c){if(!b[c]){return;}a+=" "+c+'="'+b[c]+'"'; if(c!="checked"){delete b[c];}});a="<"+a+">";}return document.id(this.createelement(a)).set(b);},newtextnode:function(a){return this.createtextnode(a); },getdocument:function(){return this;},getwindow:function(){return this.window;},id:(function(){var a={string:function(d,c,b){d=b.getelementbyid(d);return(d)?a.element(d,c):null; },element:function(b,e){$uid(b);if(!e&&!b.$family&&!(/^object|embed$/i).test(b.tagname)){var c=element.prototype;for(var d in c){b[d]=c[d];}}return b;},object:function(c,d,b){if(c.toelement){return a.element(c.toelement(b),d); }return null;}};a.textnode=a.whitespace=a.window=a.document=$arguments(0);return function(c,e,d){if(c&&c.$family&&c.uid){return c...
...And 9 more matches
Fundamental text and font styling - Learn web development
the css properties used to style text generally fall into two categories, which we'll look at separately in this article: font styles: properties that affect the font that is applied to the text, affecting what font is applied, how big it is, whether it is bold, italic, etc.
...truly a wonder of nature this urban predator — tommy the cat had many a story to tell.
...truly a wonder of nature this urban predator — tommy the cat had many a story to tell.
...And 9 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
remember that to tell svelte that a variable has changed, you have to assign it a new value.
...that's because svelte can't track object references, so we have to explicitly tell it that obj has changed by issuing an assignment.
... note: if foo is a top level variable, you can easily tell svelte to update obj whenever foo is changed with the following reactive statement: $: foo, obj = obj.
...And 9 more matches
DMD
for instance, on osx, you can run something like: dmd=1 /applications/firefox\ nightly.app/contents/macos/firefox you can tell it is working by going to about:memory and looking for "save dmd output".
... if you see the "opened" line, it tells you where the file was saved.
...this tells you how dmd was invoked, i.e.
...And 9 more matches
Signaling and video calling - Web APIs
note: if you try out the example on glitch, please note that any changes made to the code will immediately reset any connections.
... note: the onicecandidate event and createanswer() promise are both async calls which are handled separately.
...we specify the autoplay attribute, ensuring once the video starts arriving, it immediately plays.
...And 9 more matches
Enhanced Extension Installation - Archive of obsolete content
when changes are made to the extensions datasource - new items are installed, old items uninstalled, enabled or disabled, a .autoreg file is written to the profile directory as well, which tells the startup code that the system has been modified, so that it destroys the component registries, finishes pending transactions and regenerates metadata appropriately.
...if it is, a small set of metadata about it is written to the appropriate datasource (name, version, a flag to tell the system to properly install it on the next startup), and it is added to the appropriate type container.
... the system also writes a .autoreg file to the profile folder which tells the startup system that something has changed on the next restart.
...And 8 more matches
JXON - Archive of obsolete content
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ function createxml (oobjtree) { function loadobjtree (oparentel, oparentobj) { var vvalue, ochild; if (oparentobj.constructor === string || oparentobj.constructor === number || oparentobj.constructor === boolean) { oparentel.appendchild(onewdoc.createtextnode(oparentobj.tostring())); /* verbosity level is 0 or 1 */ if (oparentobj === oparentobj.valueof()) { return; } } else if (oparentobj.constructor === date) { oparentel.appendc...
...hild(onewdoc.createtextnode(oparentobj.togmtstring())); } for (var sname in oparentobj) { if (isfinite(sname)) { continue; } /* verbosity level is 0 */ vvalue = oparentobj[sname]; if (sname === "keyvalue") { if (vvalue !== null && vvalue !== true) { oparentel.appendchild(onewdoc.createtextnode(vvalue.constructor === date ?
... vvalue.togmtstring() : string(vvalue))); } } else if (sname === "keyattributes") { /* verbosity level is 3 */ for (var sattrib in vvalue) { oparentel.setattribute(sattrib, vvalue[sattrib]); } } else if (sname.charat(0) === "@") { oparentel.setattribute(sname.slice(1), vvalue); } else if (vvalue.constructor === array) { for (var nitem = 0; nitem < vvalue.length; nitem++) { ochild = onewdoc.createelement(sname); loadobjtree(ochild, vvalue[nitem]); oparentel.appendchild(ochild); } } else { ochild = onewdoc.createelement(sname); if (vvalue instanceof object) { loadobjtree(ochild, vvalue); } else if (vvalue !== null && vvalue !== true) { ochild.appendchild(onewdoc.crea...
...And 8 more matches
WAI-ARIA basics - Learn web development
if you are looking for a 3rd party javascript solution for rapid ui development, you should definitely consider the accessibility of its ui widgets as an important factor when making your choice.
...ideally, you should always use native html features to provide the semantics required by screenreaders to tell their users what is going on.
...and if for some reason your site is built using just <div>s, you should definitely include the aria roles to provide these much needed semantics!
...And 8 more matches
A first splash into JavaScript - Learn web development
previous overview: first steps next now you've learned something about the theory of javascript, and what you can do with it, we are going to give you a crash course in the basic features of javascript via a completely practical tutorial.
... you won't be expected to understand all of the code in detail immediately — we just want to introduce you to the high-level concepts for now, and give you an idea of how javascript (and other programming languages) work.
...we'll tell you if your guess was too high or too low.</p> <div class="form"> <label for="guessfield">enter a guess: </label><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> // ...
...And 8 more matches
Observer Notifications
profile-before-change-telemetry called to shut down telemetry, again separated to allow everything before this event to continue using it.
... topic subject data description chrome-document-global-created nsidomwindow null sent immediately after a chrome document window has been set up, but before any script code has been executed.
... content-document-global-created nsidomwindow origin sent immediately after a web content document window has been set up, but before any script code has been executed.
...And 8 more matches
Drawing shapes with canvas - Web APIs
rectangular shape example <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.fillrect(25, 25, 100, 100); ctx.clearrect(45, 45, 60, 60); ctx.strokerect(50, 50, 50, 50); } } this example's output is shown below.
... unlike the path functions we'll see in the next section, all three rectangle functions draw immediately to the canvas.
... note: when the current path is empty, such as immediately after calling beginpath(), or on a newly created canvas, the first path construction command is always treated as a moveto(), regardless of what it actually is.
...And 8 more matches
Document - Web APIs
WebAPIDocument
document.documentelementread only returns the element that is a direct child of the document.
... parentnode.firstelementchild read only returns the first node which is both a child of this parentnode and is also an element, or null if there is none.
... parentnode.lastelementchild read only returns the last node which is both a child of this parentnode and is an element, or null if there is none.
...And 8 more matches
PerformanceResourceTiming - Web APIs
performanceresourcetiming.workerstartread only returns a domhighrestimestamp immediately before dispatching the fetchevent if a service worker thread is already running, or immediately before starting the service worker thread if it is not already running.
... performanceresourcetiming.redirectendread only a domhighrestimestamp immediately after receiving the last byte of the response of the last redirect.
... performanceresourcetiming.fetchstartread only a domhighrestimestamp immediately before the browser starts to fetch the resource.
...And 8 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
unfortunately, some products can get confused by the vertical lines on other objects, such as list boxes, even though those lines are not blinking.
...even if you are visibly showing window focus on the correct window, you must also tell the operating system to focus this window before any other accessibility events get fired in it.
...these can be problematic, because the assistive technology has no way to tell whether the event came from your application or from windows.
...And 8 more matches
Cross-browser audio basics - Developer guides
</audio> you can grab the <audio> element like this: var myaudio = document.getelementbyid('my-audio'); alternatively, you can create a new element.
... play the play() method is used to tell the audio to play.
... myaudio.play(); pause the pause() method is used to tell the audio to pause.
...And 8 more matches
Namespaces crash course - SVG: Scalable Vector Graphics
versions of svg viewers prior to the release of firefox 1.5 unfortunately paid scant attention to namespaces, but they are essential to multi-xml dialect supporting user agents such as gecko-based browsers which must be very strict.
...in fact how does the user agent tell when xml content is something it knows about, and not just a meaningless xml file containing arbitrary element names unknown to it?
... contrary to popular opinion, the answer to this question is not "it can tell from the doctype declaration".
...And 8 more matches
From object to iframe — other embedding technologies - Learn web development
active learning: classic embedding uses in this article we are going to jump straight into an active learning section, to immediately give you a real idea of just what embedding technologies are useful for.
...t: 100px;"> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.queryselector('.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; sol...
...> <a href="https://udn.realityripple.com/docs/glossary"> fallback link for browsers that don't support iframes </a> </p> </iframe> this example includes the basic essentials needed to use an <iframe>: allowfullscreen if set, the <iframe> is able to be placed in fullscreen mode using the full screen api (somewhat beyond scope for this article.) frameborder if set to 1, this tells the browser to draw a border between this frame and other frames, which is the default behaviour.
...And 7 more matches
Using images - Web APIs
using images from the same page we can obtain a reference to images on the same page as the canvas by using one of: the document.images collection the document.getelementsbytagname() method if you know the id of the specific image you wish to use, you can use document.getelementbyid() to retrieve that specific image using images from other domains using the crossorigin attribute of an <img> element (reflected by the htmlimageelement.crossorigin property), you can request permission to load an image from another domain for use in your call to drawimage().
... using other canvas elements just as with normal images, we access other canvas elements using either the document.getelementsbytagname() or document.getelementbyid() method.
...data urls allow you to completely define an image as a base64 encoded string of characters directly in your code.
...And 7 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
example: creating an html table dynamically (sample1.html) html <input type="button" value="generate a table." onclick="generate_table()"> javascript function generate_table() { // get the reference for the body var body = document.getelementsbytagname("body")[0]; // creates a <table> element and a <tbody> element var tbl = document.createelement("table"); var tblbody = document.createelement("tbody"); // creating all cells for (var i = 0; i < 2; i++) { // creates a table row var row = document.createelement("tr"); for (var j = 0; j < 2; j++) { // create a <td> element and a text node, make the text...
... example: setting the background color of a paragraph getelementsbytagname(tagnamevalue) is a method available in any dom element or the root document element.
... html <body> <input type="button" value="set paragraph background color" onclick="set_background()"> <p>hi</p> <p>hello</p> </body> javascript function set_background() { // get a list of all the body elements (there will only be one), // and then select the zeroth (or first) such element mybody = document.getelementsbytagname("body")[0]; // now, get all the p elements that are descendants of the body mybodyelements = mybody.getelementsbytagname("p"); // get the second item of the list of p elements myp = mybodyelements[1]; myp.style.background = "rgb(255,0,0)"; } in this example, we set the myp variable to the dom object for the second p element inside the body: first, we get a list of...
...And 7 more matches
Box-shadow generator - CSS: Cascading Style Sheets
= function init() { var elem = document.queryselectorall('.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(){ boxshadow.init(); }); var boxshadow = (function boxshadow() { function getelembyid(id) { return document.getelementbyid(id); } /** * rgba color class */ function color() { this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log("typeof instance not color"); return; } this.r = obj.r; this.g = obj...
...ibers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(callback) { subscribers.indexof(callback); subscribers.splice(index, 1); } var notify = function notify(topic, value) { for (var i in subscribers[topic]) subscribers[topic][i](value); } var init = function init() { colorpicker = getelembyid("colorpicker"); hue_area = getelembyid("hue"); gradient_area = getelembyid("gradient"); alpha_area = getelembyid("alpha"); gradient_picker = getelembyid("gradient_picker"); hue_selector = getelembyid("hue_selector"); alpha_selector = getelembyid("alpha_selector"); output_color = getelembyid("output_color"); var elem = document.queryselectorall('#colorpicker .input...
...hue_area, updatehue); setmousetracking(alpha_area, updatealpha); } return { init : init, setcolor : setcolor, subscribe : subscribe, unsubscribe : unsubscribe } })(); /** * shadow dragging */ var previewmousetracking = (function drag() { var active = false; var lastx = 0; var lasty = 0; var subscribers = []; var init = function init(id) { var elem = getelembyid(id); elem.addeventlistener('mousedown', dragstart, false); document.addeventlistener('mouseup', dragend, false); } var dragstart = function dragstart(e) { if (e.button !== 0) return; active = true; lastx = e.clientx; lasty = e.clienty; document.addeventlistener('mousemove', mousedrag, false); } var dragend = function dragend(e) { if (e.button !== 0) ...
...And 7 more matches
position - CSS: Cascading Style Sheets
WebCSSposition
the margins of absolutely positioned boxes do not collapse with other margins.
... an absolutely positioned element is an element whose computed position value is absolute or fixed.
... most of the time, absolutely positioned elements that have height and width set to auto are sized so as to fit their contents.
...And 7 more matches
Media buffering, seeking, and time ranges - Developer guides
buffered the buffered attribute will tell us which parts of the media has been downloaded.
... it returns a timeranges object, which will tell us which chunks of media have been downloaded.
... this will work with <audio> or <video>; for now let's consider a simple audio example: <audio id="my-audio" controls src="music.mp3"> </audio> we can access these attributes like so: var myaudio = document.getelementbyid('my-audio'); var bufferedtimeranges = myaudio.buffered; timeranges object timeranges are a series of non-overlapping ranges of time, with start and stop times.
...And 7 more matches
Array.prototype.toLocaleString() - JavaScript
let firstelement be ?
... var firstelement = a[0]; // 6.
... if firstelement is undefined or null, then // a.let r be the empty string.
...And 7 more matches
Web audio codec guide - Web media technologies
additionally, webrtc implementations generally use a subset of these codecs for their encoding and decoding of media, and may support additional codecs as well, for optimal cross-platform support of video and audio conferencing, and to integrate better with legacy telecommunication solutions.
...c name container support aac advanced audio coding mp4, adts, 3gp alac apple lossless audio codec mp4, quicktime (mov) amr adaptive multi-rate 3gp flac free lossless audio codec mp4, ogg, flac g.711 pulse code modulation (pcm) of voice frequencies rtp / webrtc g.722 7 khz audio coding within 64 kbps (for telephony/voip) rtp / webrtc mp3 mpeg-1 audio layer iii mp4, adts, mpeg1, 3gp opus opus webm, mp4, ogg vorbis vorbis webm, ogg [1] when mpeg-1 audio layer iii codec data is stored in an mpeg file, and there is no video track on the file, the file is typically referred to as an mp3 file, even though it's still an mpeg format file.
...it was standardized in 1999 as part of the 3gpp audio standard used for both gsm and umts cellular telephony, and uses a multi-rate narrowband algorithm to encode audio frequencies at a telephony-grade quality level at around 7.4 kbps.
...And 7 more matches
page-mod - Archive of obsolete content
/lib/main.js: var tag = "p"; var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: data.url("element-getter.js"), onattach: function(worker) { worker.port.emit("getelements", tag); worker.port.on("gotelement", function(elementcontent) { console.log(elementcontent); }); } }); /data/element-getter.js: self.port.on("getelements", function(tag) { var elements = document.getelementsbytagname(tag); for (var i = 0; i < elements.length; i++) { self.port.emit("gotelement", elements[i].innerhtml); } }); when the user loads a document hosted ...
...it adds a listener to the getelements message.
...its event handler sends the getelements message to the content script, and then adds a listener to the gotelement message.
...And 6 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
many intelligent developers have been driven to the brink of insanity trying to build it for the first time.
... every extension must include an install.rdf file that tells firefox how to install it.
...use the dist_files variable in the makefile to tell make to copy the file into the extension directory and (optional) xpi file.
...And 6 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
note that the ticker is a completely separated component.
...note the following piece of code: function iframecallback(doc) { /* copies the data in the iframe to the main page */ mydata = doc.getelementbyid("mydata"); tickerdiv.innerhtml = mydata.innerhtml; } the callback is called with the parameter doc, which is a reference to the iframe's document).
...the following code snippet shows a simplified version of the logic that happens in the actual sample: // doc is the dom to the document returned articles=doc.getelementsbytagname("article"); for(i=0;i<articles.length;i++) { // acquiring the data from the dom...
...And 6 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
it's mission is to enable completely automatic configuration of mozilla's apps preferences based on users properties either retrieved from system environement variables or on an organisation ldap directory.
...// pref("general.config.obscure_value", 0); // for mcd .cfg files pref('general.config.filename', 'thunderbird.cfg'); // for mcd .cfg files it used to be in previous releases (up until 7.0) in /usr/lib/thunderbird-x.0/default/pref/autoconf.js the first pref just tells us that we won't encode the file (no more rotary 13 or 7 cf below), the second pref is the name of the file to be read: /usr/lib/thunderbird/thunderbird.cfg.
...please see //(german) http://interop.blog.de/2010/02/13/kapitel-1-ldap-anfragen-linux-ad-8001564/ //or search the net how to do it.
...And 6 more matches
Introduction to XUL - Archive of obsolete content
though the former term seems more concrete than the other, and therefore is not an exact replacement, no one is completely certain why we have both.
... mozilla applications will be built of "small" components like dialog buttons and mail inbox folders, which we collectively term "widgets." within a widget, drawing and user interactions are completely under control of the individual widget, and set when the widget was built.
... <html:script type="application/javascript"> // dialog initialization code function initwindow() { var checkbox = document.getelementbyid("remember"); if (checkbox) checkbox.checked = true; } </html:script> javascript can be referenced as in html documents: as onclick handlers and the like.
...And 6 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
unfortunately, no other browser supports web standards as completely as gecko.
...fortunately, other browsers such as opera (versions 7 & later) and to a lesser extent, internet explorer (versions 5.5 & later) also support the standards to a degree.
...unfortunately, the netscape 6 user agent string was not sufficiently generalizable due to it's use of the string netscape6 as a description of the vendor.
...And 6 more matches
Browser Feature Detection - Archive of obsolete content
00% 100% 100% / 100% 96% / 96% dom css 2 100% 98% 67% 71% / 83% 38% / 42% test results cross reference dom core level 1 support for properties/methods in document name firefox 1.5 ie 6 & 7 opera 8.54 - 9.01 document.doctype true true true document.implementation true true true document.documentelement true true true document.createelement() true true true document.createdocumentfragment() true true true document.createtextnode() true true true document.createcomment() true true true document.createcdatasection() true false true document.createprocessinginstruction() true false...
... true document.createattribute() true true true document.createentityreference()obsolete since gecko 7 (method present but only returns null: bug 9850) false false document.getelementsbytagname() true true true dom core level 2 support for properties/methods in document name firefox 1.5 ie 6 & 7 opera 8.54 - 9.01 document.doctype true true true document.implementation true true true document.documentelement true true true document.createelement() true true true document.createdocumentfragment() true true true document.createtextnode() true true true document.createcomment() true true tr...
...ue document.createcdatasection() true false true document.createprocessinginstruction() true false true document.createattribute() true true true document.createentityreference()obsolete since gecko 7 true false false document.getelementsbytagname() true true true document.importnode() true false true document.createelementns() true false true document.createattributens() true false true document.getelementsbytagnamens() true false true document.getelementbyid() true true true dom level 1 html support for properties/methods in document name firefox 1.5 ie 6 & 7 opera 8.54 - 9.01 ...
...And 6 more matches
Anatomy of a video game - Game development
this function does some work and also tells the browser to call itself next frame with window.requestanimationframe().
... but do not immediately assume animations require frame-by-frame control.
...for the first issue, if you want the main loop to just run and you do not need easy (direct) access to it, you could create it as an immediately-invoked function expression (iife).
...And 6 more matches
CSS and JavaScript accessibility best practices - Learn web development
objective: to gain familiarity with using css and javascript appropriately in your web documents to maximise accessibility and not detract from it.
... as an example, a screen reader user can't navigate a page via heading elements if the developer hasn't appropriately used heading elements to markup the content.
...something should definitely happen when states change, and you shouldn't get rid of the pointer cursor or the outline — both are very important accessibility aids for those using keyboard controls.
...And 6 more matches
HTML: A good basis for accessibility - Learn web development
objective: to gain familiarity with the features of html that have accessibility benefits and how to use them appropriately in your web documents.
...some abuses of html are due to legacy practices that have not been completely forgotten, and some are just plain ignorance.
...all rights reversed.</p> </td> </tr> </table> if you try to navigate this using a screen reader, it will probably tell you that there's a table to be looked at (although some screen readers can guess the difference between table layouts and data tables).
...And 6 more matches
HTML: A good basis for accessibility - Learn web development
objective: to gain familiarity with the features of html that have accessibility benefits and how to use them appropriately in your web documents.
...some abuses of html are due to legacy practices that have not been completely forgotten, and some are just plain ignorance.
...all rights reversed.</p> </td> </tr> </table> if you try to navigate this using a screen reader, it will probably tell you that there's a table to be looked at (although some screen readers can guess the difference between table layouts and data tables).
...And 6 more matches
Accessibility in React - Learn web development
unfortunately, these features are not very accessible to keyboard-only users.
... when we switch between templates in our <todo /> component, we completely remove the elements that were there before to replace them with something else.
... targeting our elements in order to focus on an element in our dom, we need to tell react which element we want to focus on and how to find it.
...And 6 more matches
Deployment and next steps - Learn web development
note that our application is fully functional and porting it to typescript is completely optional.
...as we saw earlier, this instruction tells svelte to compile our components and javascript files into a public/build/bundle.js file and all the css sections of our components into public/build/bundle.css.
... in the file package.json you can see that the dev and start scripts are just calling rollup: "scripts": { "build": "rollup -c", "dev": "rollup -c -w", "start": "sirv public" }, in the dev script we are passing the -w argument, which tells rollup to watch files and rebuild on changes.
...And 6 more matches
Eclipse CDT
set an initial heap space of 1 gb and max heap space of 5 gb, say, by modifying the values of the following two lines in eclipse.ini: -xms1g -xmx5g if you fail to increase these limits, then you will likely find that eclipse either hangs when it tries to index the mozilla source or else that the code intelligence is very broken after the indexing "completes".
...changes you make in one editor will be immediately reflected in the other.
...alternately, you can jump to the definition of the symbol under the cursor by pressing f3.
...And 6 more matches
Displaying Places information using views
getservice(ci.nsinavhistoryservice); var query = histserv.getnewquery(); query.searchterms = "mozilla"; query.onlybookmarked = true; var opts = histserv.getnewqueryoptions(); opts.querytype = opts.query_type_bookmarks; var uri = histserv.queriestoquerystring([query], 1, opts); var tree = document.getelementbyid("mytree"); tree.place = uri; these two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and property.
...for example, by setting a column's id to "title", you tell the view to display the title of the nsinavhistoryresultnode of each row in that column.
... to put it in terms of javascript, say you have a variable named treeview that references your places tree view: var treeview = document.getelementbyid("myplacestreeview"); points 1 and 2 apply to this variable.
...And 6 more matches
Mozilla DOM Hacking Guide
for example, when we ask for |document.getelementbyid("myid");|, xpconnect will find that |document| is a property of the window object, so it will look on the interface nsidomwindow, and it will find the getdocument() method.
...so xpconnect will then try to find a method named getelementbyid() on the nsidomdocument interface.
...fortunately, xpconnect provides us with a way to make our class available as an array in javascript.
...And 6 more matches
Investigating leaks using DMD heap scan mode
known edges: 0x7f08975a24c0 [fragmentorelement (xhtml) head https://www.example.com] --[mattrsandchildren[i]]--> 0x7f0882fe3230 0x7f08967e7b20 [js object (htmlscriptelement)] --[unwrapdomobject(obj)]--> 0x7f0882fe3230 the first two lines mean that the script element 0x7f0882fe3230 contains a strong reference to the eventlistenermanager 0x7f0899b4e550.
...most of the time, the actual chain is not important, because the cycle collector can only tell us about what went right.
...it tells us that there is 1 unknown edge, and 2 known edges.
...And 6 more matches
NS_ConvertUTF16toUTF8
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...ffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
NS_LossyConvertUTF16toASCII
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...ffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
nsAdoptingCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...ffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
nsCAutoString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...nt print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
nsCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...ffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
nsDependentCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...ffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
nsFixedCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...ffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
nsPromiseFlatCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...ffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
nsXPIDLCString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...ffset print32 acount print32 find(const char*, prbool, print32, print32) const - source parameters char* astring prbool aignorecase print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 6 more matches
nsIHTMLEditor
in astring atag, in nsidomnode aparentnode, in astring aanonclass, in boolean aiscreatedhidden); nsidomelement createelementwithdefaults(in astring atagname); void decreasefontsize(); void dodrag(in nsidomevent aevent); void getalignment(out boolean amixed, out short aalign); astring getbackgroundcolorstate(out boolean amixed); nsidomelement getelementorparentbytagname(in astring atagname, in nsidomnode anode); astring getfontcolorstate(out boolean amixed); astring getfontfacestate(out boolean amixed); astring getheadcontentsashtml(); astring gethighlightcolorstate(out boolean amixed); void getindentstate(out boolean acanindent, out boolean acanoutdent); void getinlineproperty(in nsiato...
... amixed, out boolean aol, out boolean aul, out boolean adl); astring getparagraphstate(out boolean amixed); nsidomelement getselectedelement(in astring atagname); nsidomelement getselectioncontainer(); void ignorespuriousdragevent(in boolean aignorespuriousdragevent); void increasefontsize(); void indent(in astring aindent); void insertelementatselection(in nsidomelement aelement, in boolean adeleteselection); void insertfromdrop(in nsidomevent aevent); void inserthtml(in astring ainputstring); void inserthtmlwithcontext(in astring ainputstring, in astring acontextstr, in astring ainfostr, in astring aflavor, in nsidomdocument asourcedoc, in nsidomnode adestinationnode, in long adestinationoffset, in boo...
...perties(); void removedefaultproperty(in nsiatom aproperty, in astring aattribute, in astring avalue); void removeinlineproperty(in nsiatom aproperty, in astring aattribute); void removeinsertionlistener(in nsicontentfilter infilter); void removelist(in astring alisttype); void replaceheadcontentswithhtml(in astring asourcetoinsert); void selectelement(in nsidomelement aelement); void setbackgroundcolor(in astring acolor); void setbodyattribute(in astring aattr, in astring avalue); void setcaretafterelement(in nsidomelement aelement); void setcssinlineproperty(in nsiatom aproperty, in astring aattribute, in astring avalue); void setdocumenttitle(in astring atitle); void setinlinepropert...
...And 6 more matches
Examples of web and XML development using the DOM - Web APIs
example 1: height and width the following example shows the use of the height and width properties alongside images of varying dimensions: <!doctype html> <html lang="en"> <head> <title>width/height example</title> <script> function init() { var arrimages = new array(3); arrimages[0] = document.getelementbyid("image1"); arrimages[1] = document.getelementbyid("image2"); arrimages[2] = document.getelementbyid("image3"); var objoutput = document.getelementbyid("output"); var strhtml = "<ul>"; for (var i = 0; i < arrimages.length; i++) { strhtml += "<li>image" + (i+1) + ": height=" + arrimages[i].height + ", width=" + arrimages[i].width + ", sty...
...ight, width, but style="height: 50px; width: 500px;" <img id="image3" src="https://udn.realityripple.com/samples/d2/8ba7141ed1.gif" style="height: 50px; width: 500px;"> </p> <div id="output"> </div> </body> </html> example 2: image attributes <!doctype html> <html lang="en"> <head> <title>modifying an image border</title> <script> function setborderwidth(width) { document.getelementbyid("img1").style.borderwidth = width + "px"; } </script> </head> <body> <p> <img id="img1" src="image1.gif" style="border: 5px solid green;" width="100" height="100" alt="border test"> </p> <form name="formname"> <input type="button" value="make border 20px-wide" onclick="setborderwidth(20);" /> <input type="button" value="make border 5px-wide" onclick="setbord...
... <!doctype html> <html lang="en"> <head> <title>changing color and font-size example</title> <script> function changetext() { var p = document.getelementbyid("pid"); p.style.color = "blue" p.style.fontsize = "18pt" } </script> </head> <body> <p id="pid" onclick="window.location.href = 'http://www.cnn.com/';">linker</p> <form> <p><input value="rec" type="button" onclick="changetext();" /></p> </form> </body> </html> example 4: using stylesheets the stylesheets property on the document object returns a list of the stylesheets that ...
...And 6 more matches
Element - Web APIs
WebAPIElement
nondocumenttypechildnode.nextelementsibling read only is an element, the element immediately following the given one in the tree, or null if there's no sibling node.
... nondocumenttypechildnode.previouselementsibling read only is a element, the element immediately preceding the given one in the tree, or null if there is no sibling element.
... slotable.assignedslotread only returns a htmlslotelement representing the <slot> the node is inserted in.
...And 6 more matches
Using files from web applications - Web APIs
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", handlefiles, false); function handlefiles() { const filelist = this.files; /* now you can work with the file list */ } getting information about selected file(s) the filelist object provided by the dom lists all of the files selected by the user, each specified as a file object.
...let soutput = nbytes + " bytes"; // optional code for multiples approximation const amultiples = ["kib", "mib", "gib", "tib", "pib", "eib", "zib", "yib"]; for (nmultiple = 0, napprox = nbytes / 1024; napprox > 1; napprox /= 1024, nmultiple++) { soutput = napprox.tofixed(3) + " " + amultiples[nmultiple] + " (" + nbytes + " bytes)"; } // end of optional code document.getelementbyid("filenum").innerhtml = nfiles; document.getelementbyid("filesize").innerhtml = soutput; } document.getelementbyid("uploadinput").addeventlistener("change", updatesize, false); </script> </body> </html> using hidden file input elements using the click() method you can hide the admittedly ugly file <input> element and present your own interface for opening the file picker and...
...And 6 more matches
PerformanceNavigationTiming - Web APIs
the interface also supports the following properties: performancenavigationtiming.domcomplete read only a domhighrestimestamp representing a time value equal to the time immediately before the browser sets the current document readiness of the current document to complete.
... performancenavigationtiming.domcontentloadedeventend read only a domhighrestimestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes.
... performancenavigationtiming.domcontentloadedeventstart read only a domhighrestimestamp representing the time value equal to the time immediately before the user agent fires the domcontentloaded event at the current document.
...And 6 more matches
Border-image generator - CSS: Cascading Style Sheets
pic = node.getattribute('data-topic'); var label = node.getattribute('data-label'); var selected = node.getattribute('data-selected') | 0; var select = document.createelement('div'); var list = document.createelement('div'); var uval = 0; var option = null; var option_value = null; list.classname = 'ui-dropdown-list'; select.classname = 'ui-dropdown-select'; while (node.firstelementchild !== null) { option = node.firstelementchild; option_value = option.getattribute('data-value'); if (option_value === null) option.setattribute('data-value', uval); list.appendchild(node.firstelementchild); uval++; } node.appendchild(select); node.appendchild(list); select.onclick = this.toggle.bind(this); list.onclick = this.updatevalue.bind(this); docu...
...function init() { var elem = document.queryselectorall('.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); var subject; var preview; var guidelines = []; var positions = ['top', 'right', 'bottom', 'left']; var makedraggable = function makedraggable(elem) { var offsettop; var offsetleft; elem.setattribute('data-draggable', 'true'); var dragstart = function dragstart(e) { if (e.target.getattribute('data-draggable') !== 'true' || e.
...gsource.width * scale / 100 | 0; var h = imgsource.height * scale / 100 | 0; subject.style.width = w + 'px'; subject.style.height = h + 'px'; for (var i = 0; i < positions.length; i++) guidelines['slice-' + positions[i]].updateguidelinepos(); }; var getscale = function getscale() { return scale/100; }; var togglegallery = function togglegallery() { var gallery = getelembyid('image-gallery'); var button = getelembyid('toggle-gallery'); var state = 1; button.addeventlistener('click', function() { state = 1 ^ state; if (state === 0) { gallery.setattribute('data-collapsed', 'true'); button.setattribute('data-action', 'show'); } else { gallery.removeattribute('data-collapsed'); button.setattribute('data-action', 'hide')...
...And 6 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
grid and absolutely positioned elements grid interacts with absolutely positioned elements, which can be useful if you want to position an item inside a grid or grid area.
... the specification defines the behavior when a grid container is a containing block and a parent of the absolutely positioned item.
... a grid container as containing block to make the grid container a containing block you need to add the position property to the container with a value of relative, just as you would make a containing block for any other absolutely positioned items.
...And 6 more matches
Constraint validation - Developer guides
validation-related attributes in addition to the type attribute described above, the following attributes are used to describe basic constraints: attribute input types supporting the attribute possible values constraint description associated violation pattern text, search, url, tel, email, password a javascript regular expression (compiled with the ecmascript 5 global, ignorecase, and multiline flags disabled) the value must match the pattern.
...tion date, month, week a valid date datetime, datetime-local, time a valid date and time max range, number a valid number the value must be less than or equal to the value rangeoverflow constraint violation date, month, week a valid date datetime, datetime-local, time a valid date and time required text, search, url, tel, email, password, date, datetime, datetime-local, month, week, time, number, checkbox, radio, file; also on the <select> and <textarea> elements none as it is a boolean attribute: its presence means true, its absence means false there must be a value (if set).
... stepmismatch constraint violation month an integer number of months week an integer number of weeks datetime, datetime-local, time an integer number of seconds range, number an integer minlength text, search, url, tel, email, password; also on the <textarea> element an integer length the number of characters (code points) must not be less than the value of the attribute, if non-empty.
...And 6 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
fortunately, adding color to your html is actually really easy to do, and you can add color to nearly anything.
... let colorpicker = document.getelementbyid("colorpicker"); let box = document.getelementbyid("box"); let output = document.getelementbyid("output"); box.style.bordercolor = colorpicker.value; colorpicker.addeventlistener("input", function(event) { box.style.bordercolor = event.target.value; }, false); colorpicker.addeventlistener("change", function(event) { output.innertext = "color set to " + colorpicker.value + "."; }, f...
...fortunately, there are tools available that can help you.
...And 6 more matches
Web video codec guide - Web media technologies
resolution (width and height) higher resolution video, presented in the same screen size, will typically be able to more accurately portray the original scene, barring effects introduced during compression.
...motion picture film is typically 24 frames per second, while standard definition television is about 30 frames per second (slightly less, but close enough) and high definition television is between 24 and 60 frames per second.
...it's a motion compensation based codec that is widely used today for all sorts of media, including broadcast television, rtp videoconferencing, and as the video codec for blu-ray discs.
...And 6 more matches
Example - SVG: Scalable Vector Graphics
this is done completely in w3c standards–xhtml, svg, and javascript–no flash or any vendor-specific extensions.
... </p> <p> this is done completely in w3c standards–xhtml, svg and javascript–no flash or any vendor specific extensions. currently, this will work in mozilla firefox version 1.5 and above.
... </p> <div> (c) 2006 <a id='emailme' href='#'>nick johnson</a> <script type='text/javascript'> <![cdata[ // foil spam bots var email = '@riovia.net'; email ='nick' + email; document.getelementbyid('emailme').href = 'mailto:'+email; ]]> </script> this software is free for you to use in any way whatsoever, and comes with no warranty at all.
...And 6 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
in order to host your add-on with mozilla it is crucial to minimize or completely eliminate eval use in order to receive a positive review and have your add-on made public.
... jsonp, which really is just another script tag containing generated, remotely retrieved code, is generally not secure.
... other extensions might do something similar, trying to hook the same functions, but a little different, ending up with completely broken code.
...And 5 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
459 checkadjacentelement xul methods, xul reference no summary!
... 483 getelementsbyattribute xul methods, xul reference no summary!
... 484 getelementsbyattributens xul methods, xul reference no summary!
...And 5 more matches
Document Object Model - Archive of obsolete content
retrieving elements the most common method to retrieve an element in a document is to give the element an id attribute and the use the document's getelementbyid() method.
...for example, we could get the state of a check box by using the code below: var state = document.getelementbyid('casecheck').checked; the value casecheck corresponds to the id of the case sensitive checkbox.
... function dofind(){ var meter = document.getelementbyid('progmeter'); meter.hidden = false; } this function first gets a reference to the progress meter using its id, progmeter.
...And 5 more matches
splitter - Archive of obsolete content
before when the grippy is clicked, the element immediately before the splitter in the same parent is collapsed so that its width or height is 0.
... after when the grippy is clicked, the element immediately after the splitter in the same parent is collapsed so that its width or height is 0.
... both either the element immediately before the splitter, or the element immediately after the splitter can be collapsed, if the size of that element would fall below the minimum size due to the position of the splitter.
...And 5 more matches
RDF in Mozilla FAQ - Archive of obsolete content
unfortunately, not here!
...var ds = rdf.getdatasource("http://www.mozilla.org/some-rdf-file.rdf"); // note that ds will load asynchronously, so assertions will not // be immediately available alternatively, you can create one directly using the xpcom component manager, as the following code fragment illustrates: // create an rdf/xml datasource using the xpcom component manager var ds = components .classes["@mozilla.org/rdf/datasource;1?name=xml-datasource"] .createinstance(components.interfaces.nsirdfdatasource); // the nsirdfremotedatasource interface has the inte...
...by setting // ablocking to true, we could force it to be synchronous, but this // is generally a bad idea, because your ui will completely lock up!
...And 5 more matches
Client-side form validation - Learn web development
if it gets to the server and is then rejected, a noticeable delay is caused by a round trip to the server and then back to the client-side to tell the user to fix their data.
...this validation is completely customizable, but you need to create it all (or use a library).
... the constraint validation api most browsers support the constraint validation api, which consists of a set of methods and properties available on the following form element dom interfaces: htmlbuttonelement (represents a <button> element) htmlfieldsetelement (represents a <fieldset> element) htmlinputelement (represents an <input> element) htmloutputelement (represents an <output> element) htmlselectelement (represents a <select> element) htmltextareaelement (represents a <textarea> element) the constraint validation api makes the following properties available on the above elements.
...And 5 more matches
HTML text fundamentals - Learn web development
ied to a fish.</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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.queryselector('.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; solutione...
... semantics are relied on everywhere around us—we rely on previous experience to tell us what the function of an everyday object is; when we see something, we know what its function will be.
...s bread hummus</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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.queryselector('.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; solutione...
...And 5 more matches
Creating reftest-based unit tests
this is why manual tests tend to get longer, include more steps and ultimately become a long list that actually tests a lot of things.
...it is completely trivial, but so what.
... more investigation into whether this will work is definitely warranted.
...And 5 more matches
HTML parser threading
the backing nsstringbuffers are thread-safely refcounted appropriately when the nsstring goes away.
...this method returns immediately if another invocation of it is already on the call stack (nested event loop case).
...parser termination is checked before each tree op for an early return, because, unfortunately, gecko expects parsers to be able to terminate immediately.
...And 5 more matches
An overview of NSS Internals
many (if not most) of the operations performed by nss involve the use of x.509 certificates (often abbreviated as “cert”, unfortunately making it easy to confuse with the term “computer emergency response team“).
...a trust anchor is just another x.509 certificate that is already known and has been deliberately marked as trusted by a software vendor, administrators inside an organizational infrastructure, or the software user.
... because of nss's expectation to operate with an nss database, it's mandatory that you perform an initialization call, where you tell nss which database you will be using.
...And 5 more matches
nss tech note1
the type is undefined as it is completely dependent on the content of the decoder templates.† this typically points to a struct that is described (or partially described) by the templates.
... decoder templates : the sec_asn1template structure tells the decoder what to do with the input data.
...this 32-bit field tells the decoder what to do with a particular component within the input data.
...And 5 more matches
nsIDocShell
method overview void addsessionstorage(in nsiprincipal principal, in nsidomstorage storage); void addstate(in nsivariant adata, in domstring atitle, in domstring aurl, in boolean areplace); void beginrestore(in nsicontentviewer viewer, in boolean top); void createaboutblankcontentviewer(in nsiprincipal aprincipal); void createloadinfo(out nsidocshellloadinfo loadinfo); void detacheditorfromwindow(); violates the xpcom interface guidelines void finishrestore(); void firepagehidenotification(in boolean isunload); native code only!
... canvashasfocus boolean tells the docshell whether the canvas should have focus.
... hasfocus boolean tells the docshell that it now has focus or has lost focus.
...And 5 more matches
nsIRadioInterfaceLayer
dom/system/gonk/nsiradiointerfacelayer.idlscriptable used to implement the interface between the telephony api and the radio hardware in a telephone.
... 1.0 66 introduced gecko 12.0 inherits from: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) implemented by: @mozilla.org/telephony/system-worker-manager;1.
... to create an instance, use: var radiointerfacelayer = components.classes["@mozilla.org/telephony/system-worker-manager;1"] .getservice(components.interfaces.nsiinterfacerequestor) .createinstance(components.interfaces.nsiradiointerfacelayer); method overview void answercall(in unsigned long callindex); void deactivatedatacall(in domstring cid, in domstring reason); void dial(in domstring number); void enumeratecalls(in nsiriltelephonycallback callback); void getdatacalllist(); unsigned short getnumberofmessagesfortext(in domstring text); void hangup(in unsigned long callindex); void registercallback(in nsiriltelephonycallback callback); void registerdatacallcallback(in nsirildatacallback callback); void rejectcall(in u...
...And 5 more matches
Getting Started Guide
each interface is (at least conceptually) separately `reference counted'.
...the caller can then hold onto the reference indefinitely, calling release when it no longer needs it.
...as described above, and unless you tell it otherwise, an nscomptr addrefs when you assign in to it.
...And 5 more matches
Background Tasks API - Web APIs
window.requestidlecallback() makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag.
... let totaltaskcountelem = document.getelementbyid("totaltaskcount"); let currenttasknumberelem = document.getelementbyid("currenttasknumber"); let progressbarelem = document.getelementbyid("progress"); let startbuttonelem = document.getelementbyid("startbutton"); let logelem = document.getelementbyid("log"); next we have variables which reference the dom elements we need to interact with.
... these elements are: totaltaskcountelem is the <span> we use to insert the total number of tasks created into the status display in the progress box.
...And 5 more matches
CanvasRenderingContext2D.filter - Web APIs
a value of 0% will create an image that is completely black, while a value of 100% leaves the input unchanged.
...a value of 0% will create a drawing that is completely black.
...a value of 100% is completely grayscale.
...And 5 more matches
Basic animations - Web APIs
requestanimationframe(callback) tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.
... var sun = new image(); var moon = new image(); var earth = new image(); function init() { sun.src = 'https://mdn.mozillademos.org/files/1456/canvas_sun.png'; moon.src = 'https://mdn.mozillademos.org/files/1443/canvas_moon.png'; earth.src = 'https://mdn.mozillademos.org/files/1429/canvas_earth.png'; window.requestanimationframe(draw); } function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.globalcompositeoperation = 'destination-over'; ctx.clearrect(0, 0, 300, 300); // clear canvas ctx.fillstyle = 'rgba(0, 0, 0, 0.4)'; ctx.strokestyle = 'rgba(0, 153, 255, 0.4)'; ctx.save(); ctx.translate(150, 150); // earth var time = new date(); ctx.rotate(((2 * math.pi) / 60) * time.getseconds() + ((2 * math.pi) / 60000) * time.getmill...
... function clock() { var now = new date(); var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.save(); ctx.clearrect(0, 0, 150, 150); ctx.translate(75, 75); ctx.scale(0.4, 0.4); ctx.rotate(-math.pi / 2); ctx.strokestyle = 'black'; ctx.fillstyle = 'white'; ctx.linewidth = 8; ctx.linecap = 'round'; // hour marks ctx.save(); for (var i = 0; i < 12; i++) { ctx.beginpath(); ctx.rotate(math.pi / 6); ctx.moveto(100, 0);...
...And 5 more matches
EventTarget.addEventListener() - Web APIs
because older browsers (as well as some not-too-old browsers) still assume the third parameter is a boolean, you need to build your code to handle this scenario intelligently.
... html <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> javascript // function to change the content of t2 function modifytext() { const t2 = document.getelementbyid("t2"); if (t2.firstchild.nodevalue == "three") { t2.firstchild.nodevalue = "two"; } else { t2.firstchild.nodevalue = "three"; } } // add event listener to table const el = document.getelementbyid("outside"); el.addeventlistener("click", modifytext, false); in this code, modifytext() is a listener for click events registered using addeventlistener().
... html <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> javascript // function to change the content of t2 function modifytext(new_text) { const t2 = document.getelementbyid("t2"); t2.firstchild.nodevalue = new_text; } // function to add event listener to table const el = document.getelementbyid("outside"); el.addeventlistener("click", function(){modifytext("four")}, false); notice that the listener is an anonymous function that encapsulates code that is then, in turn, able to send parameters to the modifytext() function, which is responsible for actual...
...And 5 more matches
Capabilities, constraints, and settings - Web APIs
historically, writing scripts for the web that work intimately with web apis has had a well-known challenge: often, your code needs to know whether or not an api exists and if so, what its limitations are on the user agent it's running on.
... overview the process works like this (using mediastreamtrack as an example): if needed, call mediadevices.getsupportedconstraints() to get the list of supported constraints, which tells you what constrainable properties the browser knows about.
... determining if a constraint is supported if you need to know whether or not a given constriant is supported by the user agent, you can find out by calling navigator.mediadevices.getsupportedconstraints() to get a list of the constrainable properties which the browser knows, like this: let supported = navigator.mediadevices.getsupportedconstraints(); document.getelementbyid("framerateslider").disabled = !supported["framerate"]; in this example, the supported constraints are fetched, and a control that lets the user configure the frame rate is disabled if the framerate constraint isn't supported.
...And 5 more matches
filter - CSS: Cascading Style Sheets
WebCSSfilter
when a single filter property has two or more functions it's results will be different from when two or more filter properties are separately applied with the same functions.
...a value of 0% will create an image that is completely black.
...a value of 0% will create an image that is completely gray.
...And 5 more matches
Closures - JavaScript
document.getelementbyid('size-12').onclick = size12; document.getelementbyid('size-14').onclick = size14; document.getelementbyid('size-16').onclick = size16; <a href="#" id="size-12">12</a> <a href="#" id="size-14">14</a> <a href="#" id="size-16">16</a> run the code using jsfiddle.
... notice that i defined an anonymous function that creates a counter, and then i call it immediately and assign the result to the counter variable.
... <p id="help">helpful notes will appear here</p> <p>e-mail: <input type="text" id="email" name="email"></p> <p>name: <input type="text" id="name" name="name"></p> <p>age: <input type="text" id="age" name="age"></p> function showhelp(help) { document.getelementbyid('help').innerhtml = help; } function setuphelp() { var helptext = [ {'id': 'email', 'help': 'your e-mail address'}, {'id': 'name', 'help': 'your full name'}, {'id': 'age', 'help': 'your age (you must be over 16)'} ]; for (var i = 0; i < helptext.length; i++) { var item = helptext[i]; document.getelementbyid(item.id).onfocus = function() { showhel...
...And 5 more matches
Math - JavaScript
static properties math.e euler's constant and the base of natural logarithms; approximately 2.718.
... math.ln2 natural logarithm of 2; approximately 0.693.
... math.ln10 natural logarithm of 10; approximately 2.303.
...And 5 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
one approach to this is to create different versions of your site/app for different platforms or browsers and serve them appropriately after detecting which browser or platform is looking at your site.
... it is usually much better to create a single version of your code which doesn't care about what browser or platform is accessing the site, but instead uses feature tests to find out what code features the browser supports or what the values of certain browser features are, and then adjusts the code appropriately.
...this is pretty horrible, but generally this kind of problem is easily fixed with some simple css: img, video { max-width: 100%; } this tells the replaced elements to remain constrained inside their container's widths, no matter what.
...And 5 more matches
Interacting with page scripts - Archive of obsolete content
expose objects to page scripts until firefox 30, you could use unsafewindow to perform the reverse procedure, and make objects defined in content scripts available to page scripts: // content-script.js unsafewindow.contentscriptobject = {"greeting" : "hello from add-on"}; // page-script.js var button = document.getelementbyid("show-content-script-var"); button.addeventlistener("click", function() { // access object defined by content script console.log(window.contentscriptobject.greeting); // "hello from add-on" }, false); after firefox 30, you can still do this for primitive values, but can no longer do it for objects.
... the "page.html" file adds two buttons and assigns an event listener to each: one listener displays a property of the cloned object, and the other listener displays a property of the assigned object: <html> <head> </head> <body> <input id="works" type="button" value="i will work"/> <input id="fails" type="button" value="i will not work"/> <script> var works = document.getelementbyid("works"); works.addeventlistener("click", function() { alert(clonedcontentscriptobject.greeting); }, false); var fails = document.getelementbyid("fails"); fails.addeventlistener("click", function() { alert(assignedcontentscriptobject.greeting); }, false); </script> </body> </html> if you run the example, clicking "i will work" displa...
...utation = "hello, "; function greetme(user) { return salutation + user; } exportfunction(greetme, unsafewindow, {defineas: "greetme"}); finally, the "page.html" file adds a button and a page script that calls the exported function when the user pushes the button: <html> <head> </head> <body> <input id="test" type="button" value="click me"/> <script> var test = document.getelementbyid("test"); test.addeventlistener("click", function() { alert(window.greetme("page script")); }, false); </script> </body> </html> exportfunction() works by structured cloning the arguments and return value of the function from one scope to the other.
...And 4 more matches
jpm - Archive of obsolete content
you should revoke and regenerate compromised api credentials immediately.
... if you do not list your add-on on addons.mozilla.org, you need to generate a mozilla-signed xpi and tell firefox where it can find new versions of your add-on.
... the way this works is: you run jpm sign anytime you need to create a new version you host the signed add-on xpi and update it when you need to you host an "update manifest", which, among other things, contains a url pointing to the xpi your add-on tells firefox where it can find the update manifest to do this, include two extra keys in package.json: updateurl: this url is included in the install manifest of the xpi file that jpm xpi builds.
...And 4 more matches
StringView - Archive of obsolete content
vinput.bytelength >>> 2 : this.encoding === "utf-16" ?
... vinput.bytelength >>> 1 : vinput.bytelength; araw = nstartidx === 0 && (!isfinite(nlength) || nlength === ninptlen) ?
... vinput.buffer.bytelength >>> 2 : ftaview === uint16array ?
...And 4 more matches
The Essentials of an Extension - Archive of obsolete content
if we open the chrome.manifest file (again, any text editor will do), we see that the same 3 sections are mentioned: content xulschoolhello content/ skin xulschoolhello classic/1.0 skin/ locale xulschoolhello en-us locale/ the chrome.manifest file tells firefox where to look for chrome files.
... the first word in a line tells firefox what it is that is being declared (content, skin, locale, or others mentioned later on).
...we're adding a menu of our own, and telling firefox to add it in that pane, right after the add-ons item.
...And 4 more matches
MMgc - Archive of obsolete content
alternately, you can open the mmgc namespace in your c++ source so that you can refer to the objects more concisely: using namespace mmgc; ...
...zeroing rcobjects all rcobjects (including all subclasses) must zero themselves out completely upon destruction.
...(the second switch will slow your application down a lot more than the first switch, so you could try the first, then the second.) when a missing write barrier is detected, mmgc will assert and drop you into the debugger, and will print out a message telling you which object contained the missing write barrier, the address of the member variable that needs it, and what object didn't get marked due to the missing write barrier.
...And 4 more matches
Using the Editor from XUL - Archive of obsolete content
something, somewhere, tells mozilla to open the composer window.
...having an id attribute, id="content-frame", allows us to find this element with document.getelementbyid("content-frame"), and to style it from css.
...we could either pass document.getelementbyid("content-frame") or window._content here.
...And 4 more matches
Introduction to SSL - Archive of obsolete content
because the key size is so large, there are more possible keys than for any other cipher-approximately 3.7 * 1050.
...rc4 and rc2 128-bit encryption permits approximately 3.4 * 1038 possible keys, making them very difficult to crack.
...rc4 and rc2 128-bit encryption permits approximately 3.4 * 1038 possible keys, making them very difficult to crack.
...And 4 more matches
Grids - Learn web development
add this to the css inside your file: .container { display: grid; } unlike flexbox, the items will not immediately look any different.
...cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet.
...curabitur vehicula tellus neque, ac ornare ex malesuada et.
...And 4 more matches
How does the Internet work? - Learn web development
by connecting computers to routers, then routers to routers, we are able to scale infinitely.
...well, there are already cables linked to your house, for example, electric power and telephone.
... the telephone infrastructure already connects your house with anyone in the world so it is the perfect wire we need.
...And 4 more matches
How to build custom form controls - Learn web development
if you consider that the active state and the open state are completely different, the answer is again "nothing will happen" because we did not define any keyboard interactions for the opened state.
... on the other hand, if you consider that the active state and the open state overlap a bit, the value may change but the option will definitely not be highlighted accordingly, once again because we did not define any keyboard interactions over options when the control is in its opened state (we have only defined what should happen when the control is opened, but nothing after that).
...they had the market share to successfully introduce a completely new way of interacting with a device, something most device companies can't do.
...And 4 more matches
Index - Learn web development
beginner, express, flask, learn, node, php, python, django, lamp, server-side, servers throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the html file, dragging and dropping it into the browser window, or choosing file > open...
... 41 installing basic software beginner, browser, learn, setup, tools, webmechanics, l10n:priority, text editor that looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these.
... 76 a first splash into javascript article, beginner, codingscripting, conditionals, functions, javascript, learn, objects, operators, variables, events, l10n:priority now you've learned something about the theory of javascript, and what you can do with it, we are going to give you a crash course in the basic features of javascript via a completely practical tutorial.
...And 4 more matches
Graceful asynchronous programming with Promises - Learn web development
also, the user may not respond immediately to these permission requests.
... the important thing here is that the getusermedia() call returns almost immediately, even if the camera stream hasn't been obtained yet.
... we immediately run the blob() method on this response to ensure that the response body is fully downloaded, and when it is available transform it into a blob object that we can do something with.
...And 4 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
introduction for a long time, the web platform has offered javascript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tell it to stop.
...(see the note below on why it runs "as soon as possible" and not "immediately".) more on why you might want to do this later.
... as a consequence, code like settimeout(fn, 0) will execute as soon as the stack is empty, not immediately.
...And 4 more matches
Build your own function - Learn web development
this is fine, as you can tell them apart — function names appear with parentheses after them, and variables don't.
... try including the following line below your function to call it: displaymessage(); this line invokes the function, making it run immediately.
... when you save your code and reload it in the browser, you'll see the little message box appear immediately, only once.
...And 4 more matches
Looping code - Learn web development
body { margin: 0; } button { position: absolute; top: 5px; left: 5px; } </style> </head> <body> <button>update</button> <canvas></canvas> <script> const btn = document.queryselector('button'); const canvas = document.queryselector('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,0,width,height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(...
...if we set it to i === cats.length, the loop would not run at all because i is not equal to 5 on the first loop iteration, so it would stop immediately.
...we already met this in the previous article when we looked at switch statements — when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves onto the code after it.
...And 4 more matches
Drawing graphics - Learn web development
note that on each frame we are completely clearing the canvas and redrawing everything.
...we are deliberately slowing down the frame rate because we only have six sprites to work with, and if we display one every 60th of a second, our character will move way too fast!
...e.pagex : e.clientx + (document.documentelement.scrollleft ?
...And 4 more matches
What is JavaScript? - Learn web development
browser security each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website.
...in interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned.
...if you are using javascript to manipulate elements on the page (or more accurately, the document object model), your code won't work if the javascript is loaded and parsed before the html you are trying to do something to.
...And 4 more matches
Getting started with React - Learn web development
note the use of ./ at the beginning of the path, and the .svg extension at the end — these tell us that the file is local and that it is not a javascript file.
...this expression defines what your browser ultimately renders to the dom.
...you'll notice that this change is immediately rendered in the development server running at http://localhost:3000 in your browser.
...And 4 more matches
Handling common accessibility problems - Learn web development
when we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example: visually impaired people using screen readers or magnification/zoom to access text people with motor function impairments using the keyboard (or other non-mouse features) to activate website functionality.
...defines accessibility more completely and thoroughly than this article does.
...ou can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.
...And 4 more matches
OS.File for the main thread
if (pos <= view.bytelength) { // note: should this be pos >= view.bytelength ?
... file.close(); }, function onerror(reason) { file.close(); throw reason; }); return promise; } or a variant using task.js (or at least the subset already present on mozilla-central): let writestream = function writestream(data, outfile, chunksize) { return task.spawn(function() { let view = new uint8array(data); let pos = 0; while (pos < view.bytelength) { pos += yield outfile.write(view.subarray(pos, chunksize)); } outfile.close(); }).then( null, function onfailure(reason) { outfile.close(); throw reason; } ); } example: save canvas to disk this exmaple uses image to load an image from a path (note: if your path is a file on disk you must use local file; this is accomplished with os.path.tofileu...
...note: if from is specified then even if ignoreexisting is specified as false, it will not fail due to pre-existence of directories, because the from option tells makedir to make the folders if not found.
...And 4 more matches
NSS API Guidelines
these rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules.
...in addition, some low-level apis may be completely opaque to higher level layers.
...fortunately most of the existing api has the correct semantics.
...And 4 more matches
NS_ConvertASCIItoUTF16
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
NS_ConvertUTF8toUTF16
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
nsAdoptingString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
nsAutoString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
nsDependentString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
nsFixedString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
nsPromiseFlatString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
nsString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
nsXPIDLString
@param astring is substring to be sought in this @param aignorecase selects case sensitivity @param aoffset tells us where in this string to start searching @param acount tells us how far from the offset we are to search.
...string print32 aoffset print32 acount print32 find(const prunichar*, print32, print32) const - source parameters prunichar* astring print32 aoffset print32 acount rfind print32 rfind(const nscstring&, prbool, print32, print32) const - source this methods scans the string backwards, looking for the given string @param astring is substring to be sought in this @param aignorecase tells us whether or not to do caseless compare @param aoffset tells us where in this string to start searching.
...@param acount tells us how many iterations to make starting at the given offset.
...And 4 more matches
nsILivemarkService
to use this service, use: var livemarkservice = components.classes["@mozilla.org/browser/livemark-service;2"] .getservice(components.interfaces.nsilivemarkservice); method overview long long createlivemark(in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index); long long createlivemarkfolderonly(in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index); nsiuri getfeeduri(in long long container); long long getlivemarkidforfeeduri(in nsiuri afeeduri); nsiuri getsiteuri(in long long contai...
...ner); boolean islivemark(in long long folder); void reloadalllivemarks(); void reloadlivemarkfolder(in long long folderid); void setfeeduri(in long long container, in nsiuri feeduri); void setsiteuri(in long long container, in nsiuri siteuri); void start(); void stopupdatelivemarks(); methods createlivemark() creates a new livemark.
... long long createlivemark( in long long folder, in astring name, in nsiuri siteuri, in nsiuri feeduri, in long index ); parameters folder the id of the parent folder.
...And 4 more matches
Using the clipboard
tell the transferring object about the type of data being copied.
... tell the transferring object about the data to copy.
... tell the clipboard object to copy the data using the transferring object.
...And 4 more matches
WebIDL bindings
this should only be used when it's absolutely guaranteed that the return value of the attribute getter will always be the same from the js engine's point of view.
...such attributes will have their getter called immediately when the js wrapper for the dom object is created, and the returned value will be stored directly on the js object.
...this will immediately call the c++ getter and cache the value it returns, so it needs a jscontext to work on.
...And 4 more matches
URLs - Plugins
telnet (reference to interactive sessions) locates an interactive service.
... note that npn_geturl is typically asynchronous: it returns immediately and only later handles the request, such as displaying the url or creating the stream for the instance and writing the data.
...it returns immediately and only later handles the request and calls npp_urlnotify.
...And 4 more matches
WebGL constants - Web APIs
standard webgl constants are installed on the webglrenderingcontext and webgl2renderingcontext objects, so that you use them as gl.constant_name: var canvas = document.getelementbyid('mycanvas'); var gl = canvas.getcontext('webgl'); gl.getparameter(gl.line_width); some constants are also provided by webgl extensions.
... blending modes constants passed to webglrenderingcontext.blendfunc() or webglrenderingcontext.blendfuncseparate() to specify the blending mode (for both, rbg and alpha, or separately).
... blending equations constants passed to webglrenderingcontext.blendequation() or webglrenderingcontext.blendequationseparate() to control how the blending is calculated (for both, rbg and alpha, or separately).
...And 4 more matches
Writing WebSocket servers - Web APIs
section 10 discusses security and you should definitely peruse it before exposing your server.
... if any header is not understood or has an incorrect value, the server should send a 400 ("bad request")} response and immediately close the socket.
... | +---------------------------------------------------------------+ the mask bit tells whether the message is encoded.
...And 4 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
fortunately, physicists like galileo, newton, lorentz, and einstein have given us the principle of relativity, which states that the laws of physics have the same form in every frame of reference.
...a third party can tell the difference, but the two of you cannot.
...gaming-related situations are listed separately since they are often a special case specific to gaming, but any of these perspectives might apply to any 3d graphics scene.
...And 4 more matches
Using the Web Animations API - Web APIs
animation: alicetumbling infinite 3s linear; } @keyframes alicetumbling { 0% { color: #000; transform: rotate(0) translate3d(-50%, -50%, 0); } 30% { color: #431236; } 100% { color: #000; transform: rotate(360deg) translate3d(-50%, -50%, 0); } } this changes alice’s color and her transform’s rotation over 3 seconds at a constant (linear) rate and loops infinitely.
... bring the pieces together now it’s time to bring them both together with the element.animate() method: document.getelementbyid("alice").animate( alicetumbling, alicetiming ) and boom: the animation starts playing (see the finished version on codepen).
...instead of making objects for keyframes and timing properties, we could just pass their values in directly, like so: document.getelementbyid("alice").animate( [ { transform: 'rotate(0) translate3d(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3d(-50%, -50%, 0)', color: '#000' } ], { duration: 3000, iterations: infinity } ); what’s more, if we only wanted to specify the duration of the animation and not its iterations (by default, animations iterate once), we could pass in the milliseconds alone: document.getelementbyid("alice").animate( [ { transform: 'rotate(0) translate...
...And 4 more matches
Web APIs
WebAPI
se batterymanager beforeinstallpromptevent beforeunloadevent biquadfilternode blob blobbuilder blobevent bluetooth bluetoothadvertisingdata bluetoothcharacteristicproperties bluetoothdevice bluetoothremotegattcharacteristic bluetoothremotegattdescriptor bluetoothremotegattserver bluetoothremotegattservice body broadcastchannel budgetservice budgetstate buffersource bytelengthqueuingstrategy bytestring c cdatasection css cssconditionrule csscounterstylerule cssgroupingrule cssimagevalue csskeyframerule csskeyframesrule csskeywordvalue cssmathproduct cssmathsum cssmathvalue cssmediarule cssnamespacerule cssnumericvalue cssomstring csspagerule csspositionvalue cssprimitivevalue csspseudoelement cssrule cssrulelist cssstyledeclaration cssstyl...
...ceset fontfacesetloadevent formdata formdataentryvalue formdataevent fullscreenoptions g gainnode gamepad gamepadbutton gamepadevent gamepadhapticactuator geolocation geolocationcoordinates geolocationposition geolocationpositionerror geometryutils gestureevent globaleventhandlers gyroscope h htmlanchorelement htmlareaelement htmlaudioelement htmlbrelement htmlbaseelement htmlbasefontelement htmlbodyelement htmlbuttonelement htmlcanvaselement htmlcollection htmlcontentelement htmldlistelement htmldataelement htmldatalistelement htmldetailselement htmldialogelement htmldivelement htmldocument htmlelement htmlembedelement htmlfieldsetelement htmlfontelement htmlformcontrolscollection htmlformelement htmlframesetelement htmlhrelement htmlheadelement htmlheadingelement htm...
...lhtmlelement htmlhyperlinkelementutils htmliframeelement htmlimageelement htmlinputelement htmlisindexelement htmlkeygenelement htmllielement htmllabelelement htmllegendelement htmllinkelement htmlmapelement htmlmarqueeelement htmlmediaelement htmlmenuelement htmlmenuitemelement htmlmetaelement htmlmeterelement htmlmodelement htmlolistelement htmlobjectelement htmloptgroupelement htmloptionelement htmloptionscollection htmlorforeignelement htmloutputelement htmlparagraphelement htmlparamelement htmlpictureelement htmlpreelement htmlprogresselement htmlquoteelement htmlscriptelement htmlselectelement htmlshadowelement htmlslotelement htmlsourceelement htmlspanelement htmlstyleelement htmltablecaptionelement htmltablecellelement htmltablecolelement htmltableelement htmltablerowele...
...And 4 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
property { width: 90%; margin: 5px 5%; color: #777; position: relative; float: left; } #output .property { height: 100%; width: 12%; position: absolute; left: 0; } #output .value { width: 88%; position: absolute; white-space: pre; word-wrap: break-word; display: block; right: 0; } javascript content var uicolorpicker = (function uicolorpicker() { 'use strict'; function getelembyid(id) { return document.getelementbyid(id); } var subscribers = []; var pickers = []; /** * rgba color class * * hsv/hsb and hsl (hue, saturation, value / brightness, lightness) * @param hue 0-360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); ret...
...pic = node.getattribute('data-topic'); var label = node.getattribute('data-label'); var selected = node.getattribute('data-selected') | 0; var select = document.createelement('div'); var list = document.createelement('div'); var uval = 0; var option = null; var option_value = null; list.classname = 'ui-dropdown-list'; select.classname = 'ui-dropdown-select'; while (node.firstelementchild !== null) { option = node.firstelementchild; option_value = option.getattribute('data-value'); if (option_value === null) option.setattribute('data-value', uval); list.appendchild(node.firstelementchild); uval++; } node.appendchild(select); node.appendchild(list); select.onclick = this.toggle.bind(this); list.onclick = this.updatevalue.bind(this); docu...
...subscribe }; })(); window.addeventlistener("load", function() { lineargradienttool.init(); }); window.addeventlistener("load", function() { lineargradienttool.init(); }); var lineargradienttool = (function lineargradienttool() { 'use strict'; var radian = 180 / math.pi; var inv_radian = math.pi / 180; var units = {'%': 1, 'px' : 0}; /*========== dom methods ==========*/ function getelembyid(id) { return document.getelementbyid(id); } function allowdropevent(e) { e.preventdefault(); } function createclasselement(tag, classname, parent) { var elem = document.createelement(tag); elem.classname = classname; if (parent) parent.appendchild(elem); return elem; }; function trackmouse(elem, callback, startfunc, endfunc) { startfunc = startfunc || function(e) {}; ...
...And 4 more matches
The HTML autocomplete attribute - HTML: Hypertext Markup Language
"tel" a full telephone number, including the country code.
... if you need to break the phone number up into its components, you can use these values for those fields: "tel-country-code" the country code, such as "1" for the united states, canada, and other areas in north america and parts of the caribbean.
... "tel-national" the entire phone number without the country code component, including a country-internal prefix.
...And 4 more matches
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
events change and input supported common attributes required additional attributes accept, capture, files, multiple idl attributes files and value dom interface htmlinputelement properties properties that apply only to elements of type file methods select() value a file input's value attribute contains a domstring that represents the path to the selected file(s).
...the other files can be identified using the input's htmlinputelement.files property.
...see htmlinputelement.webkitdirectory for additional details and examples.
...And 4 more matches
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
classes allow css and javascript to select and access specific elements via the class selectors or functions like the dom method document.getelementsbyclassname.
... 67 <bdi>: the bidirectional isolate element bdi, bidi, directionality, element, html, html text-level semantics, html:flow content, html:palpable content, html:phrasing content, internationalization, left-to-right, reference, right-to-left, text, web, direction, i18n, ltr, rtl the html bidirectional isolate element (<bdi>) tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text.
...hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page's content.
...And 4 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
cross-origin resource sharing (cors) is a mechanism that uses additional http headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.
...c-data/'; xhr.open('get', url); xhr.onreadystatechange = somehandler; xhr.send(); this performs a simple exchange between the client and the server, using cors headers to handle the privileges: let's look at what the browser will send to the server in this case, and let's see how the server responds: get /resources/public-data/ http/1.1 host: bar.other user-agent: mozilla/5.0 (macintosh; intel mac os x 10.14; rv:71.0) gecko/20100101 firefox/71.0 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language: en-us,en;q=0.5 accept-encoding: gzip,deflate connection: keep-alive origin: https://foo.example the request header of note is origin, which shows that the invocation is coming from https://foo.example.
...the first exchange is the preflight request/response: options /doc http/1.1 host: bar.other user-agent: mozilla/5.0 (macintosh; intel mac os x 10.14; rv:71.0) gecko/20100101 firefox/71.0 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language: en-us,en;q=0.5 accept-encoding: gzip,deflate connection: keep-alive origin: http://foo.example access-control-request-method: post access-control-request-headers: x-pingother, content-type http/1.1 204 no content date: mon, 01 dec 2008 01:15:39 gmt server...
...And 4 more matches
HTTP Index - HTTP
WebHTTPIndex
http is a stateless protocol, meaning that the server does not keep any data (state) between two requests.
... 20 cross-origin resource sharing (cors) ajax, cors, cross-origin resource sharing, fetch, fetch api, http, http access controls, same-origin policy, security, xmlhttprequest, l10n:priority cross-origin resource sharing (cors) is a mechanism that uses additional http headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin.
... 41 http public key pinning (hpkp) guide, hpkp, http, security http public key pinning (hpkp) is a security feature that tells a web client to associate a specific cryptographic public key with a certain web server to decrease the risk of mitm attacks with forged certificates.
...And 4 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
automatically starting the playback of audio (or videos with audio tracks) immediately upon page load can be an unwelcome surprise to users.
... autoplay availability as a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true: the audio is muted or its volume is set to 0 the user has interacted with the site (by clicking, tapping, pressing keys, etc.) if the site has been whitelisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features if the autoplay feature policy is used to grant autoplay support to an <iframe> and its document.
...the exact situations that result in blocking, and the specifics of how sites become whitelisted vary from browser to browser, but the above are good guidelines to go by.
...And 4 more matches
panel - Archive of obsolete content
var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline.
...var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline.
...this may take one of the following values: "start": load content scripts immediately after the document element for the panel is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the panel has been loaded, at the time the window.onload event fires this pro...
...And 3 more matches
ui/frame - Archive of obsolete content
// city-info.js var cityselector = window.document.getelementbyid("city-selector"); cityselector.addeventlistener("change", citychanged); function citychanged() { window.parent.postmessage(cityselector.value, "*"); } to listen for these messages in the main add-on code, you can assign a listener to the frame's message event.
... var toolbar = toolbar({ name: "city-info", title: "city info", items: [frame] }); function updateweather(location) { frame.postmessage(weather[location], frame.url); } to listen to these messages in the frame script, add a listener to the window's message event: window.addeventlistener("message", updateweather, false); function updateweather(message) { var label = window.document.getelementbyid("weather"); label.textcontent = message.data; } from add-on to a specific frame you can send a message from the main add-on code to the frame hosted by a particular browser window.
...if you send a json object, the sdk takes care of serializing and deserializing it for you: // frame.js var label = window.document.getelementbyid("linky"); label.addeventlistener("click", function() { window.parent.postmessage({ "type" : "ping", "reason" : "they clicked me" }, "*"); }, true); // main.js var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong); function pong(e) { if (e.data.type == "ping") { console.log(e.data.reason); e.source...
...And 3 more matches
HTML to DOM - Archive of obsolete content
function htmlparser(ahtmlstring){ var html = document.implementation.createdocument("http://www.w3.org/1999/xhtml", "html", null), body = document.createelementns("http://www.w3.org/1999/xhtml", "body"); html.documentelement.appendchild(body); body.appendchild(components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(ahtmlstring, false, null, body)); return body; } it works by creating a content-level (this is safer than chrome-level) <div> in the current page, then parsing the html fragment and attaching that fragment to th...
...the returned <body> object is of type element here is a sample that counts the number of paragraphs in a string: var dompars = htmlparser('<p>foo</p><p>bar</p>'); alert(dompars.getelementsbytagname('p').length); if htmlparser() returns the element name html (instead of body), you have all document object with its complete functions list, therefore you can retrieve info within div tag like this: var dompars = htmlparser("<div id='userinfo'>john was a mediocre programmer, but people liked him <strong>anyway</strong>.</div>"); alert(dompars.getelementbyid('userinfo').innerhtml); to parse a complete html page, load it into an iframe whose type is content (not chrome).
...for that matter, we're going to load our html document first: var request = xmlhttprequest(); request.open("get", "http://example.org/file.html", false); request.send(null); our next step is to create the document object that will represent the dom into which we'll insert our newly-retrieved html: var doc = document.implementation.createhtmldocument("example"); doc.documentelement.innerhtml = request.responsetext; after this any manipulation that we might want to do will be something as simple as the following: doc.body.textcontent = "this is inside the body!"; using a hidden iframe element to parse html to a window's dom sample code may need more work.
...And 3 more matches
Sidebar - Archive of obsolete content
to access your sidebar's window or document objects, you need to use the contentwindow or contentdocument properties of document.getelementbyid("sidebar") respectively.
... for example the code below calls a function defined in the sidebar's context: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; // verify that our sidebar is open at this moment: if (sidebarwindow.location.href == "chrome://yourextension/content/whatever.xul") { // call "yournotificationfunction" in the sidebar's context: sidebarwindow.yournotificationfunction(anyarguments); } testing which sidebar is open the sidebar content may contain different panels (bookmarks, history, webpanel, etc.) and sometimes one wants to only act on the sidebar when it contains a specific panel.
... the good practice to determine which sidebar is open at a time is by testing in location property, which is a chrome url: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; if (sidebarwindow.location.href == "chrome://yourextension/content/whatever.xul") { // act on the sidebar content } for example to test if the web panel from firefox is open: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; if (sidebarwindow.location.href == "chrome://browser/content/web-panels.xul") { // act on the sidebar content only if it is the web panels } accessing the browser.xul window from a sidebar script see accessing the elements of the top-level document from a child window section of working with windows in chrome code.
...And 3 more matches
Install Manifests - Archive of obsolete content
2 extensions 4 themes 8 locale 32 multiple item package 64 spell check dictionary 128 telemetry experiment 256 webextension experiment examples <em:type>2</em:type> this property was added for firefox 1.5, and is only required for add-on types other than extensions and themes.
... examples <em:abouturl>chrome://myext/content/about.xul</em:abouturl> bootstrap a boolean value that tells the application whether the extension is boot-strappable.
... skinnable a true or false value property that tells the application whether the (complete) theme can be skinned by lightweight themes/personas: examples <em:skinnable>true</em:skinnable> strictcompatibility a boolean value indicating if the add-on should be enabled when the version of the application is greater than its max version.
...And 3 more matches
JavaScript Client API - Archive of obsolete content
wipe() when this method is called, your store needs to completely wipe all of its stored data from the local application.
... create(record) not to be confused with createrecord(), this method (which should probably be renamed for clarity soon) tells your store to create a new item in the local application, based on the data in record.
... update(record) the argument is a record which has been remotely modified; your store should locate the matching local item (presumably using the guid, which is available in record.id) and update it to the new values provided in record.
...And 3 more matches
Venkman Introduction - Archive of obsolete content
starting the debugger the javascript debugger is automatically pre-installed in mozilla 1.x but must be installed separately in firefox and other gecko-based products, such as thunderbird and netscape 7.x.
... fortunately, the xpinstall technology makes it possible to install new application modules in firefox by just clicking a hyperlink.
... stop button waiting for execution also note that when you are currently executing javascript and click the stop button, the javascript stops immediately.
...And 3 more matches
MenuModification - Archive of obsolete content
<script> function addtomenu() { var menu = document.getelementbyid("edit-menu"); menu.appenditem("insert", "insert"); } </script> <menu id="edit-menu"/> <button label="add" oncommand="addtomenu()"/> in this example, the addtomenu function is called when the button is pressed.
... <script> function addsubmenu() { var popup = document.getelementbyid("file-popup"); var newmenu = document.createelement("menu"); popup.appendchild(newmenu); newmenu.label = "new"; newmenu.appenditem("document", "doc"); newmenu.appenditem("image", "image"); } </script> <menu label="file" onpopupshowing="addsubmenu()"> <menupopup id="file-popup"/> </menu>.
...then add menuitem to menupopup (all with appendchild to their parentelement).
...And 3 more matches
Modifying a XUL Interface - Archive of obsolete content
for example, the following will add a button to a xul window: example 1 : source view <script> function addbutton(){ var abox = document.getelementbyid("abox"); var button = document.createelement("button"); button.setattribute("label","a new button"); abox.appendchild(button); } </script> <box id="abox" width="200"> <button label="add" oncommand="addbutton();"/> </box> this example has two parts a box container element in xul.
... the button element has two attributes "label" and "oncommand" a javascript function named "addbutton()" this script first gets a reference to the box with getelementbyid(), which is the container to add a new button to.
... the function getelementbyid() does not know that the box it is looking for happens to be containing the tag that has the oncommand attribute that referenced it.
...And 3 more matches
Using Remote XUL - Archive of obsolete content
however, there is a whitelist that lets you specify sites that can still use remote xul.
... the remote xul manager extension lets you manage this whitelist, which is maintained using nsipermissionmanager, by creating entries of type "allowxulxbl", like this: components.classes["@mozilla.org/permissionmanager;1"] .getservice(components.interfaces.nsipermissionmanager) .add(uri, 'allowxulxbl', components.interfaces.nsipermissionmanager.allow_action); xul (pronounced like "zool"), which is short for xml-based user interface language, is an xml-based language for describing application interfaces.
...for apache, you can do this by adding the following line to your mime.types file: application/vnd.mozilla.xul+xml .xul alternately, add this line to your httpd.conf file or, if the apache server is configured to allow it, to the .htaccess file in the directory from which the xul file is served: addtype application/vnd.mozilla.xul+xml .xul then restart your web server.
...And 3 more matches
XUL Questions and Answers - Archive of obsolete content
unfortunately, no simple solution to this was posted.
...an example of this is: var tree = document.getelementbyid('treeid'); selectedtreeitem = tree.view.getitematindex(tree.currentindex); selectedtreeitem.firstchild.setattribute('style', 'background: #ff0000'); what is an example of tab browser in xul?
... using the following code sample, // get browsers object var browsers=document.getelementbyid('content').browsers; var numbrowsers=browsers.length; for (var i=0; numbrowsers>i; i++) { var thisuri=browsers[i].currenturi.spec; // do something with it.
...And 3 more matches
prefwindow - Archive of obsolete content
on platforms where the convention is to apply changes immediately, the preferences are adjusted as soon as the user interface element is changed.
...a true value for this preference makes the preference window apply immediately the user choices, without waiting for the dialog to close with ok.
...if it is set to true any changes to settings are supposed to be applied immediately.
...And 3 more matches
What is RSS - Archive of obsolete content
(although rdf-based rss formats exist, namely the deprecated rss 0.90 and rss 1.0.) common uses of rss syndication are for the syndication of news web sites, of blogs, of internet radio, and of internet television.
...syndication is the process of telling others that you have content for them to consume.
... in other words, when you syndicate, you are telling everyone something like: "hey everyone, i've got articles that i want everyone to come and read.
...And 3 more matches
Using the W3C DOM - Archive of obsolete content
accessing elements with the w3c dom the basic method for referencing elements in an html page is document.getelementbyid().
...for example, the following short sample dynamically sets the left margin of a <div> element with an id of "inset" to half an inch: // in the html: <div id="inset">sample text</div> document.getelementbyid("inset").style.marginleft = ".5in"; note: internet explorer 5 through 7 have a flawed implementation of getelementbyid(), which returns the first element with a matching name or id (id versus name when using getelementbyid, msdn: getelementbyid method).
... ie-specific ways to access elements w3c web standards replacements id_attribute_value document.getelementbyid() document.all.id_attribute_value document.getelementbyid() document.all[id_attribute_value] document.getelementbyid() formname.inputname.value document.forms["formname"].inputname.value or document.forms["formname"].elements["inputname"].value inputname.value document.forms["formname"].inputname.value or document.forms["formname"].elements["inputname"].value formctrlname document.forms["formname"].formctrlname or document.forms["formname"].elements["formctrlname"] document.forms(0) document.forms[0] more on accessing forms and form elements: referencing forms and form...
...And 3 more matches
ArrayBuffer.transfer() - Archive of obsolete content
the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
... if newbytelength is undefined, the bytelength of the oldbuffer is used.
... syntax arraybuffer.transfer(oldbuffer [, newbytelength]); parameters oldbuffer an arraybuffer object from which to transfer.
...And 3 more matches
Legacy layout methods - Learn web development
cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet.
...curabitur vehicula tellus neque, ac ornare ex malesuada et.
...cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet.
...And 3 more matches
Advanced form styling - Learn web development
unfortunately, the behavior of this property's original implementations was very different across browsers, making it not very usable.
...however, in the case of the number type the data being collected is simpler, and it is easy to just use a text input type instead if desired (or tel if you want mobile browsers to show the numeric keypad).
...you can use something like the following to remove the default slider track completely and replace it with a custom style (a thin red track, in this case): input[type="range"] { appearance: none; -webkit-appearance: none; background: red; height: 2px; padding: 0; outline: 1px solid transparent; } however, it is very difficult to customize the style of the range control's drag handle — to get full control over range styling you'll need to use a whole bunch of complex css code, including multiple non-standard, browser-specific pseudo-elements.
...And 3 more matches
Debugging HTML - Learn web development
note: html is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct.
...this demo is deliberately written with some built-in errors for us to explore (the html markup is said to be badly-formed, as opposed to well-formed).
...you will see something like this: this immediately doesn't look great; let's look at the source code to see if we can work out why (only the body contents are shown): <h1>html debugging examples</h1> <p>what causes errors in html?
...And 3 more matches
Video and audio content - Learn web development
fortunately, a few years later the html5 specification had such features added, with the <video> and <audio> elements, and some shiny new javascript apis for controlling them.
... we won't be teaching you how to produce audio and video files — that requires a completely different skillset.
...fortunately, there are things you can do to help prevent this from being a problem.
...And 3 more matches
Client-side storage - Learn web development
however, this does not mean cookies are completely useless on the modern-day web — they are still used commonly to store data related to user personalization and state, e.g.
... next, add the following to the bottom of your code: window.onload = function() { }; we will write all of our subsequent code inside this window.onload event handler function, called when the window's load event fires, to make sure we don't try to use indexeddb functionality before the app has completely finished loading (it could fail if we don't).
...you don't want to hang the browser while you wait for the results, so database operations are asynchronous, meaning that instead of happening immediately, they will happen at some point in the future, and you get notified when they're done.
...And 3 more matches
Framework main features - Learn web development
the curly braces around subject on line 4 tell the application to read the value of the subject constant and insert it into our <h1>.
... when used with react, the jsx from the previous snippet would be compiled into this: var subject = "world"; var header = react.createelement("header", null, react.createelement("h1", null, "hello, ", subject, "!") ); when ultimately rendered by the browser, the above snippet will produce html that looks like this: <header> <h1>hello, world!</h1> </header> handlebars the handlebars templating language is not specific to ember applications, but it is heavily utilized in ember apps.
...this data can be used influence the html that an application ultimately builds.
...And 3 more matches
React interactivity: Events and state - Learn web development
previous overview: client-side javascript frameworks next with our component plan worked out, it's now time to start updating our app from a completely static ui to one that actually allows us to interact and change things.
... the onclick attribute has special meaning here: it tells react to run a given function when the user clicks on the button.
... we want our handlesubmit() function to ultimately help us create a new task, so we need a way to pass information from <form /> to <app />.
...And 3 more matches
Introduction to automated testing - Learn web development
fortunately, there are tools to help us automate some of this pain away.
...commercial cross-browser testing apps like lambdatest, sauce labs, browserstack, and testingbot are based on selenium, but allow you to access their set up remotely using a simple interface, saving you the hassle of setting up your own testing system.
... when loading has finished, you can then start to remotely test the web site running in the chosen browser.
...And 3 more matches
JNI.jsm
working with arrays creating/preallocating a typed array methods cdata .get(number aindex); cdata .getelements(number astart, number alength); void .set(number aindex, cdata avalue); void .setelements(number astart, [array, size_is(arr.length > number anynumber > 0)] in cdata avalsarray); .get() gets the value of the element in the array at given aindex.
... .getelements() returns a new cdata object of the section of the array specified by astart and ending at position astart + alength.
... void setelements(number astart, number alength); parameters astart the position to start setting elements of the array in.
...And 3 more matches
L10n Checks
locale (en-us) by setting the -r parameter, e.g.: check-l10n-completeness -r pl browser/locales/l10n.ini ../l10n/ de output mode you can change the look and feel of the output by setting the -o parameter to 0 (tree; default), 1 (full tree) or 2 (full relative paths), e.g.: check-l10n-completeness -o 2 browser/locales/l10n.ini ../l10n/ de en-us in the locale directory in the source mode you can tell l10n checks to look for the en-us locale in the directory containing all other locales instead of the directory containing the source by setting the -l parameter (useful for e.g.
... "kompozer"), e.g.: check-l10n-completeness -l browser/locales/l10n.ini ../l10n/ de compare every directory in the source mode you can tell l10n checks to compare every directory, not only the ones set in the all-locales file, by setting the -f parameter (useful for e.g.
... "seamonkey" with its extensions), e.g.: check-l10n-completeness -f suite/locales/l10n.ini ../l10n/ de test the reference locale in the source mode you can tell l10n checks to also check the reference locale, by setting the -e parameter (requires the -a parameter to be set too), e.g.: check-l10n-completeness -a 1 -e suite/locales/l10n.ini ../l10n/ de turbo mode in the source mode you can tell l10n checks to look only for missing and obsolete entities and files, by setting the -t parameter, e.g.: check-l10n-completeness -t suite/locales/l10n.ini ../l10n/ de check access keys in all modes you can tell l10n checks to check if the access keys are set properly, by setting the -a parameter, e.g.: check-l10n-completeness -a 1 suite/locales/l10n.ini ../l10n/ de there are three modes available: ...
...And 3 more matches
NSS environment variables
see nss tracing 3.12 nss_use_decoded_cka_ec_point boolean (any value to enable) tells nss to send ec key points across the pkcs#11 interface in the non-standard unencoded format that was used by default before nss 3.12.3.
... 3.12.3 nss_use_shexp_in_cert_name boolean (any value to enable) tells nss to allow shell-style wildcard patterns in certificates to match ssl server host names.
... before 3.0 ns_use_gcc boolean (1 to enable) on systems where gcc is not the default compiler, this tells nss to build with gcc.
...And 3 more matches
Redis Tips
it is intended primarily for developers, and deliberately omits some topics that will be important in any redis deployment, like security and backups.
... the redis command watch lets you name keys you're worried about; it causes your next transaction to be immediately aborted if any of the watched keys has been modified by anyone else.
... ok, now in a different shell, and another redis-cli, do this: redis2> rpush myqueue 42 now if you look back at the first redis-cli, you'll see that it immediately popped the value off the list and said something like: redis1> 1) "myqueue" 2) "42" (26.87s) that rules!
...And 3 more matches
Animated PNG graphics
MozillaTechAPNG
conceptually, at the beginning of each play the output buffer must be completely initialized to a fully transparent black rectangle, with width and height dimensions from the 'ihdr' chunk.
...the default image should be appropriately padded with fully transparent pixels if extra space will be needed for later frames.
... num_plays indicates the number of times that this animation should play; if it is 0, the animation should play indefinitely.
...And 3 more matches
Fun With XBL and XPConnect
<method name="autocomplete"> <argument name="asearchstring"/> <argument name="resultlistener"/> <body> <![cdata[ return this.autocompletesession.autocomplete(null, anonymouscontent[0], asearchstring, this.autocompletelistener); ]]> </body> </method> you can see that the body of the method is just getting the auto complete session object and calling the auto complete method on it.
...i could apply a trick similar to what i did for the xpcom object: <property name="autocompletelistener"> <![cdata[ ({ onautocompleteresult: function(aitem, aoriginalstring, amatch) { if ( aitem ) { anonymouscontent[0].value = amatch; } } }) ]]> </property> as long as the js for the value of autocompletelistener evaluates to an object (and wrapping the expression with a set of parens like i did, does this), then the value of autoco...
...mpletelistener is an object that implements my interface.
...And 3 more matches
Introduction to XPCOM for the DOM
if you haven't grasped it completely, there is no need to read further.
... fortunately, there are nscomptr's to make our life easier.
...to do so, there are two main techniques, and the context should tell you what to use.
...And 3 more matches
nsISupportsArray
inherits from: nsicollection last changed in gecko 1.7 method overview boolean appendelements(in nsisupportsarray aelements); violates the xpcom interface guidelines nsisupportsarray clone(); void compact(); void deleteelementat(in unsigned long aindex); void deletelastelement(in nsisupports aelement); nsisupports elementat(in unsigned long aindex); violates the xpcom interface guidelines boolean enumeratebackwards(in nsisupportsarrayenumfunc afunc, in voidptr adata); violates the xpcom interface guidelines boolean enumerateforwards(in nsisupportsarrayenumfunc afunc, in voidptr adata); violates the xpcom interface guidelines boolean equals([const] in nsisupportsarray other); violat...
...); long getindexofstartingat(in nsisupports apossibleelement, in unsigned long astartindex); long getlastindexof(in nsisupports apossibleelement); long indexof([const] in nsisupports apossibleelement); violates the xpcom interface guidelines long indexofstartingat([const] in nsisupports apossibleelement, in unsigned long astartindex); violates the xpcom interface guidelines boolean insertelementat(in nsisupports aelement, in unsigned long aindex); violates the xpcom interface guidelines boolean insertelementsat(in nsisupportsarray aother, in unsigned long aindex); violates the xpcom interface guidelines long lastindexof([const] in nsisupports apossibleelement); violates the xpcom interface guidelines boolean moveelement(in long afrom, in long ato); violates the xpcom interface...
... guidelines boolean removeelementat(in unsigned long aindex); violates the xpcom interface guidelines boolean removeelementsat(in unsigned long aindex, in unsigned long acount); violates the xpcom interface guidelines boolean removelastelement([const] in nsisupports aelement); violates the xpcom interface guidelines boolean replaceelementat(in nsisupports aelement, in unsigned long aindex); violates the xpcom interface guidelines boolean sizeto(in long asize); violates the xpcom interface guidelines methods violates the xpcom interface guidelines appendelements() boolean appendelements( in nsisupportsarray aelements ); parameters aelements return value clone() nsisupportsarray clone(); parameters none.
...And 3 more matches
Web Console remoting - Firefox Developer Tools
ers, onresponse) the new startlisteners packet: { "to": "conn0.console9", "type": "startlisteners", "listeners": [ "pageerror", "consoleapi", "networkactivity", "fileactivity" ] } the reply is: { "startedlisteners": [ "pageerror", "consoleapi", "networkactivity", "fileactivity" ], "nativeconsoleapi": true, "from": "conn0.console9" } the reply tells which listeners were started and it includes a flag nativeconsoleapi which tells if the window.console object was overridden by the scripts in the page or not.
... when page navigation starts the following packet is sent from the tab actor: { "from": tabactor, "type": "tabnavigated", "state": "start", "url": newurl, "nativeconsoleapi": true } the nativeconsoleapi property tells if the window.console object is native or not for the top level window object for the given tab - this is always true when navigation starts.
... the private flag tells if the error comes from a private window/tab (added in firefox 24).
...And 3 more matches
Advanced animations - Web APIs
var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var ball = { x: 100, y: 100, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; ball.draw(); nothing special here, the ball is actually a simple circle and gets drawn with the...
... var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; function draw() { ctx.clearrect(0,0, canvas.width, canvas.height); ...
... <canvas id="canvas" style="border: 1px solid" width="600" height="300"></canvas> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; function draw() { ctx.clearrect(0,0, canvas.width, canvas.height); ...
...And 3 more matches
Introduction to the DOM - Web APIs
for example, the standard dom specifies that the getelementsbytagname method in the code below must return a list of all the <p> elements in the document: const paragraphs = document.getelementsbytagname("p"); // paragraphs[0] is the first <p> element // paragraphs[1] is the second <p> element, etc.
...though we focus exclusively on javascript in this reference documentation, implementations of the dom can be built for any language, as this python example demonstrates: # python dom example import xml.dom.minidom as m doc = m.parse(r"c:\projects\py\chap1.xml") doc.nodename # dom property of document object p_list = doc.getelementsbytagname("para") for more information on what technologies are involved in writing javascript on the web, see javascript technologies overview.
... when you create a script–whether it's inline in a <script> element or included in the web page by means of a script loading instruction–you can immediately begin using the api for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page.
...And 3 more matches
HTMLImageElement.loading - Web APIs
the htmlimageelement property loading is a string whose value provides a hint to the user agent that tells the browser how to handle loading images which are currently outside the window's visual viewport.
... this helps to optimize the loading of the document's contents by postponing loading the image until it's expected to be needed, rather than immediately during the initial page load.
...the possible values are: eager the default behavior, eager tells the browser to load the image as soon as the <img> element is processed.
...And 3 more matches
The HTML DOM API - Web APIs
htmlanchorelement htmlareaelement htmlaudioelement htmlbrelement htmlbaseelement htmlbodyelement htmlbuttonelement htmlcanvaselement htmldlistelement htmldataelement htmldatalistelement htmldetailselement htmldialogelement htmldirectoryelement htmldivelement htmlelement htmlembedelement htmlfieldsetelement htmlformelement htmlhrelement htmlheadelement htmlheadingelement htmlhtmlelement htmliframeelement htmlimageelement htmlinputelement htmllielement htmllabelelement htmllegendelement htmllinkelement htmlmapelement ...
...htmlmediaelement htmlmenuelement htmlmetaelement htmlmeterelement htmlmodelement htmlolistelement htmlobjectelement htmloptgroupelement htmloptionelement htmloutputelement htmlparagraphelement htmlparamelement htmlpictureelement htmlpreelement htmlprogresselement htmlquoteelement htmlscriptelement htmlselectelement htmlslotelement htmlsourceelement htmlspanelement htmlstyleelement htmltablecaptionelement htmltablecellelement htmltablecolelement htmltableelement htmltablerowelement htmltablesectionelement htmltemplateelement htmltextareaelement htmltimeelement htmltitleelement htmltrackelement htmlulistelement htmlunknownelement htmlvideoelement deprecated html element interfaces htmlmarqueeelement obsolete html element interfaces htmlbasefont...
...element htmlfontelement htmlframeelement htmlframesetelement htmlisindexelement htmlmenuitemelement web app and browser integration interfaces these interfaces offer access to the browser window and document that contain the html, as well as to the browser's state, available plugins (if any), and various configuration options.
...And 3 more matches
Using Pointer Events - Web APIs
function startup() { var el = document.getelementsbytagname("canvas")[0]; el.addeventlistener("pointerdown", handlestart, false); el.addeventlistener("pointerup", handleend, false); el.addeventlistener("pointercancel", handlecancel, false); el.addeventlistener("pointermove", handlemove, false); log("initialized."); } this simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they oc...
... function handlestart(evt) { log("pointerdown."); var el = document.getelementsbytagname("canvas")[0]; var ctx = el.getcontext("2d"); log("pointerdown: id = " + evt.pointerid); ongoingtouches.push(copytouch(evt)); var color = colorfortouch(evt); ctx.beginpath(); ctx.arc(touches[i].pagex, touches[i].pagey, 4, 0, 2 * math.pi, false); // a circle at the start ctx.arc(evt.clientx, evt.clienty, 4, 0, 2 * math.pi, false); // a circle at the start ctx.fillstyle = color; ctx.fill(); } after storing some of the event's processing in th...
... function handlemove(evt) { var el = document.getelementsbytagname("canvas")[0]; var ctx = el.getcontext("2d"); var color = colorfortouch(evt); var idx = ongoingtouchindexbyid(evt.pointerid); log("continuing touch: idx = " + idx); if (idx >= 0) { ctx.beginpath(); log("ctx.moveto(" + ongoingtouches[idx].pagex + ", " + ongoingtouches[idx].pagey + ");"); ctx.moveto(ongoingtouches[idx].pagex, ongoingtouches[idx].pagey); log...
...And 3 more matches
Using Service Workers - Web APIs
read jake archibald's (unfortunately-titled but well-written) application cache is a douchebag for more details.
...if you just passed in the url, and then tried to access the other items in the json separately when the for() loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.) we actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js ...
...it persists until you tell it not to — again, you have full control.
...And 3 more matches
TextRange - Web APIs
WebAPITextRange
this property should only be used as one of the solutions when you need to be compatible with lower versions of ie, rather than relying on it completely in cross browser scripts.
... textrange.boundingleftread only returns the distance between the left edge of the rectangle that binds the textrange object and the left edge that completely contains the textrange object.
... textrange.boundingtopread only returns the distance between the top edge of the rectangle that binds the textrange object and the top edge that completely contains the textrange object.
...And 3 more matches
Touch events - Web APIs
function startup() { var el = document.getelementbyid("canvas"); el.addeventlistener("touchstart", handlestart, false); el.addeventlistener("touchend", handleend, false); el.addeventlistener("touchcancel", handlecancel, false); el.addeventlistener("touchmove", handlemove, false); } document.addeventlistener("domcontentloaded", startup); this simply sets up all the event listeners for our <canvas> element so we can handle the touch...
... function handlestart(evt) { evt.preventdefault(); console.log("touchstart."); var el = document.getelementbyid("canvas"); var ctx = el.getcontext("2d"); var touches = evt.changedtouches; for (var i = 0; i < touches.length; i++) { console.log("touchstart:" + i + "..."); ongoingtouches.push(copytouch(touches[i])); var color = colorfortouch(touches[i]); ctx.beginpath(); ctx.arc(touches[i].pagex, touches[i].pagey, 4, 0, 2 * math.pi, false); // a circle at the start ctx.fillstyle = color; ctx.fill(); con...
... function handlemove(evt) { evt.preventdefault(); var el = document.getelementbyid("canvas"); var ctx = el.getcontext("2d"); var touches = evt.changedtouches; for (var i = 0; i < touches.length; i++) { var color = colorfortouch(touches[i]); var idx = ongoingtouchindexbyid(touches[i].identifier); if (idx >= 0) { console.log("continuing touch "+idx); ctx.beginpath(); console.log("ctx.moveto(" + ongoingtouches[idx].pagex + ", " + ongo...
...And 3 more matches
WebGLRenderingContext.vertexAttribPointer() - Web APIs
if stride is 0, the attribute is assumed to be tightly packed, that is, the attributes are not interleaved but each attribute is in a separate block, and the next vertex' attribute follows immediately after the current vertex.
...also, we have to call gl.enablevertexattribarray() to tell webgl that this attribute should be filled with data from our array buffer.
...for highest performance, interleave the attributes and use the smallest data type that still accurately represents your geometry.
...And 3 more matches
Using textures in WebGL - Web APIs
// until then put a single pixel in the texture so we can // use it immediately.
...this makes the texture immediately usable as a solid blue color even though it may take a few moments for our image to download.
... first, the code to specify the colors buffer is gone, replaced with this: // tell webgl how to pull out the texture coordinates from buffer { const num = 2; // every coordinate composed of 2 values const type = gl.float; // the data in the buffer is 32 bit float const normalize = false; // don't normalize const stride = 0; // how many bytes to get from one set to the next const offset = 0; // how many bytes inside the buffer to start from gl.bindbuffer...
...And 3 more matches
WebGL best practices - Web APIs
flush when expecting results (like queries or rendering frame completion) flush tells the implementation to push all pending commands out for execution, flushing them out of the queue, instead of waiting for more commands to enqueue before sending for execution.
...} this technique may not work in all applications, for example those which require programs to be immediately available for rendering.
... if you know your precision requirements, getshaderprecisionformat() will tell you what the system supports.
...And 3 more matches
WebGL model view projection - Web APIs
these composed matrices ultimately move the original model data around into a special coordinate space called clip space.
... webglbox constructor the constructor looks like this: function webglbox() { // setup the canvas and webgl context this.canvas = document.getelementbyid('canvas'); this.canvas.width = window.innerwidth; this.canvas.height = window.innerheight; this.gl = mdn.createcontext(canvas); var gl = this.gl; // setup a webgl program, anything part of the mdn object is defined outside of this article this.webglprogram = mdn.createwebglprogramfromids(gl, 'vertex-shader', 'fragment-shader'); gl.useprogram(this.webglprogram); // save...
... the attribute and uniform locations this.positionlocation = gl.getattriblocation(this.webglprogram, 'position'); this.colorlocation = gl.getuniformlocation(this.webglprogram, 'color'); // tell webgl to test the depth when drawing, so if a square is behind // another square it won't be drawn gl.enable(gl.depth_test); } webglbox draw now we'll create a method to draw a box on the screen.
...And 3 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
perfect negotiation concepts perfect negotiation makes it possible to seamlessly and completely separate the negotiation process from the rest of your application's logic.
... the process of sending an offer, and making use of the updated setlocaldescription() method: let makingoffer = false; pc.onnegotiationneeded = async () => { try { makingoffer = true; await pc.setlocaldescription(); signaler.send({ description: pc.localdescription }); } catch(err) { console.error(err); } finally { makingoffer = false; } }; we set makingoffer immediately before calling setlocaldescription() in order to lock against interfering with sending this offer, and we don't clear it back to false until the offer has been sent to the signaling server (or an error has occurred, preventing the offer from being made).
...wer()); signaler.send({ description: pc.localdescription }); } } else if (candidate) { try { await pc.addicecandidate(candidate); } catch(err) { if (!ignoreoffer) { throw err; } } } } catch(err) { console.error(err); } }; since rollback works by postponing changes until the next negotiation (which will begin immediately after the current one is finished), the polite peer needs to know when it needs to throw away a received offer if it's currently waiting for a reply to an offer it's already sent.
...And 3 more matches
Writing WebSocket client applications - Web APIs
if you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols: var examplesocket = new websocket("wss://www.example.com/socketserver", ["protocolone", "protocoltwo"]); once the connection is established (that is, readystate is open), examplesocket.protocol will tell you which protocol the server selected.
... as establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a websocket object will be successful.
... var msg = { type: "message", text: document.getelementbyid("text").value, id: clientid, date: date.now() }; // send the msg object as a json-formatted string.
...And 3 more matches
Writing a WebSocket server in C# - Web APIs
here's a barebones server implementation: ​using system.net.sockets; using system.net; using system; class server { public static void main() { tcplistener server = new tcplistener(ipaddress.parse("127.0.0.1"), 80); server.start(); console.writeline("server has started on 127.0.0.1:80.{0}waiting for a connection...", environment.newline); tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); } } tcpclient methods: system.net.sockets.networkstream getstream() gets the stream which is the communication channel.
... tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); networkstream stream = client.getstream(); //enter to an infinite cycle to be able to handle every change in stream while (true) { while (!stream.dataavailable); byte[] bytes = new byte[client.available]; stream.read(bytes, 0, bytes.length); } handshaking when a client connects to a server, it sends a get request to upgrade the connection to a websocke...
...); } put together wsserver.cs // // csc wsserver.cs // wsserver.exe using system; using system.net; using system.net.sockets; using system.text; using system.text.regularexpressions; class server { public static void main() { string ip = "127.0.0.1"; int port = 80; var server = new tcplistener(ipaddress.parse(ip), port); server.start(); console.writeline("server has started on {0}:{1}, waiting for a connection...", ip, port); tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); networkstream stream = client.getstream(); // enter to an infinite cycle to be able to handle every change in stream while (true) { while (!stream.dataavailable); while ...
...And 3 more matches
Rendering and the WebXR frame animation callback - Web APIs
this is important because as the computer becomes increasingly busy, it may not be able to accurately call your callback every frame and may have to skip frames.
... fortunately, you can easily compute how much time you're allowed to use between frames as 1/refreshrate seconds.
... fortunately, there are some tricks you can use to further reduce your impact and optimize performance if your renderering needs are particularly heavy.
...And 3 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>setinterval/clearinterval example</title> <script> var nintervid; function changecolor() { nintervid = setinterval(flashtext, 1000); } function flashtext() { var oelem = document.getelementbyid('my_box'); oelem.style.color = oelem.style.color == 'red' ?
...quisque in ante tellus, in placerat est.
...pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula.
...And 3 more matches
Cubic Bezier Generator - CSS: Cascading Style Sheets
="updatecanvas();return true;" type="text" maxlength=6 id="x2" value="0.14" class='field'> <label for="y2">y2 = </label><input onchange="updatecanvas();return true;" type="text" maxlength=6 id="y2" value="0.53" class='field'> <br> <output id="output">log</output> </form> </html> .field { width: 40px; } function updatecanvas() { var x1 = document.getelementbyid('x1').value; var y1 = document.getelementbyid('y1').value; var x2 = document.getelementbyid('x2').value; var y2 = document.getelementbyid('y2').value; drawbeziercurve(x1, y1, x2, y2); } const radius = 4; // place needed to draw the rulers const rulers = 30.5; const margin = 10.5; const basic_scale_size = 5; // size of 0.1 tick on the rulers var scaling; //limitation: sc...
...aling is computed once: if canvas.height/canvas.width change it won't be recalculated var dragsm = 0; // drag state machine: 0 = nodrag, others = object being dragged function initcanvas() { // get the canvas element using the dom var canvas = document.getelementbyid('bezier'); // make sure we don't execute when canvas isn't supported if (canvas.getcontext) { // use getcontext to use the canvas for drawing var ctx = canvas.getcontext('2d'); scaling = math.min(canvas.height - rulers - margin, canvas.width - rulers - margin); canvas.onmousedown = mousedown; canvas.onmouseup = mouseup; } else { alert('you need safari or firefox 1.5+ to see this demo.'); } } function cx(x) { return x * scaling + rulers; } function r...
...result + 0.5 : result; } function drawbeziercurve(x1, y1, x2, y2) { // get the canvas element using the dom var canvas = document.getelementbyid('bezier'); // make sure we don't execute when canvas isn't supported if (canvas.getcontext) { // use getcontext to use the canvas for drawing var ctx = canvas.getcontext('2d'); // clear canvas ctx.clearrect(0, 0, canvas.width, canvas.height); // draw the rulers ctx.beginpath(); ctx.strokestyle = "black"; // dr...
...And 3 more matches
<color> - CSS: Cascading Style Sheets
there are a few caveats to consider when using color keywords: html only recognizes the 16 basic color keywords found in css1, using a specific algorithm to convert unrecognized values (often to completely different colors).
... unlike html, css will completely ignore unknown keywords.
...this makes the background behind the colored item completely visible.
...And 3 more matches
Adding captions and subtitles to HTML5 video - Developer guides
this example uses an excerpt from the sintel open movie, created by the blender foundation.
... in this example we are using a different video, sintel, as it actually has some speech in it and therefore is better for illustrating how subtitles work!
...we actually have our subtitles in three different languages — english, german, and spanish — so we will reference all three of the relevant vtt files by adding <track> elements inside our html5 <video> element: <video id="video" controls preload="metadata"> <source src="video/sintel-short.mp4" type="video/mp4"> <source src="video/sintel-short.webm" type="video/webm"> <track label="english" kind="subtitles" srclang="en" src="captions/vtt/sintel-en.vtt" default> <track label="deutsch" kind="subtitles" srclang="de" src="captions/vtt/sintel-de.vtt"> <track label="español" kind="subtitles" srclang="es" src="captions/vtt/sintel-es.vtt"> </video> as you can see, each ...
...And 3 more matches
<input type="password"> - HTML: Hypertext Markup Language
WebHTMLElementinputpassword
if the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
...its value can, however, still be changed from javascript code that directly sets the value of the htmlinputelement.value property.
...it only specifies approximately how many can be seen at a time.
...And 3 more matches
<input type="search"> - HTML: Hypertext Markup Language
WebHTMLElementinputsearch
you can retrieve this using the htmlinputelement.value property in javascript.
... if the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
...And 3 more matches
Using the application cache - HTML: Hypertext Markup Language
in firefox, the offline cache data is stored separately from the firefox profile—next to the regular disk cache: windows vista/7: c:\users\<username>\appdata\local\mozilla\firefox\profiles\<salt>.<profile name>\offlinecache mac/linux: /users/<username>/library/caches/firefox/profiles/<salt>.<profile name>/offlinecache in firefox the current status of the offline cache can be inspected on the about:cache page (under the "offline cache device" ...
...the offline cache can be cleared for each site separately using the "remove..." button in tools -> options -> advanced -> network -> offline data.
...files listed under the cache: section header (or immediately after the cache manifest line) are explicitly cached after they're downloaded for the first time.
...And 3 more matches
Using HTTP cookies - HTTP
WebHTTPCookies
typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example.
... it remembers stateful information for the stateless http protocol.
...a simple cookie is set like this: set-cookie: <cookie-name>=<cookie-value> this shows the server sending headers to tell the client to store a pair of cookies: http/2.0 200 ok content-type: text/html set-cookie: yummy_cookie=choco set-cookie: tasty_cookie=strawberry [page content] then, with every subsequent request to the server, the browser sends back all previously stored cookies to the server using the cookie header.
...And 3 more matches
Digital audio concepts - Web media technologies
by chaining all the samples together, you can approximately represent the original wave, as seen in the diagram below.
... the most common sample rates are: 8000 hz the international g.711 standard for audio used in telephony uses a sample rate of 8000 hz (8 khz).
...the nyquist-shannon sampling theorem dictates that to reproduce a sound accurately, it must be sampled at twice the rate of the sound's frequency.
...And 3 more matches
Performance fundamentals - Web Performance
ultimately, user-perceived performance is the only performance that matters.
...a television probably looks choppy and unrealistic to a hummingbird, for example.
...intelligently allocating memory to user state is an important concern that we go over in more detail below.
...And 3 more matches
cfx - Archive of obsolete content
updateurl and updatelink if you choose to host the xpi yourself you should enable the host application to find new versions of your add-on.
...at the updateurl you host a file in the update rdf format: among other things, this includes another url called updatelink which points to the updated xpi itself.
... the --update-link option builds an update rdf alongside the xpi, and embeds the supplied url in the update rdf as the value of updatelink.
...And 2 more matches
Canvas code snippets - Archive of obsolete content
function canvas2dcontext(canvas) { if (typeof canvas === 'string') { canvas = document.getelementbyid(canvas); } if (!(this instanceof canvas2dcontext)) { return new canvas2dcontext(canvas); } this.context = this.ctx = canvas.getcontext('2d'); if (!canvas2dcontext.prototype.arc) { canvas2dcontext.setup.call(this, this.ctx); } } canvas2dcontext.setup = function() { var methods = ['arc', 'arcto', 'beginpath', 'beziercurveto', 'clearrect', 'clip', 'closepath', 'dra...
... 'quadraticcurveto', 'rect', 'restore', 'rotate', 'save', 'scale', 'settransform', 'stroke', 'strokerect', 'stroketext', 'transform', 'translate']; var gettermethods = ['createpattern', 'drawfocusring', 'ispointinpath', 'measuretext', // drawfocusring not currently supported // the following might instead be wrapped to be able to chain their child objects 'createimagedata', 'createlineargradient', 'createradialgradient', 'getimagedata', 'putimagedata' ]; var props = ['canvas', 'fillstyle', 'font', 'globalalpha', 'globalcompositeoperation', 'linecap', 'linejoin', 'linewidth', 'miterlimit', 'shadowoffsetx', 'shadowoffsety', 'shadowblur', 'shadowcolor', 'strokestyle', 'textalign', 'textbaseline']; for (let m of methods) { let method = m; canvas2dcont...
...hods) { let method = m; canvas2dcontext.prototype[method] = function() { return this.ctx[method].apply(this.ctx, arguments); }; } for (let p of props) { let prop = p; canvas2dcontext.prototype[prop] = function(value) { if (value === undefined) return this.ctx[prop]; this.ctx[prop] = value; return this; }; } }; var canvas = document.getelementbyid('canvas'); // use context to get access to underlying context var ctx = canvas2dcontext(canvas) .strokestyle('rgb(30, 110, 210)') .transform(10, 3, 4, 5, 1, 0) .strokerect(2, 10, 15, 20) .context; // use property name as a function (but without arguments) to get the value var strokestyle = canvas2dcontext(canvas) .strokestyle('rgb(50, 110, 210)') .strokestyle(); code usab...
...And 2 more matches
Miscellaneous - Archive of obsolete content
efox" for firefox services.appinfo.version; // returns "2.0.0.1" for firefox version 2.0.0.1 retrieving the version of an extension as specified in the extension's install.rdf components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("extension-guid@example.org", function(addon) { // this is an asynchronous callback function that might not be called immediately alert("my extension's version is " + addon.version); }); restarting firefox/thunderbird/seamonkey_2.0 for firefox 3 see onwizardfinish around here: http://mxr.mozilla.org/seamonkey/sou...pdates.js#1639 for firefox 2 see around here: http://mxr.mozilla.org/mozilla1.8/so...pdates.js#1631 bug 338039 tracks improving this situation by providing a simple method to restart the application.
...</div> <script type="text/javascript"> var elm = document.getelementbyid("scrollarea"); elm.addeventlistener("dommousescroll", function scroll(event){ //event.detail is positive for a downward scroll, negative for an upward scroll alert("scrolling " + event.detail + " lines"); }, false); </script> if you do not receive a dommousescroll event while holding any of the modifier keys (ctrl,shift,alt,meta) you should check the mousewheel.withcontrolk...
... var focusedcontrol; window.addeventlistener("load", function(e) { onwindowload(e); }, false); function onwindowload() { gbrowser.addeventlistener("load", onpageload, true); } function onpageload() { pagedoc = document.commanddispatcher.focusedwindow.document; var inputlist = pagedoc.getelementsbytagname('input'); for (var i=1; i<inputlist.length; i++) { inputlist.item(i).
...And 2 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
to trigger the alert() in the listener and pass the data from the web page, write code such as this in the web page: var element = document.createelement("myextensiondataelement"); element.setattribute("attribute1", "foobar"); element.setattribute("attribute2", "hello world"); document.documentelement.appendchild(element); var evt = document.createevent("events"); evt.initevent("myextensionevent", true, false); element.dispatchevent(evt); this code creates an arbitrary element -- <myextensiondataelement/> -- and inserts it into the web page's dom.
...so to trigger the right event on the right page we have to tell the extension which page to call.
...ed from web page: " + evt.target.getattribute("attribute1") + "/" + evt.target.getattribute("attribute2")); /* the extension answers the page*/ evt.target.setattribute("attribute3", "the extension"); var doc = evt.target.ownerdocument; var answerevt = doc.createelement("myextensionanswer"); answerevt.setattribute("part1", "answers this."); doc.documentelement.appendchild(answerevt); var event = doc.createevent("htmlevents"); event.initevent("myanswerevent", true, false); answerevt.dispatchevent(event); } } document.addeventlistener("myextensionevent", function(e) { myextension.mylistener(e); }, false, true); // the last value is a mozilla-specific value to indicate untrusted content is allowed to trigger the event.
...And 2 more matches
Connecting to Remote Content - Archive of obsolete content
in asynchronous mode code execution continues immediately after the send call.
... request.onload = function(aevent) { let responsexml = aevent.target.responsexml; let rootelement = responsexml.documentelement; if (rootelement && "parseerror" != rootelement.tagname) { let shopelements = rootelement.getelementsbytagname("shop"); let totalelement = rootelement.getelementsbytagname("total")[0]; window.alert(shopelements[1].getelementsbytagname("name")[0].firstchild.nodevalue); // => orange window.alert(totalelement.firstchild.nodevalue); ...
... request.onload = function(aevent) { let responsexml = aevent.target.responsexml; let xulnode; // transform the xml document to a xul document xuldocument = xsltprocessor.transformtodocument(responsexml); // append the xul node to a xul element xulnode = document.adoptnode(xuldocument.firstchild); document.getelementbyid("foo").appendchild(xulnode); }; we effectively transformed the xml file into xul and integrated it into the ui.
...And 2 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
event listeners can be defined on the given nodes by passing functions rather than strings to on* attributes: var href = "http://www.google.com/"; var text = "google"; var nodes = {}; document.documentelement.appendchild( jsontodom(["xul:hbox", {}, ["div", {}, ["a", { href: href, key: "link", onclick: function (event) { alert(event.target.href); } }, text], ["span", { class: "stuff" }, "stuff"]]], document, nodes)); alert(nodes.link); function addentrytopopup(menupopup, doc, chromewindow) { var ...
...ype: "menu", label: "test button label", tooltiptext: "test button tooltip", removable: true, key: "mytestbutton123" }, [ "menupopup", { onpopupshowing: function(event) { addentrytopopup(this, document, window); } }, null ] ]; var capturednodes = {}; var toolbox = doc.getelementbyid("navigator-toolbox"); var palette = toolbox.palette; var domfragment = jsontodom(jsontemplatebtn, document, capturednodes); palette.appendchild(domfragment); alert("capturednodes contains any created nodes that have optionally been captured (for later convenient javascript access) by giving them a 'key' attribute; for example: " + capturednodes.mytestbutton123); another example this ...
... var href = "http://www.google.com/"; var text = "google"; document.getelementbyid("target-div").innerhtml = '<div>\ <a href="' + escapehtml(href) + '" target="_top">' + escapehtml(text) + '</a>\ </div>' it needs to be stressed that this method should not be used in new code and is only a temporary measure to shore up legacy code bases.
...And 2 more matches
List of Mozilla-Based Applications - Archive of obsolete content
mium and google chrome web browser uses mozilla nss and npapi libraries chromeless browser with html-based interface classilla mozilla browser for mac os 9 clines a clone of color lines (game) standalone version cloud web operating system cloud browse iphone/ipad/ipod touch browser seems to be firefox running remotely on servers that people access through device conkeror keyboard-oriented browser convertigo enterprise mashup server server tool for transactional web scraping and for web clipping cometbird another firefox mod modified version of firefox correo email couac (fr) web-based email and jabber app couchdb docume...
... entelechy chat bot uses xulrunner epic browser web browser based on chromium uses mozilla nss and npapi libraries emusic download manager music downloader for emusic emusic remote music manager enlis genome personal genome browser esxx javascript application server uses mozilla rhino etna xml wysiw...
... evergreen library automation system evolution email client uses nss exe elearning xhtml editor seems to be using xul for some of their webui facebook open platform facebook open platform the fbml parser used in the platform is based on mozilla code fennec browser for mobiles as mark notes: fennec is not firefox, it’s a completely different application findthatfont!
...And 2 more matches
Commands - Archive of obsolete content
example: toggling command disabled example 2 : source view <command id="cmd_openhelp" oncommand="alert('help');"/> <button label="help" command="cmd_openhelp"/> <button label="more help" command="cmd_openhelp"/> <button label="disable" oncommand="document.getelementbyid('cmd_openhelp').setattribute('disabled','true');"/> <button label="enable" oncommand="document.getelementbyid('cmd_openhelp').removeattribute('disabled');"/> in this example, both buttons use the same command.
...the example below isn't completely polished.
... really, we should ensure that the selection and focus is adjusted appropriately after a deletion.
...And 2 more matches
XUL Structure - Archive of obsolete content
standalone xul applications may include xul code in a similar way, but, of course, the xul for the application will be included as part of the installation, instead of having to be installed separately as an extension.
...the packaging system is flexible enough so that you can include whatever parts you need and allow other parts, such as the text for different languages, to be downloaded separately.
...they are stored separately from xul files to facilitate modifying the skin (theme) of an application.
...And 2 more matches
calICalendarView - Archive of obsolete content
e calicalendar displaycalender; attribute calicalendarviewcontroller controller; void showdate(in calidatetime adate); void setdaterange(in calidatetime astartdate, in calidatetime aenddate); readonly attribute calidatetime startdate; readonly attribute calidatetime enddate; readonly attribute boolean supportsdisjointdates; readonly attribute boolean hasdisjointdates; void setdatelist(in unsigned long acount, [array,size_is(acount)] in calidatetime adates); void getdatelist(out unsigned long acount, [array,size_is(acount),retval] out calidatetime adates); attribute caliitembase selecteditem; attribute calidatetime selectedday; attributes displaycalendar the displaycalendar is an implementation of the calicalendar interface.
...note that this date is typically not immediately useful for querying for the events and tasks shown in the calicalendarview.
... supportsdisjointdates consumers of calicalendarview should check this attribute to determine whether or not the implementation allows for calls to setdatelist.
...And 2 more matches
Extentsions FAQ - Archive of obsolete content
"); var replaceme = document.getelementbyid("replaceme"); replaceme.parentnode.replacechild(newnode, replaceme); is it possible to place an image in the window that can be moved to anywhere in the window, and always remain on top of everything else?(similiar to using position:absolute and-index:100000 in html) you can almost do this with a stack: <window ...> <stack flex="1"> <image top="40" left="80"/> <vb...
...the appearance with a firefox tab isn't quite the same as having a completely separate explorer window.
... //setting the state document.getelementbyid("toolbar-button").setattribute("toolbar-button", "on"); //or document.getelementbyid("toolbar-button").setattribute("toolbar-button","off"); //css #myexten-toolbar-button[myexten-toolbar-button="on"] { list-style-image: url("chrome://myexten/skin/toolbar-button.png"); -moz-image-region: rect(0px 24px 24px 0px);} #myexten-toolbar-button[myexten-toolbar-button="off"] { list-sty...
...And 2 more matches
Building a Theme - Archive of obsolete content
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.
... chrome uris next, we have to tell firefox where to find the theme files for your theme.
... chrome uris consist of several components: firstly, the uri scheme (chrome) which tells firefox's networking library that this is a chrome uri.
...And 2 more matches
Developing cross-browser and cross-platform pages - Archive of obsolete content
it requires from the web author to have knowledge of the capabilities of all current browsers that may visit the page and then to code appropriately for these.
...moreover, there are many cases where even the accurately-identified browser does not perform as it is reputed/expected to.
... function hideelement(id_attribute_value) { if (document.getelementbyid && document.getelementbyid(id_attribute_value) && document.getelementbyid(id_attribute_value).style ) { document.getelementbyid(id_attribute_value).style.visibility = "hidden"; }; } // example: // <button type="button" onclick="hideelement('d1');">hide div</button> // <div id="d1">some text</div> these repeated calls to document.getelementbyid are not the most effic...
...And 2 more matches
Reference - Archive of obsolete content
well if you combine the two, you can have inherited private variables: function myclass(){ var property = 5; this.tellme = function(){ return property; } } function myotherclass(){ myclass.apply( this ); } var o = new myotherclass; alert( o.tellme() ); //alerts 5 as you'd expect — the preceding comment was added by psygnisfive (talk – contribs) on 22:23, 4 december 2006 terminology we need a terminology appendix.
... unfortunately there is not an [easy] method to download content/packages of content off of devmo for 'local' browsing/viewing/printing, yet.
...while also holding in account the previous example where it was avalable in both instances when prototyping object it should be : function->object->instance or (function=object)->instance and ofcourse function == object return false ;) and the following statements also tells me that function == object although math is only an instance of object...
...And 2 more matches
Efficient animation for web games - Game development
to take a concrete example, if you start a css transition to move something from off-screen so that it is fully visible on-screen, the browser knows that the related content will end up completely visible to the user and can then pre-render that content.
... use requestanimationframe when you are animating <canvas> content, or when your dom animations absolutely must synchronise with canvas content animations, do make sure to use window.requestanimationframe, and not older methods such as window.settimeout.
...requestanimationframe includes a domhighrestimestamp in its callback function prototype, which you definitely should use (as opposed to using the date object), as this will be the time the frame began rendering, and ought to make your animations look more fluid.
...And 2 more matches
How to structure a web form - Learn web development
the above variants increase in effectiveness as you go through them: in the first example, the label is not read out at all with the input — you just get "edit text blank", plus the actual labels are read out separately.
... in the second example, things are a bit clearer — the label read out along with the input is "name star name edit text required", and the labels are still read out separately.
...don't test the example with 2 or 3 of the versions uncommented — screenreaders will definitely get confused if you have multiple labels and multiple inputs with the same id!
...And 2 more matches
Sending forms through JavaScript - Learn web development
fortunately, the xmlhttprequest specification provides a newer, simpler way to handle form data requests with the formdata object.
... const form = document.getelementbyid( "myform" ); // ...and take over its submit event.
...unfortunately, some legacy browsers can't access binary data or require complicated workarounds.
...And 2 more matches
Your first form - Learn web development
forms allow users to enter data, which is generally sent to a web server for processing and storage (see sending form data later in the module), or used on the client-side to immediately update the interface in some way (for example, add another item to a list, or show or hide a ui feature).
...keep it simple and stay focused: ask only for the data you absolutely need.
...this turns a basic text field into a kind of "intelligent" field that will perform some validation checks on the data typed by the user.
...And 2 more matches
Advanced text formatting - Learn web development
brown color.</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.queryselector('.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; ...
...f markup contains a quotation from the mdn <q> page: <p>the quote element — <code>&lt;q&gt;</code> — is <q cite="/docs/web/html/element/q">intended for short quotations that don't require paragraph breaks.</q></p> browser default styling will render this as normal text put in quotes to indicate a quotation, like so: citations the content of the cite attribute sounds useful, but unfortunately browsers, screenreaders, etc.
...nking.)</p> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); const output = document.queryselector('.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; ...
...And 2 more matches
Getting started with HTML - Learn web development
it is a markup language that tells web browsers how to structure the web pages you visit.
...class="controls"> <input id="reset" type="button" value="reset" /> <input id="solution" type="button" value="show solution" /> </div> html { 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.queryselector('.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; solutione...
...te.&lt;/p&gt; </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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.queryselector('.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; solutione...
...And 2 more matches
Images in HTML - Learn web development
fortunately, it wasn't too long before the ability to embed images (and other more interesting types of content) inside web pages was added.
...if the image is described adequately by the main text body, you can just use alt="".
...: 95%"> <img> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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.queryselector('.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; solutione...
...And 2 more matches
Introducing asynchronous JavaScript - Learn web development
when you fetch an image from a server, you can't return the result immediately.
... when we pass a callback function as an argument to another function, we are only passing the function's reference as an argument, i.e, the callback function is not executed immediately.
...however, it doesn't wait for anything — it runs immediately.
...And 2 more matches
Test your skills: Conditionals - Learn web development
if not, it should assign a generic string to response that tells the user we don't know what season it is.
... you need to create an if...else structure that checks whether the machine is switched on and puts a message into the response variable if it isn't, telling the user to switch the machine on.
... we'd like you to create an if...else structure that checks whether the machine is switched on and puts a message into the machineresult variable telling the user whether it is on or off.
...And 2 more matches
Manipulating documents - Learn web development
there are older methods available for grabbing element references, such as: document.getelementbyid(), which selects an element with a given id attribute value, e.g.
...const elementref = document.getelementbyid('myid').
... document.getelementsbytagname(), which returns an array-like object containing all the elements on the page of a given type, for example <p>s, <a>s, etc.
...And 2 more matches
Video and Audio APIs - Learn web development
if you don't specify this, you get no playback controls: this is not as immediately useful for video playback, but it does have advantages.
...you'll see a number of features; the html is dominated by the video player and its controls: <div class="player"> <video controls> <source src="video/sintel-short.mp4" type="video/mp4"> <source src="video/sintel-short.webm" type="video/webm"> <!-- fallback content here --> </video> <div class="controls"> <button class="play" data-icon="p" aria-label="play pause toggle"></button> <button class="stop" data-icon="s" aria-label="stop"></button> <div class="timer"> <div></div> <span aria-label="timer">00:00</span> <...
... the inner <div> is absolutely positioned to sit directly on top of the outer <div>.
...And 2 more matches
Client-Server Overview - Learn web development
the header contains information like the following: the first line includes the response code 200 ok, which tells us that the request succeeded.
... the head also tells us how big it is (content-length: 41823).
...deny allow: get x-cache-info: caching content-length: 41823 <!doctype html> <html lang="en-us" dir="ltr" class="redesign no-js" data-ffo-opensanslight=false data-ffo-opensans=false > <head prefix="og: http://ogp.me/ns#"> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <script>(function(d) { d.classname = d.classname.replace(/\bno-js/, ''); })(document.documentelement);</script> ...
...And 2 more matches
Gecko info for Windows accessibility vendors
ajax: asynchronous javascript and xml ajax is a method of building interactive web applications that process user requests, user actions immediately in real time, unlike an http request, during which users must wait for a whole page to reload or for a new page to load.
... additional dom support there are a number of things available in the parsed html or xml of a document that msaa will not tell you.
...unfortunately, at this time the argument usealternateview is ignored.
...And 2 more matches
Application cache implementation overview
when the url in the manifest attribute of the html tag is identical to the manifest url the channel's nsiapplicationcache object belongs to and, the channel's loadedfromapplicationcache flag is set, the document is associated with that nsiapplicationcache object and an update attempt for the manifest is scheduled after the document completely loads.
... marking entries as foreign when nscontentsink::processofflinemanifest() discovers that the url in the manifest attribute of the html tag is different from the manifest url the channel's nsiapplicationcache object belongs to, the entry the document has been loaded from is marked “foreign” and the page load is completely restarted.
... the load starts again from the top with a completely new channel.
...And 2 more matches
HTTP Cache
the cache api is completely thread-safe and non-blocking.
... it will soon be completely obsoleted and removed (bug 913828).
... two storage objects created with in any way different nsiloadcontextinfo arguments are strictly and completely distinct and cache entries in them do not overlap even when having the same uris.
...And 2 more matches
IME handling guide
when composition completely ends, it's unregistered from the list (and released automatically).
...unfortunately, it's not allowed to use syncronous communication from chrome process to a remote process.
... note that even if there are pending notifications, they are canceled when notify_ime_of_focus is sent since querying content with following notifications immediately after getting focus does not make sense.
...And 2 more matches
DeferredTask.jsm
void start(); flush obsolete since gecko 28 perform any postponed task immediately.
... if the task is running and the timer is armed, then one last execution from start to finish will happen again, immediately after the current execution terminates; then the returned promise will be resolved.
... if the task is not running and the timer is armed, then the task is started immediately, and the returned promise resolves when the new execution terminates.
...And 2 more matches
Following the Android Toasts Tutorial from a JNI Perspective
the arguments are within the parenthesis, and the return type is immediately following.
...the documentation tells us.
...fields do not accept arguments, so the "method format" is not used, we simply tell the sig the type of the field, which we find out from the android documentation website.
...And 2 more matches
powermetrics
the following command encompasses the most useful ones: sudo powermetrics --samplers tasks --show-process-coalition --show-process-gpu -n 1 -i 5000 --samplers tasks tells it to just do per-process measurements.
... --show-process-coalition tells it to group coalitions of related processes, e.g.
... --show-process-gpu tells it to show per-process gpu measurements.
...And 2 more matches
JS::CompileOptions
callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports.
... owningcompileoptions &setelement(jsobject *e) owningcompileoptions &setelementattributename(jsstring *p) owningcompileoptions &setintroductionscript(jsscript *s) owningcompileoptions &setmutederrors(bool mute) owningcompileoptions &setversion(jsversion v) owningcompileoptions &setutf8(bool u) owningcompileoptions &setcolumn(unsigned c) owningcompileoptions &setc...
... compileoptions &setline(unsigned l) compileoptions &setfileandline(const char *f, unsigned l) compileoptions &setsourcemapurl(const char16_t *s) compileoptions &setelement(jsobject *e) compileoptions &setelementattributename(jsstring *p) compileoptions &setintroductionscript(jsscript *s) compileoptions &setmutederrors(bool mute) compileoptions &setversion(jsversion v) compileoptions &setutf8(bool u) compileoptions &setcolumn(unsigned c) compileoptions &setcompileandgo(bool cng) compileopti...
...And 2 more matches
Using the Places livemark service
initiating the livemark service before using the livemark service, you need to obtain an instance: var livemarkservice = components.classes["@mozilla.org/browser/livemark-service;2"] .getservice(components.interfaces.nsilivemarkservice); creating a new livemark the nsilivemarkservice.createlivemark() method creates a new livemark.
... var newlvmkid = livemarkservice.createlivemark(parentfolderid, "livemark name", uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); the first parameter is the id of the folder in which to create the livemark.
...when creating livemarks during startup, you should use the nsilivemarkservice.createlivemarkfolderonly() to avoid http traffic.
...And 2 more matches
XPCOM array guide
MozillaTechXPCOMGuideArrays
// get the array nscomptr<nsiarray> array; foo->getelements(getter_addrefs(array)); // make an enumerator nscomptr<nsisimpleenumerator> enumerator; array->enumerate(getter_addrefs(enumerator)); // now enumerate the elements ...
... void processvisibleitems() { // temporary stack-based nscomarray nscomarray<nsifoo> fooitems; getcompletelist(fooitems); // now filter out non visible objects // doing this backwards pruint32 i = fooitems.count(); while (i > 0) { --i; prbool isvisible; fooitems[i]->getisvisible(&isvisible); if (!isvisible) { fooitems.removeobjectat(i); } } // now deal with the processed list processlist(fooitems); // fooitems will release all its members // when it goes o...
... for example: // melements is an nscomarray<nsielement> nsfoo::getelements(nsisimpleenumerator** aresult) { return ns_newarrayenumerator(aresult, melements); } deleting objects requires gecko 6.0(firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) introduces the removeobjectsat() method to nscomarray<t>.
...And 2 more matches
imgIContainer
obsolete since gecko 2.0 void appendpalettedframe(in print32 ax, in print32 ay, in print32 awidth, in print32 aheight, in gfximageformat aformat, in pruint8 apalettedepth, [array, size_is(imagelength)] out pruint8 imagedata, out unsigned long imagelength, [array, size_is(palettelength)] out pruint32 palettedata, out unsigned long palettelength); native code only!
... gfxiimageframe getframeat(in unsigned long index); obsolete since gecko 1.9.2 void getframecolormap(in unsigned long framenumber, [array, size_is(palettelength)] out pruint32 palettedata, out unsigned long palettelength); obsolete since gecko 2.0 unsigned long getframeimagedatalength(in unsigned long framenumber); obsolete since gecko 2.0 imagecontainer getimagecontainer(); native code only!
...void appendpalettedframe( in print32 ax, in print32 ay, in print32 awidth, in print32 aheight, in gfximageformat aformat, in pruint8 apalettedepth, [array, size_is(imagelength)] out pruint8 imagedata, out unsigned long imagelength, [array, size_is(palettelength)] out pruint32 palettedata, out unsigned long palettelength ); parameters ax missing description ay missing description awidth missing description aheight missing description aformat missing description apalettedepth missing description imagedata missing description imagelength missing description palettedata missing...
...And 2 more matches
nsICollection
inherits from: nsiserializable last changed in gecko 1.7 method overview void appendelement(in nsisupports item); void clear(); pruint32 count(); nsienumerator enumerate(); nsisupports getelementat(in pruint32 index); void queryelementat(in pruint32 index, in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); void removeelement(in nsisupports item); void setelementat(in pruint32 index, in nsisupports item); methods appendelement() appends a new item to the collection.
...getelementat() returns the element at the specified index into the collection.
... nsisupports getelementat( in pruint32 index ); parameters index the index position of the item to be returned.
...And 2 more matches
nsIDOMElement
inherits from: nsidomnode last changed in gecko 1.7 method overview domstring getattribute(in domstring name); nsidomattr getattributenode(in domstring name); nsidomattr getattributenodens(in domstring namespaceuri, in domstring localname); domstring getattributens(in domstring namespaceuri, in domstring localname); nsidomnodelist getelementsbytagname(in domstring name); nsidomnodelist getelementsbytagnamens(in domstring namespaceuri, in domstring localname); boolean hasattribute(in domstring name); boolean hasattributens(in domstring namespaceuri, in domstring localname); void removeattribute(in domstring name) nsidomattr removeattributenode(in nsidomattr oldattr) void removeattributens(in domstring namespaceuri, in...
...getelementsbytagname() get all descendants of a tag name.
... nsidomnodelist getelementsbytagname( in domstring name ); parameters name tag name return value a nsidomnodelist containg all the descendants of this tag name.
...And 2 more matches
nsIDOMXULElement
66 introduced gecko 1.0 inherits from: nsidomelement last changed in gecko 1.9 (firefox 3) method overview void blur(); void click(); void docommand(); void focus(); nsidomnodelist getelementsbyattribute(in domstring name, in domstring value); nsidomnodelist getelementsbyattributens(in domstring namespaceuri, in domstring name, in domstring value); attributes attribute type description align domstring gets/sets the value of the element's align attribute.
...getelementsbyattribute() searches the dom subtree for elements with the given attribute that are not in a namespace.
... nsidomnodelist getelementsbyattribute( in domstring name, in domstring value ); parameters name the name of the attribute to search for.
...And 2 more matches
nsIFocusManager
idomelement getfocusedelementforwindow(in nsidomwindow awindow, in prbool adeep, out nsidomwindow afocusedwindow); pruint32 getlastfocusmethod(in nsidomwindow window); void movecarettofocus(in nsidomwindow awindow); void elementisfocusable(in nsidomelement aelement, in unsigned long aflags); nsidomelement movefocus(in nsidomwindow awindow, in nsidomelement astartelement, in unsigned long atype, in unsigned long aflags); void setfocus(in nsidomelement aelement, in unsigned long aflags); void windowhidden(in nsidomwindow awindow); native code only!
...if astartelement is specified, then movement is done relative to astartelement.
... if astartelement is null, then movement is done relative to the currently focused element.
...And 2 more matches
nsIMutableArray
note also that null elements can be created as a side effect of insertelementat().
... conversely, if insertelementat() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsiarray.queryelementat() will never return a null value.
...method overview void appendelement(in nsisupports element, in boolean weak); void clear(); void insertelementat(in nsisupports element, in unsigned long index, in boolean weak); void removeelementat(in unsigned long index); void replaceelementat(in nsisupports element, in unsigned long index, in boolean weak); methods appendelement() append an element at the end of the array.
...And 2 more matches
nsIZipWriter
if false, the operation is performed immediately.
...if false, the operation is performed immediately.
...if false, the operation is performed immediately.
...And 2 more matches
CSS Grid Inspector: Examine grid layouts - Firefox Developer Tools
extend lines infinitely: by default, grid lines/tracks are only shown inside the element with display: grid set on it; when toggling this option on, the grid lines extend to the edge of the viewport along each axis.
... a target icon that when clicked immediately selects the html element that this grid entry relates to, inside the html pane.
...this is useful for selecting different colors so you can easily tell your grids apart.
...And 2 more matches
Call Tree - Firefox Developer Tools
the call tree tells you which javascript functions the browser spent the most time in.
... by analyzing its results, you can find bottlenecks in your code - places where the browser is spending a disproportionately large amount of time.
... this screenshot tells us something we probably already knew: bubble sort is a very inefficient algorithm.
...And 2 more matches
Basic usage of canvas - Web APIs
this can look something like this: <canvas id="stockgraph" width="150" height="150"> current stock price: $3.15 + 0.15 </canvas> <canvas id="clock" width="150" height="150"> <img src="images/clock.png" width="150" height="150" alt=""/> </canvas> telling the user to use a different browser that supports canvas does not help users who can't read the canvas at all, for example.
... var canvas = document.getelementbyid('tutorial'); var ctx = canvas.getcontext('2d'); the first line in the script retrieves the node in the dom representing the <canvas> element by calling the document.getelementbyid() method.
...our code snippet from above becomes something like this: var canvas = document.getelementbyid('tutorial'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); // drawing code here } else { // canvas-unsupported code here } a skeleton template here is a minimalistic template, which we'll be using as a starting point for later examples.
...And 2 more matches
Transformations - Web APIs
function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.fillrect(0, 0, 150, 150); // draw a rectangle with default settings ctx.save(); // save the default state ctx.fillstyle = '#09f'; // make changes to the settings ctx.fillrect(15, 15, 120, 120); // draw a rectangle with new settings ctx.save(); // save the current state ctx.fillstyle = '#fff'; // ...
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { ctx.save(); ctx.fillstyle = 'rgb(' + (51 * i) + ', ' + (255 - 51 * i) + ', 255)'; ctx.translate(10 + j * 50, 10 + i * 50); ctx.fillrect(0, 0, 25, 25); ctx.restore(); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); screenshotlive samp...
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); // left rectangles, rotate from canvas origin ctx.save(); // blue rect ctx.fillstyle = '#0095dd'; ctx.fillrect(30, 30, 100, 100); ctx.rotate((math.pi / 180) * 25); // grey rect ctx.fillstyle = '#4d4e53'; ctx.fillrect(30, 30, 100, 100); ctx.restore(); // right rectangles, rotate from rectangle center // draw blue rect ctx.fillstyle =...
...And 2 more matches
DocumentFragment - Web APIs
parentnode.firstelementchild read only returns the element that is the first child of the documentfragment object, or null if there is none.
... parentnode.lastelementchild read only returns the element that is the last child of the documentfragment object, or null if there is none.
... documentfragment.getelementbyid() returns the first element node within the documentfragment, in document order, that matches the specified id.
...And 2 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
inside this context, whitespace character processing can be summarized as follows: first, all spaces and tabs immediately before and after a line break are ignored so, if we take our example markup from before and apply this first rule, we get: <h1>◦◦◦hello⏎ <span>◦world!</span>⇥◦◦</h1> next, all tab characters are handled as space characters, so the example becomes: <h1>◦◦◦hello⏎ <span>◦world!</span>◦◦◦</h1> next, line breaks are converted to spaces: <h1>◦◦�...
...��hello◦<span>◦world!</span>◦◦◦</h1> after that, any space immediately following another space (even across two separate inline elements) is ignored, so we end up with: <h1>◦hello◦<span>world!</span>◦</h1> and finally, sequences of spaces at the beginning and end of a line are removed, so we finally get this: <h1>hello◦<span>world!</span></h1> this is why people visiting the web page will simply see the phrase "hello world!" nicely written at the top of the page, rather than a weirdly indented "hello" followed but an even more weirdly indented "world!" on the line below that.
...this handles everything for you, and is definitely the preferred solution: ul { list-style-type: none; margin: 0; padding: 0; display: flex; } if you need to rely on inline-block, you could set the font-size of the list to 0.
...And 2 more matches
Element.closest() - Web APIs
WebAPIElementclosest
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.
... 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 el = document.getelementbyid('div-03'); var r1 = el.closest("#div-02"); // returns the element with the id=div-02 var r2 = el.closest("div div"); // returns the closest ancestor which is a div in div, here it is the div-03 itself var r3 = el.closest("article > div"); // returns the closest ancestor which is a div and has a parent article, 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 browse...
...And 2 more matches
HTMLTableElement - Web APIs
if a correct object is given, it is inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element, and the first <thead> that is a child of this element is removed from the tree, if any.
...if a correct object is given, it is inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element, and the first <tfoot> that is a child of this element is removed from the tree, if any.
...if none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element.
...And 2 more matches
RTCPeerConnection - Web APIs
the event is sent immediately after the call setremotedescription() and doesn't wait for the result of the sdp negotiation.onconnectionstatechangethe rtcpeerconnection.onconnectionstatechange property specifies an eventhandler which is called to handle the connectionstatechange event when it occurs on an instance of rtcpeerconnection.
...because this method has been deprecated, you should instead use removetrack() if your target browser versions have implemented it.removetrack()the rtcpeerconnection.removetrack() method tells the local end of the connection to stop sending media from the specified track, without actually removing the corresponding rtcrtpsender from the list of senders as reported by rtcpeerconnection.getsenders().restartice()the webrtc api's rtcpeerconnection interface offers the restartice() method to allow a web application to easily request that ice candidate gathering be redone on both ends of t...
...otherwise, both the rtp and rtcp candidates are returned, separately.
...And 2 more matches
A simple RTCDataChannel sample - Web APIs
function startup() { connectbutton = document.getelementbyid('connectbutton'); disconnectbutton = document.getelementbyid('disconnectbutton'); sendbutton = document.getelementbyid('sendbutton'); messageinputbox = document.getelementbyid('message'); receivebox = document.getelementbyid('receivebox'); // set event listeners for user interface widgets connectbutton.addeventlistener('click', connectpeers, false); disconnectbutton.addev...
... set up the ice candidates the next step is to set up each connection with ice candidate listeners; these will be called when there's a new ice candidate to tell the other side about.
... the next step is to connect the local peer to the remote by telling the remote peer about it.
...And 2 more matches
WebRTC API - Web APIs
the set of standards that comprise webrtc makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user installs plug-ins or any other third-party software.
... webrtc concepts and usage webrtc serves multiple purposes; together with the media capture and streams api, they provide powerful multimedia capabilities to the web, including support for audio and video conferencing, file exchange, screen sharing, identity management, and interfacing with legacy telephone systems including support for sending dtmf (touch-tone dialing) signals.
...its underlying data transport is completely closed at this point.
...And 2 more matches
Alerts - Accessibility
below is example javascript code which could be inserted above the closing “head” tag: <script type="application/javascript"> function removeoldalert() { var oldalert = document.getelementbyid("alert"); if (oldalert){ document.body.removechild(oldalert); } } function addalert(amsg) { removeoldalert(); var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var msg = document.createtextnode(amsg); newalert.appendchild(msg); document.body.appendchild(newalert); } function c...
...heckvalidity(aid, asearchterm, amsg) { var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); addalert(amsg); } else { elem.setattribute("aria-invalid", "false"); removeoldalert(); } } </script> the checkvalidity function the primary method in javascript used for form validation is the checkvalidity function.
...the alert we just created does not have any buttons to press, it just tells us what’s wrong.
...And 2 more matches
Cognitive accessibility - Accessibility
cognitive impairment refers to a broad range of disabilities, from people with intellectual disabilities who may have the most-limited capabilities, to age-related issues with thinking and remembering.
... overview cognitive and intellectual disabilities cover a large spectrum, and may be momentary, temporary, or permanent conditions.
...when a timeout is used, tell people exactly how much time will cause the session to time out and result in lost data.
...And 2 more matches
Using CSS animations - CSS: Cascading Style Sheets
animation-iteration-count configures the number of times the animation should repeat; you can specify infinite to repeat the animation indefinitely.
...ein; } @keyframes slidein { from { margin-left: 100%; width: 300%; } 75% { font-size: 300%; margin-left: 25%; width: 150%; } to { margin-left: 0%; width: 100%; } } <p>the caterpillar and alice looked at each other for some time in silence: at last the caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice.</p> this tells the browser that 75% of the way through the animation sequence, the header should have its left margin at 25% and the width should be 150%.
...in this case, let’s use infinite to have the animation repeat indefinitely: p { animation-duration: 3s; animation-name: slidein; animation-iteration-count: infinite; } adding it to the existing code: @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } <p>the caterpillar and alice looked at each other for some time in silence: at last the caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice.</p...
...And 2 more matches
Border-radius generator - CSS: Cascading Style Sheets
n init() { var elem = document.queryselectorall('.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.getelementbyid(id); } /** * shadow dragging */ var previewmousetracking = (function drag() { var active = false; var lastx = 0; var lasty = 0; var subscribers = []; var init = function init(id) { var elem = getelembyid(id); elem.addeventlistener('mousedown', dragstart, false); document.addeventlistener('mouseup', dragend, false); } va...
...node(this.topic); this.setunitx(this.unitx); this.setunity(this.unity); this.setunitr(this.unitr); this.updatewidth(); this.updateheight(); this.updateradius(); if (x === 'left') this.resizex = 1; if (x === 'right') this.resizex = -1; if (y === 'top') this.resizey = 1; if (y === 'bottom') this.resizey = -1; radius.classname = 'radius'; var unit_selector = document.getelementbyid("unit-selection"); var unitw = new unitselector(this.topic + '-w'); var unith = new unitselector(this.topic + '-h'); var unitr = new unitselector(this.topic); unit_selector.appendchild(unitw.container); unit_selector.appendchild(unith.container); unit_selector.appendchild(unitr.container); node.appendchild(radius); subject.appendchild(handle); unitw.select.addeventlis...
...is.maxh; this.updateheight(); } if (deltax || deltay) this.updateborderradius(); } /** * tool manager */ var tool = (function tool() { var preview; var preview_ui; var radius_containers = []; var border_width = 3; var borders1 = [null, null, null, null]; var borders2 = [0, 0, 0, 0]; var updateuiwidth = function updateuiwidth(value) { var pwidth = subject.parentelement.clientwidth; var left = (pwidth - value) / 2; subject.style.width = value + "px"; for (var i = 0; i < 4; i++) radius_containers[i].updateunits(0); } var updateuiheight = function updateuiheight(value) { var pheight = subject.parentelement.clientheight; var top = (pheight - value) / 2; subject.style.height = value + "px"; subject.style.top = top - border_width +...
...And 2 more matches
Variable fonts guide - CSS: Cascading Style Sheets
the advantage in choosing the variable font is that you have access to the entire range of weights, widths, and styles available, rather than being constrained to only the few that you previously would have loaded separately.
...the reason for this is that most typefaces have very specific designs for bolder weights and italics that often include completely different characters (lower-case 'a' and 'g' are often quite different in italics, for example).
... in order to most accurately reflect the typeface design and avoid differences between browsers and how they may or may not synthesize the different styles, it's more accurate to load the specific font files where needed when using a non-variable font.
...And 2 more matches
Getting Started - Developer guides
at this stage, you need to tell the xmlhttp request object which javascript function will handle the response, by setting the onreadystatechange property of the object and naming it after the function to call when the request changes state, like this: httprequest.onreadystatechange = nameofthefunction; note that there are no parentheses or parameters after the function name, because you're assigning a reference to the functi...
... <button id="ajaxbutton" type="button">make a request</button> <script> (function() { var httprequest; document.getelementbyid("ajaxbutton").addeventlistener('click', makerequest); function makerequest() { httprequest = new xmlhttprequest(); if (!httprequest) { alert('giving up :( cannot create an xmlhttp instance'); return false; } httprequest.onreadystatechange = alertcontents; httprequest.open('get', 'test.html'); httprequest.send(); } function alertcontents() { ...
... then in alertcontents(), we need to replace the line alert(httprequest.responsetext); with: var xmldoc = httprequest.responsexml; var root_node = xmldoc.getelementsbytagname('root').item(0); alert(root_node.firstchild.data); this code takes the xmldocument object given by responsexml and uses dom methods to access some of the data contained in the xml document.
...And 2 more matches
Audio and video manipulation - Developer guides
var processor = { timercallback: function() { if (this.video.paused || this.video.ended) { return; } this.computeframe(); var self = this; settimeout(function () { self.timercallback(); }, 16); // roughly 60 frames per second }, doload: function() { this.video = document.getelementbyid("my-video"); this.c1 = document.getelementbyid("my-canvas"); this.ctx1 = this.c1.getcontext("2d"); var self = this; this.video.addeventlistener("play", function() { self.width = self.video.width; self.height = self.video.height; self.timercallback(); }, false); }, computeframe: function() { this.ctx1.drawimage(this.video, 0, 0, this.width, ...
... html <video id="my-video" controls src="https://udn.realityripple.com/samples/6f/08625b424a.m4v"> </video> javascript var myvideo = document.getelementbyid('my-video'); myvideo.playbackrate = 2; playable code <video id="my-video" controls="true" width="480" height="270"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> ...
... <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> var myvideo = document.getelementbyid('my-video'); myvideo.playbackrate = 2;</textarea> var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var edit = document.getelementbyid('edit'); var code = textarea.value; function setplaybackrate() { eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; setplaybackrate(); }); edit.addeventlistener('click', function() { textarea.focus(); }) textarea.addeventlistener('input', setplaybackrate); window.addeventlistener('load', setplaybackrate); note: try the playbackrate example live.
...And 2 more matches
HTML attribute: rel - HTML: Hypertext Markup Language
WebHTMLAttributesrel
link not allowed not allowed dns-prefetch tells the browser to preemptively perform dns resolution for the target resource's origin external resource not allowed not allowed external referenced document is not part of the same site as the current document.
... link link link manifest web app manifest link not allowed not allowed modulepreload tells to browser to preemptively fetch the script and store it in the document's module map for later evaluation.
... dns-prefetch relevant for the <link> element both in the <body> and <head>, it tells the browser to preemptively perform dns resolution for the target resource's origin.
...And 2 more matches
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
ragraph = document.queryselector('p'); button.addeventlistener('click', updatebutton); function updatebutton() { if (button.value === 'start machine') { button.value = 'stop machine'; paragraph.textcontent = 'the machine has started!'; } else { button.value = 'start machine'; paragraph.textcontent = 'the machine is stopped.'; } } the script gets a reference to the htmlinputelement object representing the <input> in the dom, saving this refence in the variable button.
...e.pagex : e.clientx + (document.documentelement.scrollleft ?
... document.documentelement.scrollleft : document.body.scrollleft); cury = (window.event) ?
...And 2 more matches
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
you can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so: <label for="appt-time">choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30"> you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var timecontrol = document.queryselector('input[type="time"]'); timecontrol.value = '15:30'; time value format the value of the time input is always in 24-hour format that includes leading zeros: hh:mm, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent).
... var starttime = document.getelementbyid("starttime"); var valuespan = document.getelementbyid("value"); starttime.addeventlistener("input", function() { valuespan.innertext = starttime.value; }, false); when a form including a time input is submitted, the value is encoded before being included in the form's data.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
...And 2 more matches
Browser detection using the user agent - HTTP
so, user agent sniffing is definitely not the way to go.
...indow) { hastouchscreen = true; // deprecated, but good fallback } else { // only as a last resort, fall back to user agent sniffing var ua = navigator.useragent; hastouchscreen = ( /\b(blackberry|webos|iphone|iemobile)\b/i.test(ua) || /\b(android|windows phone|ipad|ipod)\b/i.test(ua) ); } } if (hastouchscreen) document.getelementbyid("examplebutton").style.padding="1em"; as for the screen size, simply use window.innerwidth and window.addeventlistener("resize", function(){ /*refresh screen size dependent things*/ }).
...there a single instance of a dog box immediately above a cat box, of course.
...And 2 more matches
CSP: script-src - HTTP
use this sparingly and definitely not for scripts.
... examples violation case given this csp header: content-security-policy: script-src https://example.com/ the following script is blocked and won't be loaded or executed: <script src="https://not-example.com/js/library.js"></script> note that inline event handlers are blocked as well: <button id="btn" onclick="dosomething()"> you should replace them with addeventlistener calls: document.getelementbyid("btn").addeventlistener('click', dosomething); unsafe inline script note: disallowing inline styles and inline scripts is one of the biggest security wins csp provides.
... however, if you absolutely have to use it, there are a few mechanisms that will allow them.
...And 2 more matches
Firefox user agent string reference - HTTP
mac os x version gecko user agent string mac os x on intel x86 or x86_64 mozilla/5.0 (macintosh; intel mac os x x.y; rv:10.0) gecko/20100101 firefox/10.0 mac os x on powerpc mozilla/5.0 (macintosh; ppc mac os x x.y; rv:10.0) gecko/20100101 firefox/10.0 linux linux is a more diverse platform.
...android versions 4 and above will report the version accurately.
.../5.0 (mobile; rv:26.0) gecko/26.0 firefox/26.0 tablet mozilla/5.0 (tablet; rv:26.0) gecko/26.0 firefox/26.0 tv mozilla/5.0 (tv; rv:44.0) gecko/44.0 firefox/44.0 device-specific mozilla/5.0 (mobile; nnnn; rv:26.0) gecko/26.0 firefox/26.0 device-specific user agent strings although it is strongly discouraged by mozilla, some handset manufacturers unfortunately include a token in their device's ua string that represents their device id.
...And 2 more matches
Promise.all() - JavaScript
it rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.
...it is typically used when there are multiple asynchronous tasks that are dependent on one another to complete successfully, as it does not wait and will reject immediately upon any of the input promises rejecting.
...ronicity of promise.all this following example demonstrates the asynchronicity (or synchronicity, if the iterable passed is empty) of promise.all: // we are passing as argument an array of promises that are already resolved, // to trigger promise.all as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.all(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code after the stack is empty settimeout(function() { console.log('the stack is now empty'); console.log(p); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: array[2] } the same thing happens if promise.all rejects: var mixedpromises...
...And 2 more matches
Codecs used by WebRTC - Web media technologies
due to its low sample rate and sample size, g.711 audio quality is generally considered poor by modern standards, even though it's roughly equivalent to what a landline telephone sounds like.
...this changes the order of preference of the codecs, letting you tell webrtc to prefer a different codec over all others.
... default codecs unless otherwise specified, the default—or, more accurately, preferred—codecs requested by each browser's implementation of webrtc are shown in the table below.
...And 2 more matches
The "codecs" parameter in common media types - Web media technologies
0 0 0 yuv 4:4:4 1 0 0 yuv 4:2:2 1 1 0 yuv 4:2:0 1 1 1 yuv 4:0:0 (monochrome) the third digit in ccc indicates the chroma sample position, with a value of 0 indicating that the position is unknown and must be separately provided during decoding; a value of 1 indicating that the sample position is horizontally colocated with the (0, 0) luma sample; and a value of 2 indicating that the sample position is colocated with (0, 0) luma.
... 58 00 main profile (mp) the profile used for standard-definition digital television being broadcast in mpeg-4 format.
... not used for high-definition television broadcasts.
...And 2 more matches
Navigation and resource timings - Web Performance
the document can now handle post-load tasks, after which point the document is marked as completely loaded.
...the request start is the moment immediately before the user agent starts requesting the resource from the server, or from relevant application caches or from local resources.
... the response start is the time immediately after the user agent's http parser receives the first byte of the response from relevant application caches, or from local resources or from the server, which happens after the request is received and processed.
...And 2 more matches
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
versions of svg viewers prior to the release of firefox 1.5 unfortunately paid scant attention to namespaces, but they are essential to multi-xml dialect supporting user agents such as gecko-based browsers which must be very strict.
...the image and its components can also be transformed, composited together, or filtered to change their appearance completely.
... 288 texts intermediate, svg, svg:tutorial when talking about text in svg we have to differentiate two almost completely separate topics.
...And 2 more matches
XPath snippets - XPath
anode.documentelement : anode.ownerdocument.documentelement); var result = xpe.evaluate(aexpr, anode, nsresolver, 0, null); var found = []; var res; while (res = result.iteratenext()) found.push(res); return found; } this function uses the new xpathevaluator() constructor, which is supported in firefox, chrome, opera and safari, but not in edge or internet explorer.
...scripts in a web document which might be accessed by edge or internet explorer users should replace the call to new xpathevaluator() with the following fragment: // xpathevaluator is implemented on objects that implement document var xpe = anode.ownerdocument || anode; in that case the creation of the xpathnsresolver can be simplified as: var nsresolver = xpe.creatensresolver(xpe.documentelement); note however that creatensresolver should only be used if you are sure the namespace prefixes in the xpath expression match those in the document you want to query (and that no default namespace is being used (though see document.creatensresolver for a workaround)).
...if you can rely on id attributes, document.getelementbyid() is still powerful, but it's not nearly as powerful as xpath.
...And 2 more matches
page-worker - Archive of obsolete content
in this example we fetch the first paragraph of a page from wikipedia, then the first paragraph of a different page: var getfirstparagraph = "var paras = document.getelementsbytagname('p');" + "console.log(paras[0].textcontent);" + "self.port.emit('loaded');" pageworker = require("sdk/page-worker").page({ contentscript: getfirstparagraph, contenturl: "http://en.wikipedia.org/wiki/chalk" }); pageworker.port.on("loaded", function() { pageworker.contenturl = "http://en.wikipedia.org/wiki/cheese" }); scripting...
...this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires this prope...
...setting it loads the content immediately.
...this may have one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read...
Label and description - Archive of obsolete content
absolutely nothing!</description> with white-space: pre; all whitespace, including newlines, is rendered literally.
...absolutely nothing!</description> with white-space: pre-wrap; all whitespace is rendered literally, but text is additionally permitted to wrap at spaces.
... absolutely nothing!</description> text can also be made to wrap by inserting an <html:br/> element regardless of the css style, but this creates a hard-break that does not change as parent elements resize.
... <description>i am your father's brother's nephew's cousin's former roommate.<html:br/> what's that make us?<html:br/> absolutely nothing!</description> using labels as anchors its possible to make a label look and act like an html <a> tag: <label class="text-link" href="http://whatever.com" value="click here to go to whatever"/> "text-link" is a built-in, predefined class.
JavaScript timers - Archive of obsolete content
the requestanimationframe() function tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame.
... setimmediate() calls a function immediately after the browser has completed other operations, such as events and display updates.
... requestanimationframe() requestanimationframe() tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame.
...unfortunately the canvas element was never designed to be used in this way (unlike flash) so there are limitations.
How to convert an overlay extension to restartless - Archive of obsolete content
mappings, so that you can access your files with custom paths such as: resource://myaddon/filename.ext chrome://myaddon/content/filename.ext step 2: no more resource:// uris for files internal to your bundle unfortunately, resource mappings in your chrome.manifest were not usable in restartless add-ons until mozilla finally fixed this bug in firefox 38, which looked bad, but only because mozilla is still using resource:// uris internally and in examples.
...unfortunately, the built in apis for dealing with preferences are missing this basic stuff, and its plain text handling doesn't work with unicode properly.
...docs: document.getelementbyid(), document.createelement(), element reference, node reference (dom elements are also nodes).
....nsidomwindow)); } var windowlistener = { onopenwindow: function(xulwindow) { var window = xulwindow.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); function onwindowload() { window.removeeventlistener("load",onwindowload); if (window.document.documentelement.getattribute("windowtype") == "navigator:browser") loadintowindow(window); } window.addeventlistener("load",onwindowload); }, onclosewindow: function(xulwindow) { }, onwindowtitlechange: function(xulwindow, newtitle) { } }; as mentioned above, components.utils.unload() will not work properly if the jsm file it is unloading is in a jar.
JavaScript Object Management - Archive of obsolete content
the load event is fired after the dom on the window has loaded completely, but before it's displayed to the user.
... */ init : function(aevent) { this._stringbundle = document.getelementbyid("xulschoolhello-string-bundle"); // you can make changes to the window dom here.
...if you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aevent) { let that = this; this._stringbundle = document.getelementbyid("xs-hw-string-bundle"); window.settimeout( function() { window.alert(that._stringbundle.getstring("xulschoolhello.greeting.label")); }, 0); } the settimeout function executes the function in the first parameter, after a delay in miliseconds specified by the second parameter.
...all module files should begin with a declaration like this: var exported_symbols = ["〈modulenamespace〉"]; exported_symbols is a special identifier that tells firefox that this file is only publishing the object named 〈modulenamespace〉.
Setting Up a Development Environment - Archive of obsolete content
ultimately you can just compress the contents of the src directory using any zip or archive tool and get a similar result.
...that is because make can tell that the file in the bin directory is up to date, and nothing needs to be done.
...you can even change styles, attributes and execute javascript code in it, although that's not completely reliable.
...it's definitely worth a try.
Adding preferences to an extension - Archive of obsolete content
next, we call our own refreshinformation() method to immediately fetch and display the current information about the stock the extension is configured to monitor.
... once we've gotten the updated preference, we call refreshinformation() to immediately update the display with the new stock's information.
... watchstock() while we're at it, let's add a method that sets which stock we want to be watching, changing the preference and immediately requesting a refresh of the display.
...ation: function() { // because we may be called as a callback, we can't rely on // "this" referring to the right object, so we need to reference // it by its full name var symbol = stockwatcher.tickersymbol; var fullurl = "http://quote.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=" + symbol; function inforeceived() { var samplepanel = document.getelementbyid('stockwatcher2'); var output = httprequest.responsetext; if (output.length) { // remove any whitespace from the end of the string output = output.replace(/\w*$/, ""); // build the tooltip string var fieldarray = output.split(","); samplepanel.label = symbol + ": " + fieldarray[1]; samplepanel.tooltiptext = "chg: " + fi...
Creating a dynamic status bar extension - Archive of obsolete content
we use the window.addeventlistener() dom function to tell firefox to call the stockwatcher.startup() function when a new browser window is opened: window.addeventlistener("load", function(e) { stockwatcher.startup(); }, false); our new extension has two primary functions: startup() and refreshinformation().
...refreshinformation() embeds another function, inforeceived(), which we'll look at separately shortly.
...function inforeceived() { var samplepanel = document.getelementbyid('stockwatcher'); var output = httprequest.responsetext; if (output.length) { // remove whitespace from the end of the string; // this gets rid of the end-of-line characters output = output.replace(/\w*$/, ''); // build the tooltip string var fieldarray = output.split(','); // assert that fieldarray[0] == 'goog' samplepanel.label = 'goog: ' + fieldarray[1...
...]; samplepanel.tooltiptext = 'chg: ' + fieldarray[4] + ' | ' + 'open: ' + fieldarray[5] + ' | ' + 'low: ' + fieldarray[6] + ' | ' + 'high: ' + fieldarray[7] + ' | ' + 'vol: ' + fieldarray[8]; } } the first thing we do here is get the status bar panel into the variable samplepanel by calling the document.getelementbyid() dom function.
Using microformats - Archive of obsolete content
var nummicroformats = microformats.count(name, rootelement, options); parameters name the name of the microformat to count.
... rootelement required.
... var microformatsarray = microformats.get(name, rootelement, options, targetarray); parameters name the name of the microformat to find.
... rootelement required.
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
if the menu is visible, it will reflect the changes immediately.
... show(anchornode) shows the menu immediately.
...if a user forgets or is unable to tell whether a certain menuitem is part of firefox or provided by a feature, she does not know where to turn when she has problems with it.
...notifications.show(menuitem.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: j...
Mozilla Crypto FAQ - Archive of obsolete content
at that point both nss and psm will be completely buildable using the open source code available from the mozilla.org site, and nss and psm will be included in the mozilla binary releases distributed by mozilla.org.
...district court for the northern district of california issued a final ruling (written by judge marilyn hall patel) that "the [u.s.
...bureau of export administration immediately afterward, and the u.s.
...an earlier (circa 1995) collection of essays and public documents, with a concentration on the clipper chip controversy and the digital telephony act.
New Security Model for Web Services - Archive of obsolete content
these scripts may legitimately require access to external resources, but permitting them to access internal resources permits the compromise of these resources that would normally not be available to applications outside of the firewall.
...but signed scripts have not really caught on as they require certificates do not change the basic problem that some completely-unknown party has written a script that might now have access to internal resources.
...this could be combined with the other options above such as whitelisting, signed scripts, etc.
... unfortunately, this does not prevent soap messages from being sent to non-soap addresses, which is a big enough problem that the verification cannot stand alone to guarantee that untrusted service requests are always properly rejected by services that should be firewall-protected.
File object - Archive of obsolete content
file.writeln() write bytes to the file, followed by a line separator, flushing the buffer if file.hasautoflush.
... file.writeall() writes an array of lines to the file, obeying the same semantics as writeln.
... examples example: hello, world file.output.writeln("hello, world"); example: writing a new file var file = new file("myfile.txt"); file.open("write,create", "text"); file.writeln("the quick brown fox jumped over the lazy dogs"); file.close(); example: reading from a file var data; var file = new file("myfile.txt"); file.open("read", "text"); data = file.readln(); file.close(); example: sending mail through a pipeline var mail = new file("...
...|/usr/lib/sendmail foo@bar.com"); mail.writeln("i love javascript.\npipe support is especially good!"); mail.close(); ...
OpenClose - Archive of obsolete content
here is a complete example which uses a button to open a menu: <button label="open menu" oncommand="document.getelementbyid('editmenu').open = true;"/> <menu id="editmenu" label="edit"> <menupopup> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> </menu> this technique may be used for both menupopups that use the menu tag, the button tag and the toolbarbutton tag.
... somepopup.openpopup(document.documentelement, "end_before", 0, 0, false, false); the second argument to openpopup is the anchor position, which specifies which side of the anchor the popup is positioned on.
...here is an example mouse click event listener: function mouseclicked(event) { var panel = document.getelementbyid("some-panel"); panel.openpopup(null, "", event.clientx, event.clienty, false, false); } the openpopupatscreen method a second method, openpopupatscreen, may be used to open up a popup and place it at a specific screen coordinate.
...in the following example, the popup is opened at horizontal positon 100 and vertical position 200: popup.openpopupatscreen(100, 200, false); note that if the supplied coordinates would cause the popup to be partially or completely off screen, the popup will be moved such that it is fully visible, and may be resized if necessary.
Sorting and filtering a custom tree view - Archive of obsolete content
"sort(this)" class="sortdirectionindicator"/> <splitter class="tree-splitter"/> <treecol id="weapon" label="weapon" flex="1" persist="width ordinal hidden" onclick="sort(this)" class="sortdirectionindicator"/> </treecols> <treechildren id="tree-children"/> </tree> </window> sort.js var table = null; var data = null; var tree; var filtertext = ""; function init() { tree = document.getelementbyid("tree"); loadtable(); } //this function is called every time the tree is sorted, filtered, or reloaded function loadtable() { //remember scroll position.
...this way, we don't have to deal with //mapping between the two data.push({name: "leonardo", description: "leader", weapon: "dual katanas"}); data.push({name: "michaelangelo", description: "party dude", weapon: "nunchaku"}); data.push({name: "donatello", description: "does machines", weapon: "bo"}); data.push({name: "raphael", description: "cool, but rude", weapon: "sai"}); data.push({name: "splinter", description: "rat", weapon: "walking stick"}); data.push({name: "shredder", description: "armored man", weapon: "blades"}); data.push({name: "casey jones", description: "goalie masked man", weapon: "hockey stick"}); data.push({name: "...
..."ascending" : "descending"); tree.setattribute("sortresource", columnname); tree.view = new treeview(table); //set the appropriate attributes to show to indicator var cols = tree.getelementsbytagname("treecol"); for (var i = 0; i < cols.length; i++) { cols[i].removeattribute("sortdirection"); } document.getelementbyid(columnname).setattribute("sortdirection", order == 1 ?
... return o.tolowercase(); } return o; } function gettopvisiblerow() { return tree.treeboxobject.getfirstvisiblerow(); } function settopvisiblerow(topvisiblerow) { return tree.treeboxobject.scrolltorow(topvisiblerow); } function inputfilter(event) { //do this now rather than doing it at every comparison var value = prepareforcomparison(event.target.value); setfilter(value); document.getelementbyid("clearfilter").disabled = value.length == 0; } function clearfilter() { document.getelementbyid("clearfilter").disabled = true; var filterelement = document.getelementbyid("filter"); filterelement.focus(); filterelement.value = ""; setfilter(""); } function setfilter(text) { filtertext = text; loadtable(); } ...
Template Logging - Archive of obsolete content
fortunately, some debugging and logging support is provided with templates that may help.
...however, calling getelementbyid using this id will retrieve the generated content for that result if you want to further study the content that was generated.
...we could debug this by removing parts of the query bottom up, for instance, removing the <triple> element completely and seeing whether any results or content is generated.
...unfortunately, detecting network or parsing errors with the data itself can be difficult.
Manipulating Lists - Archive of obsolete content
here is an example: example 1 : source view <script> function additem(){ document.getelementbyid('thelist').appenditem("thursday", "thu"); } </script> <listbox id="thelist"/> <button label="add" oncommand="additem();"/> the appenditem() takes two arguments, the label, in this case 'thursday', and a value 'thu'.
... example 3 : source view <script> function doselect(){ var val = document.getelementbyid('number').value; val = number(val); if (val != null) document.getelementbyid('level').selectedindex = val - 1; } </script> <hbox align="center"> <label value="enter a number from 1 to 3:"/> <textbox id="number"/> <button label="select" oncommand="doselect();"/> </hbox> <radiogroup id="level"> <radio label="excellent"/> <radio label="good"/> <radio label="poor"/> </r...
... deleting selected items the following example shows a method of deleting the selected items properly: example 4 : source view <script> function deleteselection(){ var list = document.getelementbyid('thelist'); var count = list.selectedcount; while (count--){ var item = list.selecteditems[0]; list.removeitemat(list.getindexofitem(item)); } } </script> <button label="delete" oncommand="deleteselection();"/> <listbox id="thelist" seltype="multiple"> <listitem label="cheddar"/> <listitem label="cheshire"/> <listitem label="edam"/> <listitem label="gouda"/> <li...
...compare the effect of both functions at different scroll positions in this example: example 5 : source view <button label="scrolltoindex" oncommand="document.getelementbyid('thelist').scrolltoindex(4);"/> <button label="ensureindexisvisible" oncommand="document.getelementbyid('thelist').ensureindexisvisible(4);"/> <listbox id="thelist" rows="5"> <listitem label="1"/> <listitem label="2"/> <listitem label="3"/> <listitem label="4"/> <listitem label="5"/> <listitem label="6"/> <listitem label="7"/> <listitem label="8"/> <listitem...
The Implementation of the Application Object Model - Archive of obsolete content
this gives you a feature called aggregation, the ability to put completely different kinds of data into the same place.
...because the file lives remotely, it can be updated whenever the owner of the web site sees fit.
...the only way that one content node would know how to instantiate a content node of a completely different type is if it had additional information stored for every child content node that it contained.
...let's consider another required feature that has heretofore gone unmentioned in this document: the need to take the same set of data and present it as completely different content models.
datepicker - Archive of obsolete content
in addition, the date, month and year properties may be used to retrieve and modify each component of the date separately.
... attributes disabled, firstdayofweek, readonly, type, tabindex, value properties date, dateleadingzero, datevalue, disabled, month, monthleadingzero, open, readonly, tabindex, value, year, yearleadingzero examples <datepicker type="grid" value="2007-03-26"/> attributes disabled type: boolean indicates whether the element is disabled or not.
... dateleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the date when it is less than 10.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
tab - Archive of obsolete content
ArchiveMozillaXULtab
afterselected type: boolean this is set to true if the tab is immediately after the currently selected tab.
... beforeselected type: boolean this is set to true if the tab is immediately before the currently selected tab.
...this would be useful if the images are stored remotely or you plan on swapping the image frequently.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
timepicker - Archive of obsolete content
in addition, the hour, minute and second properties may be used to retrieve and modify each component of the time separately.
... attributes disabled, hideseconds, increment, readonly, tabindex, value properties amindicator, datevalue, disabled, hideseconds, hour, hourleadingzero, increment, is24hourclock, ispm, minute, minuteleadingzero, pmindicator, readonly, second, secondleadingzero, tabindex, value examples <timepicker value="12:05"/> attributes disabled type: boolean indicates whether the element is disabled or not.
... minuteleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the minute when it is less than 10.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
now you need to set up a special .mozconfig file to tell mozilla to build both xulrunner and your application.
...moz_build_projects="xulrunner mccoy" mk_add_options moz_objdir=@topsrcdir@/../mccoybase # global options ac_add_options --enable-debug ac_add_options --disable-optimize # xulrunner options ac_add_app_options xulrunner --enable-application=xulrunner # mccoy options ac_add_app_options mccoy --enable-application=mccoy ac_add_app_options mccoy --with-libxul-sdk=../xulrunner/dist the first section tells mozilla what to build and where to put the resulting object files.
...it tells mozilla where to look for the build.mk file, which is what tells it where to start building your app.
...makefiles.sh - you don't absolutely need this file since the build system will generate makefiles as need by walking the tree (based on the value of dirs).
Gecko Compatibility Handbook - Archive of obsolete content
in addition, internet explorer 4 and netscape navigator 4 use completely different methods of embedding third-party software into the browser.
...unfortunately, this is invalid html and can cause problems both when parsing the page and when applying the css styles.
... wrong doctype problem: an incorrect doctype can completely alter a page's presentation.
...unfortunately, several implementations of ssl 3.0 incorrectly implement the negotiation of which version of ssl to use and fail to connect to gecko browsers.
NPN_GetValue - Archive of obsolete content
play =1: unix only: returns the current display npnvxtappcontext: unix only: returns the application's xtappcontext npnvnetscapewindow: ms windows and unix/x11 only: ms windows: gets the native window on which plug-in drawing occurs; returns hwnd unix/x11: gets the browser toplevel window in which the plug-in is displayed; returns window npnvjavascriptenabledbool: tells whether javascript is enabled; true=javascript enabled, false=not enabled npnvasdenabledbool: tells whether smartupdate (former name: asd) is enabled; true=smartupdate enabled, false=not enabled npnvisofflinebool: tells whether offline mode is enabled; true=offline mode enabled, false=not enabled npnvtoolkit: npnvsupportsxembedbool: npnvwindownpobject: returns the npobject * poin...
...ter for the dom window object; see getting the page url in npapi plugin for a rough example npnvpluginelementnpobject: npnvsupportswindowless: tells whether the browser supports windowless plugins.
... the value parameter should point to a npbool, which will be set appropriately if the function returns nperr_no_error.
...the value parameter should point to an npbool, which will be set appropriately if the function returns nperr_no_error.
NPAPI plugin reference - Archive of obsolete content
browser-side plug-in api this chapter describes methods in the plug-in api that are provided by the browser; these allow call back to the browser to request information, tell the browser to repaint part of the window, and so forth.
... npn_forceredraw asks the plugin host to immediately (synchronously) repaint invalid areas.
... npp_destroystream tells the plug-in that a stream is about to be closed or destroyed.
... npp_setwindow tells the plug-in when a window is created, moved, sized, or destroyed.
Introduction to Public-Key Cryptography - Archive of obsolete content
while in transit, the encrypted information is unintelligible to an intruder.
...the user must supply a name and password separately for each new server the user wishes to use during a work session.
... contents of a certificate the contents of certificates are organized according to the x.509 v3 certificate specification, which has been recommended by the international telecommunications union (itu), an international standards body, since 1988.
... depending on an organization's policies, the process of issuing certificates can range from being completely transparent for the user to requiring significant user participation and complex procedures.
Using workers in extensions - Archive of obsolete content
when the result is received from xmlhttprequest, instead of immediately updating the displayed information in the status bar, a message is sent to the main thread using the worker's postmessage() method.
... line 22 sends a message to the ticker thread to tell it what symbol to monitor.
...it needs to be updated to post a message to the worker to tell it which stock symbol to track.
...watchstock() is updated to pass the symbol to the ticker thread, and refreshinformation(), whose main functionality is now in the worker, is updated to simply pass an empty message to the worker, which tells the worker to refresh the stock information immediately.
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
listing 5 - demonstration of server-proxy <script runat="server"> function notexposed() { // runs on the server, hidden from the browser return "can't see me!"; } function exposed() { // runs on the server, callable from the browser return "exposed to the browser"; } exposed.proxy = true; // tell jaxer this function is ok to be called from the browser </script> <script runat="client" type="text/javascript"> alert( exposed() ); //works like a charm alert( notexposed() ); //produces an object not found error since it server-side only </script> understanding the concept of operating context in jaxer is central to moving forward with the example application which is wh...
... listing 7 - manipulating the dom server-side <script runat="server"> window.onserverload = function() { document.getelementbyid( "out-logger" ).innerhtml = jaxer.file.read( "dump.txt" ); } </script> the code in listing 7 is executed server-side and takes advantage of the onserverload event which ensures that we have a complete dom before trying to access it.
... <script> function formhandler() { // get the form values var name = txt_name.getvalue(); var email = txt_email.getvalue(); var message = txt_message.getvalue(); // if the form passes validation client-side, submit results to the processor if( validatecomments( name, email, message ) ) { formprocessor( name, email, message ); // update the logger with the most recent entry document.getelementbyid( "out-logger" ).innerhtml += "name: " + name + "<br/>email: " + email + "<br/>message: " + message + "<br/><br/>"; } else { ext.msg.alert( "error", "please enter the required fields" ); } } </script> <!-- processes the form contents --> <script runat="server"> function formprocessor( name, email, message ) { // perform the same validation of the data server-side if( !validatecomme...
... listing 10 - creating a simple xml service <script runat="server"> var rs_comments = jaxer.db.execute("select * from comments"); var doc = document.implementation.createdocument('', 'comments', null); var root = doc.documentelement; rs_comments.rows.foreach(function(row, index) { if (true || index < 10) { var node = doc.createelement('comment'); node.setattribute('id', row.id); node.setattribute('name', row.name); node.setattribute('message', row.message); root.appendchild(node); } }); jaxer.response.exit(200, doc); </script> the data from the database is represented in xml format as follows: <comments> <comment mes...
Writing JavaScript for XHTML - Archive of obsolete content
problem: names in xhtml and html are represented in different cases scripts that used getelementsbytagname() with an upper case html name no longer work, and attributes like nodename or tagname return upper case in html and lower case in xhtml.
... solution: use or convert to lower case for methods like getelementsbytagname(), passing the name in lower case will work in both html and xhtml.
...so if the browser tells our server, that it can handle xhtml as xml, that is, the accept: field in the http head contains application/xhtml+xml somewhere, we are safe to send the content as xml.
...ss here is the accept field, that firefox 2.0.0.9 sends with its requests: accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 further reading you will find several useful articles in the developer wiki: xml in mozilla dom xml introduction xml extras dom 2 methods you will need are: dom:document.createelementns dom:document.getelementsbytagnamens see also properly using css and javascript in xhtml documents ...
Parsing microformats in JavaScript - Archive of obsolete content
telgetter() specifically retrieves a telephone number from a microformat node.
... this handles the fact that telephone numbers use "value" as the name of one of their subproperties, but "value" is also used for value excerpting.
... tel = microformats.parser.telgetter(propnode, parentnode); parameters propnode the dom node to check.
... return value a string containing the telephone number.
Audio for Web games - Game development
unfortunately these are also the platforms that people often use to play games.
...also note that playing and immediately pausing your audio does not guarantee that a small piece of audio won't be played.
... let's add some javascript to make this work: var myaudio = document.getelementbyid('myaudio'); var buttons = document.getelementsbytagname('button'); var stoptime = 0; for (var i = 0; i < buttons.length; i++) { buttons[i].addeventlistener('click', function() { myaudio.currenttime = this.getattribute("data-start"); stoptime = this.getattribute("data-stop"); myaudio.play(); }, false); } myaudio.addeventlistener('timeupdate', function() { if (this.curr...
... note: if the first parameter is 0 or less than the context currenttime, playback will commence immediately.
Mobile touch controls - Game development
overview: control mechanisms next the future of mobile gaming is definitely web, and many developers choose the mobile first approach in their game development process — in the modern world, this generally also involves implementing touch controls.
... pure javascript approach we could implement touch events on our own — setting up event listeners and assigning relevant functions to them would be quite straightforward: var el = document.getelementsbytagname("canvas")[0]; el.addeventlistener("touchstart", handlestart); el.addeventlistener("touchmove", handlemove); el.addeventlistener("touchend", handleend); el.addeventlistener("touchcancel", handlecancel); this way, touching the game's <canvas> on the mobile screen would emit events, and thus we could manipulate the game in any way we want (for example, moving the space ship around).
...you can assign functions on input down and input up separately if you'd like to perform more complicated actions, but in this game touching the right side of the screen will simply fire the bullets to the right — this is all we need in this case.
... the stick being pressed can be handled during the gameplay in the update function like so: if(this.stick.isdown) { // move the player } we can adjust the player's velocity based on the current angle of the stick and move him appropriately.
IIFE - MDN Web Docs Glossary: Definitions of Web-related terms
an iife (immediately invoked function expression) is a javascript function that runs as soon as it is defined.
... the second part creates the immediately invoked function expression () through which the javascript engine will directly interpret the function.
... examples the function becomes a function expression which is immediately executed.
... var result = (function () { var name = "barry"; return name; })(); // immediately creates the output: result; // "barry" ...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
(note that this has not been thoroughly tested for all circumstances and may not necessarily reflect the standard behavior completely.) note also that if you wish to allow xml:base, you will need the xml:base function, and the line beginning var href = ...
... should become: var href = getxmlbaselink (/* xlink sans xml:base */ xinclude.getattribute('href'), /* element to query from */ xinclude); function resolvexincludes(docu) { // http://www.w3.org/tr/xinclude/#xml-included-items var xincludes = docu.getelementsbytagnamens('http://www.w3.org/2001/xinclude', 'include'); if (xincludes) { for (i=0; i < xincludes.length; i++) { var xinclude = xincludes[i]; var href = xinclude.getattribute('href'); var parse = xinclude.getattribute('parse'); var xpointer = xinclude.getattribute('xpointer'); var encoding = xinclude.getattribute('encoding'); // e.g., utf-8 // "text/xml or application/xml or matches text/*+xml or application/*+xml" before encoding (then utf-8) v...
...ar accept = xinclude.getattribute('accept'); // header "accept: "+x var acceptlanguage = xinclude.getattribute('accept-language'); // "accept-language: "+x var xifallback = xinclude.getelementsbytagnamens('http://www.w3.org/2001/xinclude', 'fallback')[0]; // only one such child is allowed if (href === '' || href === null) { // points to same document if empty (null is equivalent to empty string) href = null; // set for uniformity in testing below if (parse === 'xml' && xpointer === null) { alert('there must be an xpointer attribute present if "href" is empty an parse is "xml"'); return false; } } else if (href.match(/#$/, '') || href.match(/^#/, '...
... 0; k < xpathresult.snapshotlength; k++) { a[k] = xpathresult.snapshotitem(k); } responsenodes = a; } else { // otherwise, the response must be a single well-formed document response responsenodes = [response.documentelement]; // put in array so can be treated the same way as the above } // prepend any node(s) (as xml) then remove xinclude for (j=0; j < responsenodes.length ; j++) { xincludeparent.insertbefore(responsenodes[j], xinclude); } xi...
Practical positioning examples - Learn web development
vestibulum et orci scelerisque, vulputate tellus quis, lobortis dui.
...the <a> elements are set to display inline-block so they will sit in a line but still be stylable, and they are styled appropriately for tab buttons, using a variety of other properties.
...the first rule we'll add will absolutely position the panels, and make them all sit flush to the top and left of their <div> container — this part is absolutely key to this whole layout feature, as it makes the panels sit on top of one another.
...don't worry if you didn't get this all immediately — positioning is a fairly advanced topic, and you can always work through the articles again to aid your understanding.
Responsive design - Learn web development
zoe mickley gillenwater was instrumental in her work to describe and formalize the different ways in which flexible sites could be created, attempting to find a happy medium between filling the screen or being completely fixed in size.
...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.
... you can also art direct images used at different sizes, thus providing a different crop or completely different image to different screen sizes.
... <meta name="viewport" content="width=device-width,initial-scale=1"> this meta tag tells mobile browsers that they should set the width of the viewport to the device width, and scale the document to 100% of its intended size, which shows the document at the mobile-optimized size that you intended.
How do you make sure your website works properly? - Learn web development
resources like webpagetest.org or browser add-ons like yslow can tell you a few interesting things: grades go from a to f.
... ping is a useful shell tool that tests the domain name you provide and tells you if the server's responding or not: $ ping mozilla.org ping mozilla.org (63.245.215.20): 56 data bytes 64 bytes from 63.245.215.20: icmp_seq=0 ttl=44 time=148.741 ms 64 bytes from 63.245.215.20: icmp_seq=1 ttl=44 time=148.541 ms 64 bytes from 63.245.215.20: icmp_seq=2 ttl=44 time=148.734 ms 64 bytes from 63.245.215.20: icmp_seq=3 ttl=44 time=147.857 ms ^c --- mozilla.org ping statistics --- 4 packets transmitted, 4 pa...
... ctrl+c sends an “interrupt” signal to the runtime and tells it to stop.
... if you don't stop the runtime, ping will ping the server indefinitely.
The HTML5 input types - Learn web development
it is a helpful aid to guide users to fill out a form accurately, and it can save time — it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server.
... phone number field a special field for filling in phone numbers can be created using tel as the value of the type attribute: <input type="tel" id="tel" name="tel"> when accessed via a touch device with a dynamic keyboard, most devices will display a numeric keypad when type="tel" is encountered, meaning this type is useful whenever a numeric keypad is useful, and doesn't just have to be used for telephone numbers.
...if the range is too large for incremental increases to make sense (such as usa zip codes, which range from 00001 to 99999), the tel type might be a better option; it provides the numeric keypad while forgoing the number's spinner ui feature.
...then we immediately set the output's textcontent to the current value of the input.
UI pseudo-classes - Learn web development
to fix this we style the parent <div> to become a flex container, but also tell it to wrap its contents onto new lines if the content becomes too long: fieldset > div { margin-bottom: 20px; display: flex; flex-flow: row wrap; } the effect this has is that the label and input sit on separate lines because they are both width: 100%, but the <span> has a width of 0 so can sit on the same line as the input.
...we then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively.
... now finally, we've used some javascript to 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.queryselectorall('#billing input[type="text"]'); // select the billing text labels let billinglabels = document.queryselectorall('.billing-label'); // toggle the billing text fields and labels for (let i = 0; i < ...
...one use case could be an indicator to tell users that they really need to select a radio button before they move on.
Tips for authoring fast-loading HTML pages - Learn web development
then you just apply the same image each time you need it for a background and adjust the x/y coordinates appropriately.
... specify sizes for images and tables if the 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.
...switching to lazy loading of images tells the browser to hold off on loading images until they're about to be needed to draw the visual viewport.
...interaction scripts typically can only run after the page has completely loaded and all necessary objects have been initialized.
Arrays - Learn web development
if we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item.
...try the following: shopping.length; // should return 5 this has other uses, but it is most commonly used to tell a loop to keep going until it has looped through all the items in an array.
... 4 // number 5 let itemtext = 0; const listitem = document.createelement('li'); listitem.textcontent = itemtext; list.appendchild(listitem); } totalbox.textcontent = 'total: $' + total.tofixed(2); </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="show solution"> </div> const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); let code = textarea.value; let userentry = textarea.value; function updatecode() { eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = jssolution; solution.value = 'show solution'; ...
...us(); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); let code = textarea.value; let userentry = textarea.value; function updatecode() { eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = jssolution; solution.value = 'show solution'; ...
What went wrong? Troubleshooting JavaScript - Learn web development
sure enough, loworhi's value is null at this point, so there is definitely a problem with line 48.
... syntax errors round three now if you try playing the game through again, you should get more success — the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of guesses.
...definitely not quite how we want the game to play out!
... there's definitely a problem in the game logic somewhere — the game is not returning an error; it just isn't playing right.
Aprender y obtener ayuda - Learn web development
for example: materials i need: a computer internet access pens and paper knowledge i need: how to use html, css, javascript, and associated tools and best practices to build web sites and web applications (we can definitely help you with this one!).
...don't try to work in a room with distractions — for example a television on, with your friends watching football!
... style hover/focus/active states of menu items appropriately.
...for example, professional web developers have created lots of horizontal navigation menus, so they'll immediately start thinking of a solution like this: a nav menu is usually created from a list of links, something like: <ul> <li>first menu item</li> <li>second menu item</li> <li>third menu item</li> <li>etc.</li> </ul> to make all the items sit horizontally on a line, the easiest modern way is to use flexbox: ul { display: flex; } to remove unneeded spacing and bullet points, we can do thi...
Server-side web frameworks - Learn web development
the model doesn't state any information about the underlying database as that is a configuration setting that may be changed separately of our code.
...if you're starting from absolutely no programming experience then consider django (it is one of the easiest to learn based on the above criteria).
... built-in testing facility and code formatter (deno fmt) (javascript) browser compatibility: deno programs that are written completely in javascript excluding the deno namespace (or feature test for it), should work directly in any modern browser.
... although definitely not the only framework based on java it is easy to use to create stand-alone, production-grade spring-based applications that you can "just run".
Website security - Learn web development
a reflected xss vulnerability occurs when user content that is passed to the server is returned immediately and unmodified for display in the browser.
...however, a malicious user could completely change the behavior of this sql statement to the new statement in the following example, by simply specifying the text in bold for the username.
...by putting a backslash in front of this character (\'), we escape the symbol, and tell sql to instead treat it as a character (just a part of the string).
...clickjacking could also be used to get the user to click a button on a visible site, but in doing so actually unwittingly click a completely different button.
Beginning our React todo list - Learn web development
we have a heading that tells us how many tasks remain.
...for example: <button type="button" classname="btn toggle-btn" aria-pressed="true"> <span classname="visually-hidden">show </span> <span>all</span> <span classname="visually-hidden"> tasks</span> </button> here, aria-pressed tells assistive technology (like screen readers) that the button can be in one of two states: pressed or unpressed.
... the aria-labelledby attribute tells assistive technologies that we're treating our list heading as the label that describes the purpose of the list beneath it.
... finally, the labels and inputs in our list items have some attributes unique to jsx: <input id="todo-0" type="checkbox" defaultchecked={true} /> <label classname="todo-label" htmlfor="todo-0"> eat </label> the defaultchecked attribute in the <input/ > tag tells react to check this checkbox initially.
Componentizing our Svelte app - Learn web development
you'll notice that when you click on the filter buttons, they are selected and the style updates appropriately.
... using bind, we will tell svelte that any changes made to the filter prop in the filterbutton component should propagate back up to the parent component, todos.
...in addition, the remove event listener is sending the daa change back up to the parent, so our "x out of y items completed" status heading will now update appropriately when todos are deleted.
...and our "x out of y items completed" status heading will now update appropriately when todos are completed.
Dynamic behavior in Svelte: working with variables and props - Learn web development
observe how the numbers in the message are updated appropriately.
... so with export let todos = [], we are telling svelte that our todos.svelte component will accept a todos attribute, which when omitted will be initialized to an empty array.
... we can tell svelte that we want our totaltodos and completedtodos variables to be reactive by prefixing them with $:.
...in this case, the preventdefault modifier tells svelte to generate the code to call event.preventdefault() before running the handler.
Creating our first Vue component - Learn web development
this will tell vue that we expect every instance of this component to have a label field.
...this tells vue that we expect the value of this property to be a string.
...this tells vue we expect the value prop to be a javascript boolean type.
...this is to keep the data values unique for each instance of a component at runtime — the function is invoked separately for each component instance.
Handling common HTML and CSS problems - Learn web development
in our debugging html and debugging css articles, we provided some really basic guidance on debugging html/css — if you are not familiar with the basics, you should definitely study these articles before carrying on.
...if a browser encounters a declaration or rule it doesn't understand, it just skips it completely without applying it or throwing an error.
... 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).
... store a reference to this element in a variable, for example: const test = document.getelementbyid('hplogo'); now try to set a new value for the css property you are interested in on that element; you can do this using the style property of the element, for example try typing these into the javascript console: test.style.transform = 'rotate(90deg)' test.style.webkittransform = 'rotate(90deg)' as you start to type the property name representation after the second dot (note tha...
Handling common JavaScript problems - Learn web development
if you want this to work correctly, you need to define a function to add the handler separately, calling it on each iteration and passing it the current value of para and i each time (or something similar).
... using the javascript debugger unfortunately, we still have the same error — the problem has not gone away.
...to give you a clue, you can either tell the xmlhttprequest object explicitly to return json format, or convert the returned text to json after the response arrives.
...this all made browser sniffing even more error prone, and ultimately pointless.
Strategies for carrying out testing - Learn web development
by coding defensively, we mean trying to build in intelligent fallbacks so that if a feature or style doesn't work in a browser, the site will be able to downgrade to something less exciting that still provides an acceptable user experience — the core information is still accessible, for example, even if it doesn't look quite as nice.
...of course, this relies on you already having a site to use it on, so it isn't much good for completely new sites.
...you should definitely include accessibility as a grade a testing requirement (we'll cover exactly what you should test in our handling common accessibility problems article) plus you might have other considerations.
...this unfortunately only runs on a mac.
Command line crash course - Learn web development
windows has traditionally had its own terminal-like program called cmd (“the command prompt”) for a long time, but this definitely doesn’t have parity with unix commands, and is equivalent to the old-style windows dos prompt.
...fortunately, a small change to the command usage can give you a lot more information.
...try it now: curl /docs/web/api/fetch we need to explicitly tell curl to follow redirects using the -l flag.
... the vast ecosystem of installable tools for front end web development currently exists mostly inside npm, a privately owned, package hosting service that works closely together with node.js.
Multiprocess on Windows
unfortunately this topic is often poorly explained.
...unfortunately, crossing apartment boundaries using com incurs the exact same problem as crossing process boundaries: if we directly use com's built in marshaling capabilities to forward an rpc from the mta to the main thread sta, com will still use the sta's message queue, thus defeating the purpose of using the mta in the first place!
...without the support for length_is and size_is annotations, the interceptor cannot tell the difference between a scalar outparam and an array outparam.
...this should usually be set to vt_unknown | vt_byref, which is telling the interceptor that the outparam is an iunknown**.
Mozilla’s UAAG evaluation report
also, in the overwhelming majority of cases, the filename is unintelligible.
...(p2) p our interface for image toggling needs redesign unfortunately, there are quite a few open bugs on image toggling guideline 4.
...unforutunately, some are hard coded.
... unfortunately, switching profiles requires the entire application to be relaunched.
mach
it's a python script that creates an instance of the mach core, registers commands with it, then tells the mach core to execute.
... the decorators are: @commandprovider this is a class decorator that tells mach that this class contains methods that implement mach commands.
... @command this is a method decorator that tells mach that this method implements a mach command.
... @commandargument this is a method decorator that tells mach about an argument to a mach command.
Performance
performance best practices declaring stateless functions once per process bad: // addon.js services.mm.loadframescript("framescript.js", true) // framescript.js const precomputedconstants = // ...
...sage.target result = helper(frameglobal.content, message.data) frameglobal.sendasyncmessage("my-addon:response-from-child", {something: result}) } function addframe(frameglobal) { frameglobal.addmessagelistener("my-addon:request-from-parent", dosomething) } javascript modules are per-process singletons and thus all their objects are only initialized once, which makes them suitable for stateless callbacks.
...not only does that increase memory footprint but the deserialization also has to be executed seperately for each tab, thus requiring more cpu time.
...um) } tabmm.addmessagelistener("my-addon:paragraph-count", callback); tabmm.loadframescript("data:,sendasyncmessage('my-addon:paragraph-count', {num: content.document.queryselectorall('p').length})", false) } function decoratebutton(button, count) { // do stuff with result } this executes the script only when it is needed and only in one tab and allows it to be garbage-collected immediately after execution.
IPDL Tutorial
because protocol messages are represented as c++ methods, it's easy to forget that they are in fact asynchronous messages: by default the c++ method will return immediately, before the message has been delivered.
...the message is sent, and the c++ method returns immediately.
...if you absolutely need to block on a reply, use sync semantics very carefully.
...any time a message implementation returns false, ipdl will immediately begin catastrophic error handling: the communication channels for the child process (tab or plugin) will be disconnected, and the process will be terminated.
Addon
overview of required methods void iscompatiblewith(in string appversion, in string platformversion) void findupdates(in updatelistener listener, in integer reason, in string appversion, in string platformversion) overview of optional methods void uninstall() void canceluninstall() boolean hasresource(in string path) nsiuri getresourceuri(in string path) void getdatadirectory(in datadirectorycallback callback) required properties attribute type de...
...for some add-ons this will change immediately based on the appdisabled and userdisabled properties; for others it will only change after an application restart.
... void findupdates( in updatelistener listener, in integer reason, in string appversion, in string platformversion ) parameters listener an updatelistener for the update process reason a reason code for performing the update appversion an application version to check for updates for platformversion a platform version to check for updates for optional methods uninstall() uninstalls this add-on.
... if possible the uninstall will happen immediately, otherwise it will wait until the next application restart.
Log.jsm
expect these to be immediately visible on a status console.
...expect these to be immediately visible on a status console.
...expect these to be immediately visible on a status console.
...expect these to be immediately visible on a console, so be conservative and keep to a minimum.
Localization content best practices
for example, suppose this string needs to be changed from "event" to "add new event": new-event-header = event add-new-event-header is definitely a better choice for the new string than new-event-header1.
... create localizable strings don't assume grammar structures you need to consider the need for different grammar structures in different locales, and add switching mechanisms to present them appropriately.
...unfortunately, this won't work at all: you need at least a third string to place after the link, without that some languages won't be able to create a natural sounding sentence.
...if you have doubts about the localizability of some text or structure (not about the text itself, that would need copywriters), it's definitely good to ask feedback.
Release phase
consequently, if you already have a local clone that you pulled using http, you'll need to modify a config file to tell mercurial to push through ssh.
...configuration before you try pushing, you need to tell ssh which username you wish to use for connecting with hg.mozilla.org.
... the following lines to your ~/.ssh/config file, replacing user@host.domain with your mozilla ldap account name: host hg.mozilla.org user user@host.domain if you have already cloned the remote repository using the http protocol using this command: $ hg clone http://hg.mozilla.org/releases/l10n-central/x-testing then you will need to edit the .hg/hgrc file (inside the x-testing local clone) to tell mercurial to push using ssh.
... if you don't see this message, try running the same command in a more verbose mode (with the debugging information): $ ssh -vvv hg.mozilla.org this should tell you why your connection is not succeeding.
Memory reporting
this is most obviously used in about:memory and telemetry.
...this is important because sometimes an object might be embedded in another object that is measured separately.
...because you want to show them separately in about:memory.
... dmd is absolutely crucial; these things cannot be done without it.
Build instructions
ns_use_gcc: on platforms where gcc is not the native compiler, tells nss to build with gcc instead of the native compiler.
... use_64: on platforms that support both 32-bit and 64-bit abis, tells nss to build for the 64-bit abi.
... moz_debug_symbols: tells nss to build with debug symbols, even in an optimized build.
... on windows, in both debug and optimized builds, when using msvc, tells nss to put symbols in a .pdb file.
NSS functions
mxr 3.2 and later cert_decodeprivkeyusageperiodextension mxr 3.10 and later cert_decodetruststring mxr 3.4 and later cert_decodeusernotice mxr 3.2 and later cert_dernametoascii mxr 3.4 and later cert_destroycertarray mxr 3.2 and later cert_destroycertificate mxr 3.2 and later cert_destroycertificatelist mxr 3.2 and later cert_destroycertificatepoliciesextension mxr 3.2 and later cert_destroycertificaterequest mxr 3.2 and later cert_destroycertlist mxr 3.2 and later cert_destroyname mxr 3.2 and later cert_destroyocspcertid mxr 3.6 and later cert_destroyocsprequest mxr 3.6 and later cert_des...
...indslotbyname mxr 3.2 and later pk11_findslotsbynames mxr 3.9 and later pk11_fortezzahaskea mxr 3.2 and later pk11_fortezzamapsig mxr 3.2 and later pk11_freeslot mxr 3.2 and later pk11_freeslotlist mxr 3.2 and later pk11_freeslotlistelement mxr 3.11 and later pk11_freesymkey mxr 3.2 and later pk11_generatefortezzaiv mxr 3.2 and later pk11_generatekeypair mxr 3.2 and later pk11_generatekeypairwithflags mxr 3.10.2 and later pk11_generatekeypairwithopflags mxr 3.12 and later ...
... mxr 3.2 and later nssbase64_encodeitem mxr 3.4 and later nssbase64encoder_create mxr 3.2 and later nssbase64encoder_destroy mxr 3.2 and later nssbase64encoder_update mxr 3.2 and later nssrwlock_destroy mxr 3.2 and later nssrwlock_havewritelock mxr 3.2 and later nssrwlock_lockread mxr 3.2 and later nssrwlock_lockwrite mxr 3.2 and later nssrwlock_new mxr 3.2 and later nssrwlock_unlockread mxr 3.2 and later nssrwlock_unlockwrite mxr 3.2 and later nsssmime_versioncheck ...
... 3.3 and later sec_pkcs7encodeitem mxr 3.9.3 and later sec_pkcs7encoderabort mxr 3.9 and later sec_pkcs7encoderfinish mxr 3.2 and later sec_pkcs7encoderstart mxr 3.2 and later sec_pkcs7encoderupdate mxr 3.2 and later sec_pkcs7getcertificatelist mxr 3.2 and later sec_pkcs7getcontent mxr 3.2 and later sec_pkcs7getencryptionalgorithm mxr 3.2 and later sec_pkcs7getsignercommonname mxr 3.4 and later sec_pkcs7getsigneremailaddress mxr 3.4 and later sec_pkcs7getsigningtime mxr 3.4 and later ...
Hacking Tips
since there isn't debug info for the jitted code, you will need to tell gdb that you are looking at arm code: (gdb) set arm force-mode arm or you can wrap the x command in your own command: def xi set arm force-mode arm eval "x/%di %d", $arg0, $arg1 set arm force-mode auto end printing asm.js/wasm generated assembly code (from gdb) set a breakpoint on js::wasm::instance::callexport (defined in wasminstance.cpp as of november 18th 2016).
... $ valgrind --smc-check=all-non-file --vex-iropt-register-updates=allregs-at-mem-access --vgdb-error=0 ./js … this command will tell you how to start gdb as a remote.
... $ cgset -r cpuset.mems=0 /benchmarks $ cgset -r cpuset.mems=0 /benchmarks/mask $ cgset -r cpuset.mems=0 /benchmarks/negate-mask then we limit the performance of the cpu, as a proportion such as the result approximately correspond to what you might have if you were running on a phone.
... for example an unagi is approximately 40 times slower than my computer.
Property cache
entry->vcap caches the results of part 1 above, telling which object contains the desired property.
...jsobject::objshape tells an object's shape.
... teleportation.
...the jit code "teleports" directly to the appropriate object.
Finishing the Component
* * a user of a service may keep references to particular services * indefinitely and only must call release when it shuts down.
...also, provides access to the url that are whitelisted.
... if you care to extend this implementation so that the list of urls is held remotely on a server somewhere - as might be the case when the weblock component is used in a corporate intranet, for example - there are networking apis in gecko that will support this.
...if the scheme isn't "http", "https", or "ftp", it immediately returns true, which continues the loading process unblocked.
Setting up the Gecko SDK
the following four sections tell the developer how to download and organize the gecko sdk and create a new project in which components like weblock can be created.
... environment setup you can create a batch file to set up the environment for you, but this example tells you from the command prompt.
... set lib=c:\program files\microsoft sdks\windows\v7.0\lib;c:\program files (x86)\microsoft visual studio 9.0\vc\lib;d:\projects\xulrunner-sdk\lib this tells the linker where the default libraries to bind to are.
... this allows you to created the component without sending any extra dlls set path=%path%;d:\projects\xulrunner-sdk\sdk\bin;d:\projects\xulrunner-sdk\bin this tells the command prompt where to find the gecko tools, importantly (xpidl, regxpcom, and gmake).
Using XPCOM Components
the iweblock interface lock lock the browser to the current site (or to the whitelist of approved sites read from disk).
... addsite add a new site to the whitelist.
... removesite remove a given site from the whitelist.
... sites enumerator for the list of approved sites read in from the whitelist.
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
most streams are asynchronous: they make no assumptions that all the data a resource provides is available immediately.
...from the nsirequestobserver interface, the .onstartrequest(request, context) method tells you when the request begins, while the .onstoprequest(request, context) method tells you when the request ends.
... there are two parts: initializing the pump, and telling it to asynchronously read data into the stream listener: var pump = components.classes["@mozilla.org/network/input-stream-pump;1"] .createinstance(components.interfaces.nsiinputstreampump); pump.init(stream, -1, -1, 0, 0, true); pump.asyncread(listener, context); nsipipe code examples file input and output for file input, see code snippets: reading from a file.
... * * also, baseinputstream has been completely consumed at this point, so we * shouldn't read from it anymore.
Interfacing with the XPCOM cycle collector
handling jsobjects fields if your class needs to store a pointer to a jsobject then you need to tell the cycle collector about it.
... when you have something in the js object pointer you need to use mozilla::holdjsobjects to tell the gc to trace it and keep the object alive: ...
...unfortunately this macro defines the trace method and so you can't list your js object; hence, you need to also manually implmenet trace and unlink as above.
...hence, we need to tell the cycle collector about any such member variables.
IAccessibleTable
iscolumnselected() returns a boolean value indicating whether the specified column is completely selected.
...isselected returns true if the specified column is selected completely and false otherwise.
...isrowselected() returns a boolean value indicating whether the specified row is completely selected.
...isselected returns true if the specified row is selected completely and false otherwise.
IAccessibleTable2
iscolumnselected() returns a boolean value indicating whether the specified column is completely selected.
...isselected returns true if the specified column is selected completely and false otherwise.
...isrowselected() returns a boolean value indicating whether the specified row is completely selected.
...isselected returns true if the specified row is selected completely and false otherwise.
nsIDOMWindowUtils
sheets added via this api take effect immediately on the document.
...if you don't need an absolutely up to date node list, you can set this to false.
...the removal takes effect immediately.
...the displayport can approximately be thought of as a "persistent" drawwindow() (albeit with coordinates relative to the css viewport): the bounds are remembered by the platform, and layer pixels are retained and updated inside the viewport bounds.
nsIWebNavigation
methods goback() tells the object to navigate to the previous session history item.
... void goback( ); goforward() tells the object to navigate to the next session history item.
... void goforward( ); gotoindex() tells the object to navigate to the session history item at a given index.
... reload() tells the object to reload the current page.
Working with windows in chrome code
note however, that the open() call returns before the window is fully loaded, so some calls, like win.document.getelementbyid() will fail.
...to access the elements and variables inside the sidebar, you need to use document.getelementbyid("sidebar").contentdocument or .contentwindow, like when accessing content documents.
... {status: "reading remote data", maxprogress: 50, progress: 10} ); progress.xul: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window onload="onload();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script><![cdata[ var gstatus, gprogressmeter; var maxprogress = 100; function onload() { gstatus = document.getelementbyid("status"); gprogressmeter = document.getelementbyid("progressmeter"); if("arguments" in window && window.arguments.length > 0) { maxprogress = window.arguments[0].maxprogress; setprogress(window.arguments[0].progress); setstatus(window.arguments[0].status); } } function setprogress(value) { gprogressmeter.value = 100 * value / maxprogress; } function setstatus(text...
...you could declare a local variable in each window along with corresponding setter functions to keep the "instances" of the variable in sync across windows, but fortunately, there's a better way.
Mozilla
fortunately, over the years, mozilla developers have come up with not just technologies and features to help you debug code, but have devised tips and techniques that can help too.
...a stacktrace will tell mozilla developers what crashed and provide a starting point for investigating its cause.
...it is intended primarily for developers, and deliberately omits some topics that will be important in any redis deployment, like security and backups.
... zombie compartments this page tells you how to detect and avoid zombie compartments, which are a particular kind of memory leak.
Plug-in Basics - Plugins
unlike a plug-in, a helper application runs separately from the browser in its own application space and does not interact with the browser or the web.
... how plug-ins work the life cycle of a plug-in, unlike that of an application, is completely controlled by the web page that calls it.
... var plugin = mimetype.enabledplugin; if (plugin) { // yes, so show the data in-line document.writeln("here\'s a movie: <object data='mymovie.swf' height='100' width='100'></object>"); } else { // no, so provide a link to the data document.writeln("<a href='mymovie.swf'>click here</a> to see a movie."); } } else { // no, so tell them so document.writeln("sorry, can't show you this movie."); } overview of plug-in structure this section is an overview of basic informatio...
...this type of plug-in completely fills the web page.
Streams - Plugins
in normal-mode streams, the browser calls the plug-in to tell it when a stream is created and to push more data.
... receiving a stream sending a stream receiving a stream when the browser sends a data stream to the plug-in, it has several tasks to perform: telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode telling the plug-in when a stream is created to tell the plug-in instance when a new stream is created, the browser calls the npp_newstream method.
... telling the plug-in when a stream is deleted the browser calls the npp_destroystream method when it completes the stream sent to the plug-in, either successfully or abnormally.
...this number tells the browser that it can pass as much data to the instance as possible in a single call to npp_write.
Examine and edit HTML - Firefox Developer Tools
(paste) before paste the clipboard contents into the document immediately before this node.
... (paste) after paste the clipboard contents into the document immediately after this node.
... duplicate node create a copy of this element, and insert the copy immediately after this element.
... editing html you can edit the html — tags, attributes, and content — directly in the html pane: double-click the text you want to edit, change it, and press enter to see the changes reflected immediately.
Intensive JavaScript - Firefox Developer Tools
it gives us a compressed view of the waterfall, which tells us what kinds of operations the browser is doing during the recording.
...we can see that frame rate is pretty healthy for most of the recording, but collapses completely whenever we press the button.
... requestanimationframe() tells the browser to run the given function in each frame, just before it performs a repaint.
... 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } } return primes; } in the worker, we have to listen for a message telling us to start, and send a "done" message back when we are done.
AbstractRange - Web APIs
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.queryselector("p"); let endelem = startelem.queryselector("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 c...
... to illustrate this, consider the html below: <div class="container"> <div class="header"> <img src="" class="sitelogo"> <h1>the ultimate website</h1> </div> <article> <section class="entry" id="entry1"> <h2>section 1: an interesting thing...</h2> <p>a <em>very</em> interesting thing happened on the way to the forum...</p> <aside class="callout"> <h2>aside</h2> <p>an interesting aside to share with you...</p> </aside> </section> </article> <pre id="lo...
... as it turns out, the dom specification fortunately addresses this exact issue.
...the code to do that looks like the following: let paranode = document.queryselector("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.
AuthenticatorAssertionResponse.authenticatorData - Web APIs
syntax var authnrdata = authenticatorassertionresponse.authenticatordata; value an arraybuffer that has a arraybuffer.bytelength of at least 37 bytes, containing the following fields: rpidhash (32 bytes) - a sha256 hash of the relying party id that was seen by the browser.
... bit 6, attested credential data (at) - if set, attestedcredentialdata will immediately follow the first 37 bytes of this authenticatordata.
...extension data will follow attestedcredentialdata if it is present, or will immediatelly follow the first 37 bytes of the authenticatordata if no attestedcredentialdata is present.
... credentialidlength (2 bytes) - the length of the credential id that immediately follows these bytes.
CanvasRenderingContext2D.arcTo() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // tangential lines ctx.beginpath(); ctx.strokestyle = 'gray'; ctx.moveto(200, 20); ctx.lineto(200, 130); ctx.lineto(50, 20); ctx.stroke(); // arc ctx.beginpath(); ctx.strokestyle = 'black'; ctx.linewidth = 5; ctx.moveto(200, 20); ctx.arcto(200,130, 50,20, 40); ctx.stroke(); // start point ctx.beginpath(); ctx.fillstyle = 'blue'; ctx.arc...
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const p0 = { x: 230, y: 20 } const p1 = { x: 90, y: 130 } const p2 = { x: 20, y: 20 } const labelpoint = function (p) { const offset = 15; ctx.filltext('(' + p.x + ',' + p.y + ')', p.x + offset, p.y + offset); } ctx.beginpath(); ctx.moveto(p0.x, p0.y); ctx.arcto(p1.x, p1.y, p2.x, p2.y, 50); ctx.lineto(p2.x, p2.y); labelpoint(p0)...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(180, 90); ctx.arcto(180,130, 110,130, 130); ctx.lineto(110, 130); ctx.stroke(); result live demo more sophisticated demo of the method.
... html <div> <label for="radius">radius: </label> <input name="radius" type="range" id="radius" min=0 max=100 value=50> <label for="radius" id="radius-output">50</label> </div> <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const controlout = document.getelementbyid('radius-output'); const control = document.getelementbyid('radius'); control.oninput = () => { controlout.textcontent = r = control.value; }; const mouse = { x: 0, y: 0 }; let r = 100; // radius const p0 = { x: 0, y: 50 }; const p1 = { x: 100, y: 100 }; const p2 = { x: 150, y: 50 }; const p3 = { x: 200, y: 100 }; const labelpoint = function (p,...
Drawing text - Web APIs
function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.font = '48px serif'; ctx.filltext('hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); a stroketext example the text is filled using the current strokestyle.
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.font = '48px serif'; ctx.stroketext('hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); styling text in the examples above we are already making use of the font property to make the text a bit larger than the default size.
...le code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ctx.font = "48px serif"; ctx.textbaseline = "hanging"; ctx.stroketext("hello world", 0, 100);</textarea> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var edit = document.getelementbyid('edit'); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; dra...
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); var text = ctx.measuretext('foo'); // textmetrics object text.width; // 16; } gecko-specific notes in gecko (the rendering engine of firefox, firefox os and other mozilla based applications), some prefixed apis were implemented in earlier versions to draw text on a canvas.
Pixel manipulation with canvas - Web APIs
<canvas id="canvas" width="300" height="227" style="float:left"></canvas> <div id="color" style="width:200px;height:50px;float:left"></div> var img = new image(); img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg'; var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); img.onload = function() { ctx.drawimage(img, 0, 0); img.style.display = 'none'; }; var color = document.getelementbyid('color'); function pick(event) { var x = event.layerx; var y = event.layery; var pixel = ctx.getimagedata(x, y, 1, 1); var data = pixel.data; var rgba = 'rgba(' + data[0] + ', ' + data[1] + ', ' + d...
... <canvas id="canvas" width="300" height="227"></canvas> <div> <input id="grayscalebtn" value="grayscale" type="button"> <input id="invertbtn" value="invert" type="button"> </div> var img = new image(); img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg'; img.onload = function() { draw(this); }; function draw(img) { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); img.style.display = 'none'; var imagedata = ctx.getimagedata(0, 0, canvas.width, canvas.height); var data = imagedata.data; var invert = function() { for (var i = 0; i < data.length; i += 4) { data[i] = 255 - data[i]; // red data[i + 1] = 255 - data[i + 1]; // green data[i +...
... 2] = 255 - data[i + 2]; // blue } ctx.putimagedata(imagedata, 0, 0); }; var grayscale = function() { for (var i = 0; i < data.length; i += 4) { var avg = (data[i] + data[i + 1] + data[i + 2]) / 3; data[i] = avg; // red data[i + 1] = avg; // green data[i + 2] = avg; // blue } ctx.putimagedata(imagedata, 0, 0); }; var invertbtn = document.getelementbyid('invertbtn'); invertbtn.addeventlistener('click', invert); var grayscalebtn = document.getelementbyid('grayscalebtn'); grayscalebtn.addeventlistener('click', grayscale); } zooming and anti-aliasing with the help of the drawimage() method, a second canvas and the imagesmoothingenabled property, we are able to zoom into our picture and see the details.
...ght="227"></canvas> <canvas id="zoom" width="300" height="227"></canvas> <div> <label for="smoothbtn"> <input type="checkbox" name="smoothbtn" checked="checked" id="smoothbtn"> enable image smoothing </label> </div> var img = new image(); img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg'; img.onload = function() { draw(this); }; function draw(img) { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); img.style.display = 'none'; var zoomctx = document.getelementbyid('zoom').getcontext('2d'); var smoothbtn = document.getelementbyid('smoothbtn'); var togglesmoothing = function(event) { zoomctx.imagesmoothingenabled = this.checked; zoomctx.mozimagesmoothingenabled = this.checked; zoomctx.webk...
Document.execCommand() - Web APIs
createlink creates an hyperlink from the selection, but only if there is a selection.
... enableabsolutepositioneditor enables or disables the grabber that allows absolutely-positioned elements to be moved around.
... enableobjectresizing enables or disables the resize handles on images, tables, and absolutely-positioned elements and other resizable objects.
...the requirements for this string are the same as createlink.
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
note that authors are discouraged from using fill modes to persist the effect of an animation indefinitely.
...in this case, we have just two keyframes; the first defines what affect is applied to the element immediately after the animation first begins to play, and the second defines the effect applied to the element in the last moment before it ends.
... document.getelementbyid("animatebutton").addeventlistener("click", event => { document.getelementbyid("box").animate( boxrotationkeyframes, boxrotationtiming ); }, false); the rest of the code is pretty simple: it adds an event listener to the "animate" button so that when it's clicked by the user, the box is animated by calling element.animate() on it, providing the boxrotationkeyframes and boxrot...
...when used to persist the effect of an animation indefinitely, however, they have a number of drawbacks: the forwards fill of an animation (or backwards fill if the animation is playing in reverse) will continue to override any changes to specified style indefinitely which can lead to confusing behavior.
Element: fullscreenchange event - Web APIs
the fullscreenchange event is fired immediately after an element switches into or out of full-screen mode.
... html <h1>fullscreenchange event example</h1> <div id="fullscreen-div"> <button id="toggle-fullscreen">toggle fullscreen mode</button> </div> javascript document.getelementbyid('fullscreen-div').addeventlistener('fullscreenchange', (event) => { // document.fullscreenelement will point to the element that // is in fullscreen mode if there is one.
... if (document.fullscreenelement) { console.log(`element: ${document.fullscreenelement.id} entered fullscreen mode.`); } else { console.log('leaving full-screen mode.'); } }); document.getelementbyid('toggle-fullscreen').addeventlistener('click', (event) => { if (document.fullscreenelement) { // exitfullscreen is only available on the document object.
... document.exitfullscreen(); } else { document.getelementbyid('fullscreen-div').requestfullscreen(); } }); specifications specification status fullscreen api living standard ...
Guide to the Fullscreen API - Web APIs
let's consider this <video> element: <video controls id="myvideo"> <source src="somevideo.webm"></source> <source src="somevideo.mp4"></source> </video> we can put that video into full-screen mode as follows: var elem = document.getelementbyid("myvideo"); if (elem.requestfullscreen) { elem.requestfullscreen(); } this code checks for the existence of the requestfullscreen() method before calling it.
... other information the document provides some additional information that can be useful when developing fullscreen web applications: documentorshadowroot.fullscreenelement the fullscreenelement property tells you the element that's currently being displayed fullscreen.
... document.fullscreenenabled the fullscreenenabled property tells you whether or not the document is currently in a state that would allow fullscreen mode to be requested.
... function togglefullscreen() { if (!document.fullscreenelement) { document.documentelement.requestfullscreen(); } else { if (document.exitfullscreen) { document.exitfullscreen(); } } } this starts by looking at the value of the fullscreenelement attribute on the document (checking it prefixed with both moz, ms, or webkit).
Fullscreen API - Web APIs
returns a promise which is resolved once full-screen mode has been completely shut off.
... documentorshadowroot.fullscreenelement the fullscreenelement property tells you the element that's currently being displayed in full-screen mode on the dom (or shadow dom).
... document.fullscreenenabled the fullscreenenabled property tells you whether or not it is possible to engage full-screen mode.
... function togglefullscreen() { if (!document.fullscreenelement) { document.documentelement.requestfullscreen(); } else { if (document.exitfullscreen) { document.exitfullscreen(); } } } this starts by looking at the value of the document's fullscreenelement attribute.
Using the Gamepad API - Web APIs
var gamepadinfo = document.getelementbyid("gamepad-info"); var ball = document.getelementbyid("ball"); var start; var a = 0; var b = 0; next we use the gamepadconnected event to check for a gamepad being connected.
...in each execution of the loop we check if one of four buttons is being pressed; if so, we update the values of the a and b movement variables appropriately, then update the left and top properties, changing their values to the current values of a and b respectively.
... a.classname = "axes"; for (var i = 0; i < gamepad.axes.length; i++) { var p = document.createelement("progress"); p.classname = "axis"; //p.id = "a" + i; p.setattribute("max", "2"); p.setattribute("value", "1"); p.innerhtml = i; a.appendchild(p); } d.appendchild(a); // see https://github.com/luser/gamepadtest/blob/master/index.html var start = document.getelementbyid("start"); if (start) { start.style.display = "none"; } document.body.appendchild(d); requestanimationframe(updatestatus); } function disconnecthandler(e) { removegamepad(e.gamepad); } function removegamepad(gamepad) { var d = document.getelementbyid("controller" + gamepad.index); document.body.removechild(d); delete controllers[gamepad.index]; } function updatesta...
...tus() { if (!haveevents) { scangamepads(); } var i = 0; var j; for (j in controllers) { var controller = controllers[j]; var d = document.getelementbyid("controller" + j); var buttons = d.getelementsbyclassname("button"); for (i = 0; i < controller.buttons.length; i++) { var b = buttons[i]; var val = controller.buttons[i]; var pressed = val == 1.0; if (typeof(val) == "object") { pressed = val.pressed; val = val.value; } var pct = math.round(val * 100) + "%"; b.style.backgroundsize = pct + " " + pct; if (pressed) { b.classname = "button pressed"; } else { b.classname = "button"; } } var axes = d.getelementsbyclassname("axis"); for (i = 0; i < controller.ax...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
while there have been tricks available that made it possible to enqueue microtasks in the past (such as by creating a promise that resolves immediately), the addition of the queuemicrotask() method adds a standard way to introduce a microtask safely and without tricks.
... let logelem = document.getelementbyid("log"); let log = s => logelem.innerhtml += s + "<br>"; in the following code, we see a call to queuemicrotask() used to schedule a microtask to run.
... let logelem = document.getelementbyid("log"); let log = s => logelem.innerhtml += s + "<br>"; in the following code, we see a call to queuemicrotask() used to schedule a microtask to run.
... let logelem = document.getelementbyid("log"); let log = s => logelem.innerhtml += s + "<br>"; the main program code follows.
MediaStreamTrack.stop() - Web APIs
syntax track.stop() description calling stop() tells the user agent that the track's source—whatever that source may be, including files, network streams, or a local camera or microphone—is no longer needed by the mediastreamtrack.
... since multiple tracks may use the same source (for example, if two tabs are using the device's microphone), the source itself isn't necessarily immediately stopped.
...once no media tracks are using the source, the source may actually be completely stopped.
... immediately after calling stop(), the readystate property is set to ended.
Recording a media element - Web APIs
note that the autoplay attribute is used so that as soon as the stream starts to arrive from the camera, it immediately gets displayed, and the muted attribute is specified to ensure that the sound from the user's microphone isn't output to their speakers, causing an ugly feedback loop.
...notice that the playback panel doesn't have autoplay set (so the playback doesn't start as soon as media arrives), and it has controls set, which tells it to show the user controls to play, pause, and so forth.
... let preview = document.getelementbyid("preview"); let recording = document.getelementbyid("recording"); let startbutton = document.getelementbyid("startbutton"); let stopbutton = document.getelementbyid("stopbutton"); let downloadbutton = document.getelementbyid("downloadbutton"); let logelement = document.getelementbyid("log"); let recordingtimems = 5000; most of these are references to elements we need to work with.
...so by setting the download link's download attribute to "recordedvideo.webm", we tell the browser that clicking the button should download a file named "recordedvideo.webm" whose contents are the recorded video.
Node.firstChild - Web APIs
WebAPINodefirstChild
<p id="para-01"> <span>first span</span> </p> <script> var p01 = document.getelementbyid('para-01'); console.log(p01.firstchild.nodename); </script> in the above, the console will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening <p> and <span> tags.
... <p id="para-01"><span>first span</span></p> <script> var p01 = document.getelementbyid('para-01'); console.log(p01.firstchild.nodename); </script> now the console will show 'span'.
... to avoid the issue with node.firstchild returning #text or #comment nodes, parentnode.firstelementchild can be used to return only the first element node.
... however, node.firstelementchild requires a shim for internet explorer 9 and earlier.
Node.insertBefore() - Web APIs
WebAPINodeinsertBefore
example example 1 <div id="parentelement"> <span id="childelement">foo bar</span> </div> <script> // create the new node to insert let newnode = document.createelement("span") // get a reference to the parent node let parentdiv = document.getelementbyid("childelement").parentnode // begin test case [ 1 ] : existing childelement (all works correctly) let sp2 = document.getelementbyid("childelement") parentdiv.insertbefore(newn...
... of id "childelement" parentdiv.insertbefore(newnode, sp2) // implicit dynamic cast to type node // end test case [ 2 ] // begin test case [ 3 ] : childelement is of type "undefined" ( string ) let sp2 = "undefined" // non-existent node of id "childelement" parentdiv.insertbefore(newnode, sp2) // generates "type error: invalid argument" // end test case [ 3 ] </script> example 2 <div id="parentelement"> <span id="childelement">foo bar</span> </div> <script> // create a new, plain <span> element let sp1 = document.createelement("span") // get the reference element let sp2 = document.getelementbyid("childelement") // get the parent element let parentdiv = sp2.parentnode // insert the new element into before sp2 parentdiv.insertbefore(sp1, sp2) </script> note: there is no insertafter...
... in the previous example, sp1 could be inserted after sp2 using: parentdiv.insertbefore(sp1, sp2.nextsibling) if sp2 does not have a next sibling, then it must be the last child — sp2.nextsibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).
... // get the parent element let parentelement = document.getelementbyid('parentelement') // get the parent's first child let thefirstchild = parentelement.firstchild // create a new element let newelement = document.createelement("div") // insert the new element before the first child parentelement.insertbefore(newelement, thefirstchild) when the element does not have a first child, then firstchild is null.
Page Visibility API - Web APIs
for example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user.
... note: while onblur and onfocus will tell you if the user switches windows, it doesn't necessarily mean it's hidden.
... policies in place to aid background page performance separately from the page visibility api, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs.
... { // opera 12.10 and firefox 18 and later support hidden = "hidden"; visibilitychange = "visibilitychange"; } else if (typeof document.mshidden !== "undefined") { hidden = "mshidden"; visibilitychange = "msvisibilitychange"; } else if (typeof document.webkithidden !== "undefined") { hidden = "webkithidden"; visibilitychange = "webkitvisibilitychange"; } var videoelement = document.getelementbyid("videoelement"); // if the page is hidden, pause the video; // if the page is shown, play the video function handlevisibilitychange() { if (document[hidden]) { videoelement.pause(); } else { videoelement.play(); } } // warn if the browser doesn't support addeventlistener or the page visibility api if (typeof document.addeventlistener === "undefined" || hidden === undefine...
Using the Payment Request API - Web APIs
in the code above, you'll see that we've called the paymentresponse.complete() method to signal that the interaction has finished — you'd use this to carry out finishing steps, like updating the user interface to tell the user the transaction is complete, etc.
... const checkoutbutton = document.getelementbyid('checkout-button'); if (window.paymentrequest) { let request = new paymentrequest(buildsupportedpaymentmethodnames(), buildshoppingcartdetails()); checkoutbutton.addeventlistener('click', function() { request.show().then(function(paymentresponse) { // handle successful payment }).catch(function(error) { // handle cancelled or failed payment.
... const checkoutbutton = document.getelementbyid('checkout-button'); checkoutbutton.innertext = "loading..."; if (window.paymentrequest) { let request = new paymentrequest(buildsupportedpaymentmethodnames(), buildshoppingcartdetails()); request.canmakepayment().then(function(canmakeafastpayment) { if (canmakeafastpayment) { checkoutbutton.innertext = "fast checkout with w3c"; } else { checkoutbutton.innert...
... const additionaldetailscontainer = document.getelementbyid('additional-details-container'); additionaldetailscontainer.style.display = 'block'; window.scrollto(additionaldetailscontainer.getboundingclientrect().x, 0); }).catch(function(error) { // handle error.
Pointer events - Web APIs
) { } function enter_handler(event) { } function down_handler(event) { } function move_handler(event) { } function up_handler(event) { } function cancel_handler(event) { } function out_handler(event) { } function leave_handler(event) { } function gotcapture_handler(event) { } function lostcapture_handler(event) { } function init() { var el=document.getelementbyid("target"); // register pointer event handlers el.onpointerover = over_handler; el.onpointerenter = enter_handler; el.onpointerdown = down_handler; el.onpointermove = move_handler; el.onpointerup = up_handler; el.onpointercancel = cancel_handler; el.onpointerout = out_handler; el.onpointerleave = leave_handler; el.gotpointercaptu...
... ev.pointertype + " is not suported"); } // call the tilt handler if (ev.tiltx != 0 && ev.tilty != 0) process_tilt(ev.tiltx, ev.tilty); // call the pressure handler process_pressure(ev.pressure); // if this event is not primary, call the non primary handler if (!ev.isprimary) process_non_primary(ev); } function init() { var el=document.getelementbyid("target"); // register pointerdown handler el.onpointerdown = down_handler; } </script> <body onload="init();"> <div id="target"> touch me ...
... <html> <script> function downhandler(ev) { let el = document.getelementbyid("target"); // element 'target' will receive/capture further events el.setpointercapture(ev.pointerid); } function init() { let el = document.getelementbyid("target"); el.onpointerdown = downhandler; } </script> <body onload="init();"> <div id="target"> touch me ...
... <html> <script> function downhandler(ev) { let el = document.getelementbyid("target"); // element "target" will receive/capture further events el.setpointercapture(ev.pointerid); } function cancelhandler(ev) { let el = document.getelementbyid("target"); // release the pointer capture el.releasepointercapture(ev.pointerid); } function init() { let el = document.getelementbyid("target"); // register pointerdown and pointercancel handlers el.onpointerdown = downhandler; el.onpointercancel = cancelhandler; ...
SVGTextPositioningElement - Web APIs
it is inherited by svgtextelement, svgtspanelement, svgtrefelement and svgaltglyphelement.
...roke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggraphicselement</text></a><polyline points="301,89 291,84 291,94 301,89" stroke="#d4dde4" fill="none"/><line x1="291" y1="89" x2="261" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgtextcontentelement" target="_top"><rect x="51" y="65" width="210" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="156" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextcontentelement</text></a><polyline points="51,89 41,84 41,94 51,89" stroke="#d4dde4" fill="none"/><line x1="41" y1="89" ...
...ll="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="-114" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextpositioningelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties this interface also inherits properties from its parent, svgtextcontentelement.
... methods this interface doesn't provide any specific methods, but inherits methods from its parent, svgtextcontentelement.
WEBGL_compressed_texture_etc - Web APIs
the rgb part is encoded the same as rgb_etc2, but the alpha part is encoded separately.
...the srgb part is encoded the same as srgb_etc2, but the alpha part is encoded separately.
... ext.compressed_rgb8_punchthrough_alpha1_etc2 similar to rgb8_etc, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
... ext.compressed_srgb8_punchthrough_alpha1_etc2 similar to srgb8_etc, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
WebGLRenderingContext - Web APIs
to get an access to a webgl context for 2d and/or 3d graphics rendering, call getcontext() on a <canvas> element, supplying "webgl" as the argument: var canvas = document.getelementbyid('mycanvas'); var gl = canvas.getcontext('webgl'); once you have the webgl rendering context for a canvas, you can render within it.
... webglrenderingcontext.blendequationseparate() sets the rgb blend equation and alpha blend equation separately.
... webglrenderingcontext.blendfuncseparate() defines which function is used for blending pixel arithmetic for rgb and alpha components separately.
...does not seem to support html5 canvas.</canvas> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : inline-block; width : 120px; height : 80px; margin : auto; padding : 0; border : none; background-color : black; } window.addeventlistener("load", function() { "use strict" var firstcanvas = document.getelementsbytagname("canvas")[0], secondcanvas = document.getelementsbytagname("canvas")[1]; firstcanvas.width = firstcanvas.clientwidth; firstcanvas.height = firstcanvas.clientheight; [firstcanvas, secondcanvas].foreach(function(canvas) { var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.queryselector("p").innerhtml = ...
Fundamentals of WebXR - Web APIs
fortunately, webgl and the various webgl-based frameworks and libraries are available to make it much easier to deal with all of that.
... field of view and mixed reality devices to achieve a wide enough field of view that the user's eyes are tricked into believing that the virtual world completely surrounds them, the fov needs to at least approach the width of the binocular vision area.
...when objects are drawn, they are drawn onto the goggles' lenses, either partially or completely blocking the physical environment from being seen through the obscured portion of the lens.
... caves a cave automated virtual environment (cave) is an immersive vr environment in which the scene is projected or otherwise displayed on the walls (as well as possibly the ceiling and/or floor), thus completely surrounding the user with the simulation and allowing them to be immersed in the scene.
Lighting a WebXR setting - Web APIs
fortunately, lighting isn't overly difficult to apply in your own vertex and fragment shaders.
... in essence, lighting estimation collects this information about the light sources and the shape and orientation of the objects in the scene, along with information about the materials they're made of, then returns data you can use to create virtual light source objects that approximately match the real world's lighting.
...by ensuring that the coordinates of the ar scene don't align with compass coordinates, and by reducing the precision of the sun's light angle, the location can no longer be accurately estimated using this technique.
...this could be done remotely, or it could be performed by an attacker who's located in the same room but wants to determine if the other person is also in the same room.
Migrating from webkitAudioContext - Web APIs
it was first implemented in webkit, and some of its older parts were not immediately removed as they were replaced in the specification, leading to many sites using non-compatible code.
... new engines implementing the web audio spec (such as gecko) will only implement the official, final version of the specification, which means that code using webkitaudiocontext or old naming conventions in the web audio specification may not immediately work out of the box in a compliant web audio implementation.
...r.responsetype = "arraybuffer"; xhr.send(); xhr.onload = function() { context.decodeaudiodata(xhr.response, function onsuccess(decodedbuffer) { // decoding was successful, do something useful with the audio buffer }, function onfailure() { alert("decoding the audio buffer failed"); }); }; note that the decodeaudiodata() method is asynchronous, which means that it will return immediately, and then when the decoding finishes, one of the success or failure callback functions will get called depending on whether the audio decoding was successful.
... those values have since been changed to use the web idl based enumerated values, which should be familiar because they are similar to things like the the htmlinputelement property type.
Background audio processing using AudioWorklet - Web APIs
specifying a value of true as the result from your process() function in essence tells the web audio api that your processor needs to keep being called even if the api doesn't think there's anything left for you to do.
... returning false from the process() method tells the api that it should follow its normal logic and shut down your processor node if it deems it appropriate to do so.
... note: at this time, unfortunately, chrome does not implement this algorithm in a manner that matches the current standard.
... here, for example, we set the value to newvalue, effective immediately.
Using the Web Storage API - Web APIs
a different storage object is used for the sessionstorage and localstorage for each origin — they function and are controlled separately.
...both of these can be manipulated in the same way, but separately.
...for example: function setstyles() { var currentcolor = localstorage.getitem('bgcolor'); var currentfont = localstorage.getitem('font'); var currentimage = localstorage.getitem('image'); document.getelementbyid('bgcolor').value = currentcolor; document.getelementbyid('font').value = currentfont; document.getelementbyid('image').value = currentimage; htmlelem.style.backgroundcolor = '#' + currentcolor; pelem.style.fontfamily = currentfont; imgelem.setattribute('src', currentimage); } here, the first three lines grab the values from local storage.
... function populatestorage() { localstorage.setitem('bgcolor', document.getelementbyid('bgcolor').value); localstorage.setitem('font', document.getelementbyid('font').value); localstorage.setitem('image', document.getelementbyid('image').value); setstyles(); } the populatestorage() function sets three items in local storage — the background color, font, and image path.
Window.open() - Web APIs
WebAPIWindowopen
note that remote urls won't load immediately.
...moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best.
... how can i tell when my window was blocked by a popup blocker?
... references "if your link spawns a new window, or causes another windows to 'pop up' on your display, or move the focus of the system to a new frame or window, then the nice thing to do is to tell the user that something like that will happen." world wide web consortium accessibility initiative regarding popups "use link titles to provide users with a preview of where each link will take them, before they have clicked on it." ten good deeds in web design, jakob nielsen, october 1999 using link titles to help users predict where they are going, jakob nielsen, january 1998 exam...
Window.pageYOffset - Web APIs
mauris efficitur tellus massa, id ullamcorper ipsum fermentum eu.
...integer euismod lectus a ipsum pellentesque lacinia.</p> `; document.getelementbyid("frame").contentdocument .body.innerhtml = contenthtml; in this example, an <iframe> is created and filled with content, then a specific element within the document is scrolled into view in the frame.
... <iframe id="frame"> </iframe> <div id="info"> </div> javascript var frame = document.getelementbyid("frame"); var framedoc = frame.contentdocument; var info = document.getelementbyid("info"); var target = framedoc.getelementbyid("overview"); framedoc.scrollingelement.scrolltop = target.offsettop; info.innertext = "y offset after scrolling: " + frame.contentwindow.pageyoffset + " pixels"; the javascript code begins by getting into frame and info the <iframe> element ...
...it then gets a reference to the element we want to scroll into view calling getelementbyid() on the frame's htmliframeelement.contentdocument.
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
if this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle.
...function() { vcallback.apply(null, aargs); } : vcallback, ndelay); }; }, 0, 'test'); }()) ie-only fix if you want a completely unobtrusive fix for every other mobile or desktop browser, including ie 9 and below, you can either use javascript conditional comments: /*@cc_on // conditional ie < 9 only fix @if (@_jscript_version <= 9) (function(f){ window.settimeout = f(window.settimeout); window.setinterval = f(window.setinterval); })(function(f){return function(c,t){var a=[].slice.call(arguments,2);retu...
...for example: function foo() { console.log('foo has been called'); } settimeout(foo, 0); console.log('after settimeout'); will write to the console: after settimeout foo has been called this is because even though settimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately.
...this causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.
Using the alert role - Accessibility
assistive technology products should listen for such an event and notify the user accordingly: screen readers may interrupt current output (whether it's speech or braille) and immediately announce or display the alert message.
...if the element was already in the original source code when the page loaded, the screen reader will announce the error immediately after announcing the page title.
...the pseudo code snippet below illustrates this approach: <p id="forminstruction">you must select at least 3 options</p> // when the user tries to submit the form with less than 3 checkboxes selected: document.getelementbyid("forminstruction").setattribute("role", "alert"); example 4: making an element with an alert role visible if an element already has role="alert" and is initially hidden using css, making it visible will cause the alert to fire as if it was just added to the page.
... .hidden { display:none; } <p id="expirationwarning" role="alert" class="hidden">your log in session will expire in 2 minutes</p> // removing the 'hidden' class makes the element visible, which will make the screen reader announce the alert: document.getelementbyid("expirationwarning").classname = ""; working examples: alert role example using an aria alert box alert example using a modal aria dialog box notes using the alert role on an element implies that element has aria-live="assertive".
ARIA: alert role - Accessibility
the alert role can be used to tell the user an element has been dynamically updated.
... description one of the five live region roles, the alert role is used to provide the user with important, and usually time-sensitive, information, and often to tell the user an element has been dynamically updated.
...it is perfect for situations such as when a user fills out a form and javascript is used to add an error message - the alert would immediately read out the message.
... <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.queryselector('.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.
ARIA: application role - Accessibility
any sort of special interpretation of html structures and widgets should be suspended, and control should be completely handed over to the browser and web application to handle mouse, keyboard, or touch interaction.
... in this mode, the web author is completely responsible for handling any and all keyboard input, focus management, and other interactions and cannot assume assistive technologies would do any processing on their end.
... keyboard interactions keyboard interaction is completely under the web author's control and can be anything associated with the particular widget being implemented.
... the application role does not have a related html widget and thus is completely free form.
WAI-ARIA Roles - Accessibility
for a full list of roles, see using aria: roles, states, and properties aria: alert rolethe alert role can be used to tell the user an element has been dynamically updated.
...dialogs can be either non-modal (it's still possible to interact with content outside of the dialog) or modal (only the content in the dialog can be interacted with).aria: document rolegenerally used in complex composite widgets or applications, the document role can inform assistive technologies to switch context to a reading mode: the document role tells assistive technologies with reading or browse modes to use the document mode to read the content contained within this element.aria: feed rolea feed is a dynamic scrollable list of articles in which articles are added to or removed from either end of the list as the user scrolls.
... a feed enables screen readers to use the browse mode reading cursor to both read and scroll through a stream of rich content that may continue scrolling infinitely by loading more content as the user reads.aria: figure rolethe aria figure role can be used to identify a figure inside page content where appropriate semantics do not already exist.
... alertdialog banner combobox command columnheader (estelle) complementary composite definition directory feed gridcell (eric e) group input landmark link - old page listbox log - old page marquee math menu menubar menuitem menuitemcheckbox menuitemradio none note option presentation progressbar - old page radio - old page radiogroup range region roletype rowheader(estelle) scrollbar searchbox section sectionhead sele...
Web applications and ARIA FAQ - Accessibility
unfortunately, there isn't a more semantic tag available to developers in html 4, so we need to include aria roles and properties.
...var progressbar = document.getelementbyid("percent-loaded"); // set its aria roles and states, so that assistive technologies know what kind of widget it is.
...and here is the javascript code that will ensure the progress bar still works in older browsers: var progressbar = document.getelementbyid("progress-bar"); // check to see if the browser supports the html5 <progress> tag.
... document.getelementbyid("update-button").addeventlistener("click", function (e) { updateprogress(75); e.preventdefault(); }, false); } initdemo(); how do assistive technologies work?
Accessibility documentation index - Accessibility
20 using the aria-invalid attribute aria, accessibility, attribute, codingscripting, html, javascript, needscontent, role(2), agent, alert, user, useragent the aria-invalid attribute is used to indicate that the value entered into an input field does not conform to the format expected by the application.this may include formats such as email addresses or telephone numbers.
... 51 aria: alert role aria, aria role, aria alert, aria widget, reference the alert role can be used to tell the user an element has been dynamically updated.
... 60 aria: document role aria, aria role, document, reference generally used in complex composite widgets or applications, the document role can inform assistive technologies to switch context to a reading mode: the document role tells assistive technologies with reading or browse modes to use the document mode to read the content contained within this element.
...a feed enables screen readers to use the browse mode reading cursor to both read and scroll through a stream of rich content that may continue scrolling infinitely by loading more content as the user reads.
Using CSS transitions - CSS: Cascading Style Sheets
instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time.
... you can control the individual components of the transition with the following sub-properties: (note that these transitions loop infinitely only for the purpose of our examples; css transitions only visualize a property change from start to finish.
... javascript examples care should be taken when using a transition immediately after: adding the element to the dom using .appendchild() removing an element's display: none; property.
... <p>click anywhere to move the ball</p> <div id="foo"></div> using javascript you can make the effect of moving the ball to a certain position happen: var f = document.getelementbyid('foo'); document.addeventlistener('click', function(ev){ f.style.transform = 'translatey('+(ev.clienty-25)+'px)'; f.style.transform += 'translatex('+(ev.clientx-25)+'px)'; },false); with css you can make it smooth without any extra effort.
<filter-function> - CSS: Cascading Style Sheets
ight: 300px; background: 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.queryselector('select'); const divelem = document.queryselector('div'); const slider = document.queryselector('input'); const output = document.queryselector('output'); const curvalue = document.queryselector('p code'); selectelem.addeventlistener('change', () => { setslider(selectelem.value); setdiv(selectelem.value); }); slider.addeventlistener('input', () => { setdiv(selec...
...telem.value); }); function setslider(filter) { if(filter === 'blur') { slider.value = 0; slider.min = 0; slider.max = 30; slider.step = 1; slider.setattribute('data-unit', 'px'); } else if(filter === 'brightness' || filter === 'contrast' || filter === 'saturate') { slider.value = 1; slider.min = 0; slider.max = 4; slider.step = 0.05; slider.setattribute('data-unit', ''); } else if(filter === 'drop-shadow') { slider.value = 0; slider.min = -20; slider.max = 40; slider.step = 1; slider.setattribute('data-unit', 'px'); } else if(filter === 'opacity') { slider.value = 1; slider.min = 0; slider.max = 1; slider.step = 0.01; slider.setattribute('data-unit', ''); } else if(filter === 'grayscale' || filter === '...
...{ slider.value = 0; slider.min = 0; slider.max = 1; slider.step = 0.01; slider.setattribute('data-unit', ''); } else if(filter === 'hue-rotate') { slider.value = 0; slider.min = 0; slider.max = 360; slider.step = 1; slider.setattribute('data-unit', 'deg'); } } function setdiv(filter) { if(filter === 'drop-shadow') { divelem.style.filter = `${selectelem.value}(${math.round(slider.value)}${slider.getattribute('data-unit')} ${math.round(slider.value)}${slider.getattribute('data-unit')} ${math.round(math.abs(slider.value/2))}${slider.getattribute('data-unit')})`; } else { divelem.style.filter = `${selectelem.value}(${slider.value}${slider.getattribute('data-unit')}`; } updateoutput(); updatecurvalue(); } function updateoutput() { ...
...output.textcontent = slider.value; } function updatecurvalue() { curvalue.textcontent = `filter: ${divelem.style.filter}`; } setslider(selectelem.value); setdiv(selectelem.value); result specifications specification status filter effects module level 1the definition of 'filter-function' in that specification.
justify-self - CSS: Cascading Style Sheets
for absolutely-positioned elements, it aligns an item inside its containing block on the inline axis, accounting for the offset values of top, left, bottom, and right.
... values auto the value used is the value of the justify-items property of the parents box, unless the box has no parent, or is absolutely positioned, in these cases, auto represents normal.
... in absolutely-positioned layouts, the keyword behaves like start on replaced absolutely-positioned boxes, and as stretch on all other absolutely-positioned boxes.
... formal definition initial valueautoapplies toblock-level boxes, absolutely-positioned boxes, and grid itemsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | normal | stretch | <baseline-position> | <overflow-position>?
Making content editable - Developer guides
these are object resizing on <img>, <table>, and absolutely-positioned elements; inline table editing to add or remove rows and columns; and the grabber that allows moving of absolutely-positioned elements.
... fortunately, in modern browsers things are somewhat more consistent.
...oard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.clipboard.cutcopy", "allaccess"); user_pref("capability.policy.allowclipboard.clipboard.paste", "allaccess"); example: a simple but complete rich text editor <!doctype html> <html> <head> <title>rich text editor</title> <script type="text/javascript"> var odoc, sdeftxt; function initdoc() { odoc = document.getelementbyid("textbox"); sdeftxt = odoc.innerhtml; if (document.compform.switchmode.checked) { setdocmode(true); } } function formatdoc(scmd, svalue) { if (validatemode()) { document.execcommand(scmd, false, svalue); odoc.focus(); } } function validatemode() { if (!document.compform.switchmode.checked) { return true ; } alert("uncheck \"show html\"."); odoc.focus(); return false; } f...
...ick="formatdoc('indent');" src="data:image/gif;base64,r0lgodlhfgawaomiaaaaadljwl9vj1ie35gjuaezxtdv3nha7p///////////////////////////////yh5baeaaagalaaaaaawabyaaaq7emljq704650b/x8gemmpgugwhjnzxodkso5oquogo5khbwwesymqscrdhu9voyk5tm9zspfsr9gsjwiaow==" /> <img class="intlink" title="hyperlink" onclick="var slnk=prompt('write the url here','http:\/\/');if(slnk&&slnk!=''&&slnk!='http://'){formatdoc('createlink',slnk)}" src="data:image/gif;base64,r0lgodlhfgawaomkab1chdrly19vj3morpgjuaezxrcztb/i19ha7pv8/f///////////////////////yh5baekaa8alaaaaaawabyaaary8mljq7046827/2byiqvhhg9pegvgiklydeuby/rle4fqf4dcj2aqxaijqdcwqcaebwiioemqbgsafhdagghgi9xghahmnoszgjkjei33uesv2+/4vd4taqa7" /> <img class="intlink" title="cut" onclick="formatdoc('cut');" src="data:image/gif;base64,r0lgodlhfgawaiqsab1chbfnsrjtysjywjljwkx...
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
are not valid javascript escapes; the character code strategy is more general-purpose.) inline svg and mathml support as a completely new parsing feature, html5 introduced support for inline svg and mathml in text/html.
... the syntax <foo/> opens and immediately closes the foo element if it is a mathml or svg element (i.e.
... attributes starting with xmlns have absolutely no effect on what namespace elements or attributes end up in, so you don’t need to use attributes starting with xmlns.
... to deal with legacy pages where authors have pasted partial svg fragments into html (who knows why) or used a <math> tag for non-mathml purposes, attempts to nest various common html elements as children of svg elements (without foreignobject) will immediately break out of svg or mathml context.
Parsing and serializing XML - Developer guides
parsing strings into dom trees this example converts an xml fragment in a string into a dom tree using a domparser: var smystring = '<a id="a"><b id="b">hey!</b></a>'; var oparser = new domparser(); var odom = oparser.parsefromstring(smystring, "application/xml"); // print the name of the root element or error message console.log(odom.documentelement.nodename == "parsererror" ?
... "error while parsing" : odom.documentelement.nodename); parsing url-addressable resources into dom trees using xmlhttprequest here is sample code that reads and parses a url-addressable xml file into a dom tree: var xhr = new xmlhttprequest(); xhr.onload = function() { dump(xhr.responsexml.documentelement.nodename); } xhr.onerror = function() { dump("error while getting xml."); } xhr.open("get", "example.xml"); xhr.responsetype = "document"; xhr.send(); the value returned in the xhr object's responsexml field is a document constructed by parsing the xml.
... var dochtml = document.documentelement.innerhtml; as a result, dochtml is a domstring containing the html of the contents of the document; that is, the <body> element's contents.
... you can get html corresponding to the <body> and its descendants with this code: var dochtml = document.documentelement.outerhtml; ...
<input type="datetime-local"> - HTML: Hypertext Markup Language
you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var datecontrol = document.queryselector('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.
... </select> in either case, the date/time and time zone values would be submitted to the server as separate data points, and then you'd need to store them appropriately in the database on the server-side.
...if you are stuck with other hardware, you can try to emulate 64-bit hardware inside a 32-bit virtual machine, but most vms don't support this kind of virtualization, stability may suffer, and performance will definately suffer greatly.
...ter { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="datetime-local">, we create a new <input> element, try setting its type to datetime-local, then immediately check what its type is set to.
<input type="email"> - HTML: Hypertext Markup Language
WebHTMLElementinputemail
if the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
...it only specifies approximately how many can be seen at a time.
... it's far too easy for someone to make adjustments to the html that allow them to bypass the validation, or to remove it completely.
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlscriptelement attributes this element includes the global attributes.
... nonce a cryptographic nonce (number used once) to whitelist scripts in a script-src content-security-policy.
... notes scripts without async , defer or type="module" attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page.
... <!-- generated by the server --> <script id="data" type="application/json">{"userid":1234,"username":"john doe","membersince":"2000-01-01t00:00:00.000z"}</script> <!-- static --> <script> const userinfo = json.parse(document.getelementbyid("data").text); console.log("user information: %o", userinfo); </script> specifications specification status comments html living standardthe definition of '<script>' in that specification.
HTTP Public Key Pinning (HPKP) - HTTP
http public key pinning (hpkp) was a security feature that used to tell a web client to associate a specific cryptographic public key with a certain web server to decrease the risk of mitm attacks with forged certificates.
...hpkp can circumvent this threat for the https protocol by telling the client which public key belongs to a certain web server.
...the first time a web server tells a client via a special http header which public keys belong to it, the client stores this information for a given period of time.
...max-age=5184000 tells the client to store this information for two months, which is a reasonable time limit according to the ietf rfc.
Using Promises - JavaScript
to avoid having them cluttering up your output—by adding a handler for the unhandledrejection event, like this: window.addeventlistener("unhandledrejection", event => { /* you might start here by adding code to examine the promise specified by event.promise and the reason in event.reason */ event.preventdefault(); }, false); by calling the event's preventdefault() method, you tell the javascript runtime not to do its default action when rejected promises go unhandled.
...unfortunately, some apis still expect success and/or failure callbacks to be passed in the old way.
...result3) */ timing to avoid surprises, functions passed to then() will never be called synchronously, even with an already-resolved promise: promise.resolve().then(() => console.log(2)); console.log(1); // 1, 2 instead of running immediately, the passed-in function is put on a microtask queue, which means it runs later when the queue is emptied at the end of the current run of the javascript event loop, i.e.
... a good rule-of-thumb is to always either return or terminate promise chains, and as soon as you get a new promise, return it immediately, to flatten things: dosomething() .then(function(result) { return dosomethingelse(result); }) .then(newresult => dothirdthing(newresult)) .then(() => dofourththing()) .catch(error => console.error(error)); note that () => x is short for () => { return x; }.
DataView() constructor - JavaScript
syntax new dataview(buffer [, byteoffset [, bytelength]]) parameters buffer an existing arraybuffer or sharedarraybuffer to use as the storage backing the new dataview object.
... bytelength optional the number of elements in the byte array.
... exceptions rangeerror thrown if the byteoffset or bytelength parameter values result in the view extending past the end of the buffer.
... for example, if the buffer is 16 bytes long, the byteoffset is 8, and the bytelength is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer.
Promise - JavaScript
this lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
...sometimes there is no choice, because an error must be handled immediately.
... "use strict"; var promisecount = 0; function testpromise() { let thispromisecount = ++promisecount; let log = document.getelementbyid('log'); // begin log.insertadjacenthtml('beforeend', thispromisecount + ') started (sync code started)'); // we make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s) let p1 = new promise((resolve, reject) => { // the executor function is called with the ability to resolve or reject the promise log.insertadjacenthtml('beforeend'...
...ulfillment value log.insertadjacenthtml('beforeend', val + ') promise fulfilled (async code terminated)'); }).catch((reason) => { // log the rejection reason console.log(`handle rejected promise (${reason}) here.`); }); // end log.insertadjacenthtml('beforeend', thispromisecount + ') promise made (sync code terminated)'); } if ("promise" in window) { let btn = document.getelementbyid("btn"); btn.addeventlistener("click",testpromise); } else { log = document.getelementbyid('log'); log.innerhtml = "live example not available as your browser doesn't support the <code>promise<code> interface."; } this example is started by clicking the button.
Using templates and slots - Web Components
let's look at a trivial quick example: <template id="my-paragraph"> <p>my paragraph</p> </template> this won't appear in your page until you grab a reference to it with javascript and then append it to the dom, using something like the following: let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; document.body.appendchild(templatecontent); although trivial, you can already start to see how this could be useful.
...we'll call it <my-paragraph>: customelements.define('my-paragraph', class extends htmlelement { constructor() { super(); let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(templatecontent.clonenode(true)); } } ); the key point to note here is that we append a clone of the template content to the shadow root, created using the node.clonenode() method.
... customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(true)); } } ); using the <element-details> custom element with named slots now let’s take that <element-details> element and actually use it in our document: <element-details> <span slot="element-name">slot</span> <span slot="des...
...hanism for holding client- side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using javascript.</span> </element-details> <script> customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(true)); } }) </script> </body> </html> ...
Introduction to using XPath in JavaScript - XPath
contextnode.documentelement : contextnode.ownerdocument.documentelement ); or alternatively by using the <code>creatensresolver</code> method of a <code>xpathevaluator</code> object.
...contextnode.documentelement : contextnode.ownerdocument.documentelement ); </pre> and then pass document.evaluate, the nsresolver variable as the namespaceresolver parameter.
...xmldoc.documentelement : xmldoc.ownerdocument.documentelement); var personiterator = xmldoc.evaluate('//person', xmldoc, nsresolver, xpathresult.any_type, null ); note when the xpathresult object is not defined, the constants can be retrieved in privileged code using components.interfaces.nsidomxpathresult.any_type (ci.nsidomxpathresult).
... in order to accurately grab elements with the xlink @href attribute (without also being confined to predefined prefixes in a namespace resolver), one could obtain them as follows: var xpathels = 'someelements[@*[local-name() = "href" and namespace-uri() = "http://www.w3.org/1999/xlink"]]'; // grabs elements with any single attribute that has both the local name 'href' and the xlink namespace var thislevel = xml.evalu...
Compiling from Rust to WebAssembly - WebAssembly
in this case, that statement is an extern, which tells rust that we want to call some externally defined functions.
...the first part — [lib] — tells rust to build a cdylib version of our package; we won't get into what that means in this tutorial.
...here's where we tell cargo what version of wasm-bindgen we want to depend on; in this case, that's any 0.2.z version (but not 0.3.0 or above).
...as far as the javascript code can tell, this is just a normal module.
Using the WebAssembly JavaScript API - WebAssembly
these methods are easier than their non-streaming counterparts, because they can turn the byte code directly into module/instance instances, cutting out the need to separately put the response into an arraybuffer.
... note: since an arraybuffer’s bytelength is immutable, after a successful memory.prototype.grow() operation the buffer getter will return a new arraybuffer object (with the new bytelength) and any previous arraybuffer objects become “detached”, or disconnected from the underlying memory they previously pointed to.
... the mutations are immediately accessible via table.prototype.get() in javascript, and to wasm modules.
... const output = document.getelementbyid('output'); function asserteq(msg, got, expected) { output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success!
Communicating With Other Scripts - Archive of obsolete content
ncludes a button and a page script: <html> <head> <meta charset="utf-8"> </head> <body> <input id="message" type="button" value="send a message"/> <script type="text/javascript" src="page-script.js"></script> </body> </html> the content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getelementbyid("message"); messenger.addeventlistener("click", sendcustomevent, false); function sendcustomevent() { var greeting = {"greeting" : "hello world"}; var event = document.createevent('customevent'); event.initcustomevent("addon-message", true, true, greeting); document.documentelement.dispatchevent(event); } finally, the page script "page-script.js" listens for the message and log...
...from firefox 30 this sharing requires an extra step: the content script needs to explicitly clone the message payload into the page script's scope using the global cloneinto() function: var messenger = document.getelementbyid("message"); messenger.addeventlistener("click", sendcustomevent, false); function sendcustomevent() { var greeting = {"greeting" : "hello world"}; var cloned = cloneinto(greeting, document.defaultview); var event = document.createevent('customevent'); event.initcustomevent("addon-message", true, true, cloned); document.documentelement.dispatchevent(event); } messaging from pa...
....js") }); the web page "talk.html" creates and dispatches a custom dom event, using initcustomevent()'s detail parameter to supply the payload: <!doctype html> <html> <head></head> <body> <script> function sendmessage() { var event = document.createevent('customevent'); event.initcustomevent("addon-message", true, true, { hello: 'world' }); document.documentelement.dispatchevent(event); } </script> <button onclick="sendmessage()">send message</button> </body> </html> finally, the content script "listen.js" listens for the new event and retrieves the payload from its detail attribute: window.addeventlistener("addon-message", function(event) { console.log(json.stringify(event.detail)); }, false); ...
Communicating using "port" - Archive of obsolete content
accessing port accessing port in the content script note that the global self object is completely different from the self module, which provides an api for an add-on to access its data files and id.
... function getfirstparagraph() { var paras = document.getelementsbytagname('p'); console.log(paras[0].textcontent); self.port.removelistener("get-first-para", getfirstparagraph); } self.port.on("get-first-para", getfirstparagraph); the result is that the paragraph is only logged the first time the button is clicked.
... this example rewrites the "listener.js" content script in the port.removelistener() example so that it uses once(): function getfirstparagraph() { var paras = document.getelementsbytagname('p'); console.log(paras[0].textcontent); } self.port.once("get-first-para", getfirstparagraph); json-serializable values the payload for an message can be any json-serializable value.
Content Scripts - Archive of obsolete content
it takes one of: "start": load the scripts immediately after the document element for the page is inserted into the dom.
...so to emit a message from a content script: self.port.emit("mycontentscriptmessage", mycontentscriptmessagepayload); to receive a message from the add-on code: self.port.on("myaddonmessage", function(myaddonmessagepayload) { // handle the message }); note that the global self object is completely different from the self module, which provides an api for an add-on to access its data files and id.
... = require("sdk/page-worker").page({ contentscriptfile: self.data.url("content-script.js"), contenturl: "http://en.wikipedia.org/wiki/internet" }); pageworker.port.on("first-para", function(firstpara) { console.log(firstpara); }); pageworker.port.emit("get-first-para"); // content-script.js self.port.on("get-first-para", getfirstpara); function getfirstpara() { var paras = document.getelementsbytagname("p"); if (paras.length > 0) { var firstpara = paras[0].textcontent; self.port.emit("first-para", firstpara); } } from page-mod a single page-mod object might attach its scripts to multiple pages, each with its own context in which the content scripts are executing, so it needs a separate channel (worker) for each page.
Classes and Inheritance - Archive of obsolete content
to illustrate this, let's define a simple constructor for a class shape: function shape(x, y) { this.x = x; this.y = y; } we can now use this constructor to create instances of shape: let shape = new shape(2, 3); shape instanceof shape; // => true shape.x; // => 2 shape.y; // => 3 the keyword new tells javascript that we are performing a constructor call.
...the method draw is defined on instances of shape, so we definitely want it to be defined on instances of circle.
...consider the following: let circle = circle(2, 3, 5); circle instanceof shape; // => false since instances of circle inherit from shape, we definitely want the result of this expression to be true.
Modules - Archive of obsolete content
unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names.
...unfortunately, javascript does not provide any means to load scripts from other locations: we have to rely on the host application to provide us with this functionality.
...a whitelist of modules is generated statically when the add-on is linked.
dev/panel - Archive of obsolete content
panel.html", onready: function() { this.postmessage("message from the add-on"); } }); // export the constructor exports.mypanel = mypanel; // create a new tool, initialized // with the new constructor const mytool = new tool({ panels: { mypanel: mypanel } }); in the panel document script: // my-panel.js window.addeventlistener("message", function(event) { var content = document.getelementbyid("content"); content.textcontent = event.data; }); note that at the moment you have to pass an array of ports into postmessage, even if you don't need to use them: // main.js // require the sdk modules const { panel } = require("dev/panel"); const { tool } = require("dev/toolbox"); const { class } = require("sdk/core/heritage"); const mypanel = class({ extends: panel, label: "m...
..., dispose: function() { this.debuggee = null; }, onready: function() { this.debuggee.start(); this.postmessage("port", [this.debuggee]); } }); // export the constructor exports.mypanel = mypanel; // create a new tool, initialized // with the new constructor const mytool = new tool({ panels: { mypanel: mypanel } }); in my-panel.js: // my-panel.js var content = document.getelementbyid("content"); window.addeventlistener("message", function(event) { var debuggee = event.ports[0]; console.log(debuggee); debuggee.onmessage = function(event) { content.textcontent = json.stringify(event.data); } debuggee.postmessage({ "to":"root", "type":"listtabs" }); }); if you do this, don't forget to call start() on the port before passing it over to the pa...
...ke this: <html> <head> <meta charset="utf-8"> <link href="./my-panel.css"rel="stylesheet"></link> <script src="resource://sdk/dev/volcan.js"></script> </head> <body> <div id = "content"></div> </body> <script src="./my-panel.js"></script> </html> here's a script that uses volcan.js to get the selected tab and display its url: // my-panel.js var content = document.getelementbyid("content"); window.addeventlistener("message", function(event) { var debuggee = event.ports[0]; volcan.connect(debuggee).
Creating Reusable Modules - Archive of obsolete content
.createinstance(ci.nsilocalfile); f.initwithpath(path); var istream = cc["@mozilla.org/network/file-input-stream;1"] .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstance(ci.nsicryptohash); // we want to use the md5 algorithm ch.init(ch.md5); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // convert the binary hash data to a hex string.
... .createinstance(ci.nsilocalfile); f.initwithpath(path); var istream = cc["@mozilla.org/network/file-input-stream;1"] .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstance(ci.nsicryptohash); // we want to use the md5 algorithm ch.init(ch.md5); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // convert the binary hash data to a hex string.
... .createinstance(ci.nsilocalfile); f.initwithpath(path); var istream = cc["@mozilla.org/network/file-input-stream;1"] .createinstance(ci.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = cc["@mozilla.org/security/hash;1"] .createinstance(ci.nsicryptohash); // we want to use the md5 algorithm ch.init(ch.md5); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // convert the binary hash data to a hex string.
Dialogs and Prompts - Archive of obsolete content
programmatic button access if you want to access the accept ("ok") and cancel buttons from script, use this: // disable the ok and cancel btns document.documentelement.getbutton("accept").disabled = true; document.documentelement.getbutton("cancel").disabled = true; links dialog.xml — xbl bindings for <dialog> and <dialogheader> elements.
...><label value="name:"/><textbox id="name"/></row> <row align="center"><label value="description:"/><textbox id="description"/></row> <row align="center"><spacer/><checkbox id="enabled" label="check to enable"/></row> </rows> </grid> </dialog> mydialog.js: // called once when the dialog displays function onload() { // use the arguments passed to us by the caller document.getelementbyid("name").value = window.arguments[0].inn.name; document.getelementbyid("description").value = window.arguments[0].inn.description; document.getelementbyid("enabled").checked = window.arguments[0].inn.enabled; } // called once if and only if the user clicks ok function onok() { // return the changed arguments.
... // notice if user clicks cancel, window.arguments[0].out remains null // because this function is never called window.arguments[0].out = {name:document.getelementbyid("name").value, description:document.getelementbyid("description").value, enabled:document.getelementbyid("enabled").checked}; return true; } see also passing parameter to a dialog and getting return values from it.
Installing Extensions and Themes From Web Pages - Archive of obsolete content
furthermore, calling updateenabled may lead to problems if your distribution site is not in the user's whitelist, because firefox only displays the "installation blocked" message when install or installchrome are called, or when a xpi file is loaded.
...and your site is not in the whitelist, when the user invokes that code, updateenabled will return false because your site isn't whitelisted, and since it was updateenabled that discovered this, not a call to install, there will be no notification to the user.
... thus you should only use updateenabled to display content in the page to alert the user that software installation is disabled, or your site is not in the whitelist—do not place it in the install code path.
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
ad="initclock();"> <script type="application/javascript" src="chrome://helloworld/content/clock.js"/> <hbox align="center"> <label value="current time:" /> <textbox id="currenttime" /> </hbox> </dialog> listing 6: content for clock.js function initclock() { showcurrenttime(); window.setinterval(showcurrenttime, 1000); } function showcurrenttime() { var textbox = document.getelementbyid("currenttime"); textbox.value = new date().tolocaletimestring(); textbox.select(); } operations check perform an operations check to make sure that your changes to the source file are correct.
...download the files icon.png and icon-small.png from the resources website and place them appropriately.
...if true, causes a confirmation dialog to appear; if false, deletes immediately.
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
in this case the user is told that firefox needs to restart in order for the extension to be completely removed.
...the add-on will not be completely removed until the browser is restarted.
...you shouldn't perform very time-consuming operations here, at least not without telling users what is going on.
Appendix F: Monitoring DOM changes - Archive of obsolete content
unfortunately, adding listeners for any of these events to a document has a highly deleterious effect on performance, an effect which is not mitigated in the slightest by later removing those listeners.
... non-mutation triggers it is usually possible to tell when a mutation has occurred or is about to occur without resorting to mutation events or observers.
... ' + watchnodes.namespace + prop) .join('\n'); doc.addeventlistener('animationstart', listener, false); function listener(event) { if (event.animationname == event) callback.call(this, event); } style.textcontent = ' ' + preamble + selector + '{' + properties + '}'; (doc.head || doc.documentelement).appendchild(style); // this will only work in chrome privileged code.
Getting Started with Firefox Extensions - Archive of obsolete content
they can add anything from a toolbar button to a completely new feature.
... firefox provides a very rich and flexible architecture that allows extension developers to add advanced features, customize the user's experience, and completely replace and remove parts of the browser.
...you should see another pop-up telling you that you are installing an unverified add-on.
The Box Model - Archive of obsolete content
in order to use this page, you'll need to install the remote xul manager extension and add developer.mozilla.org to the whitelist.
...using the former allows the ui to scale proportionately depending on font size settings, which are often changed by users with accessibility limitations.
...a spacer element is completely invisible and doesn't do more than take space.
Creating a status bar extension - Archive of obsolete content
many of the concepts introduced here apply to any xul-based application; however, to keep from getting completely overwhelmed, we're going to focus specifically on firefox.
...download the sample the install manifest the install manifest, install.rdf, is a text file containing information that tells the host application important information about the extension.
...the chrome manifest the chrome manifest is a file that tells the target application where to look for the chrome package for your extension.
Using XML Data Islands in Mozilla - Archive of obsolete content
like this: <script id="purchase-order" type="application/xml"> <purchaseorder xmlns="http://example.mozilla.org/purchaseorderml"> <lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> the xml source text can then be retrieved like this: var ordersource = document.getelementbyid("purchase-order").textcontent; the xml source text can be parsed into a dom tree using the domparser api: var parser = new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); the html5 data block-based way shown here works in firefox, opera, webkit-based browsers such as chrome and safari, and ie9 while ie's xml data islands work only in ie.
...itle>xml data block demo</title> <script id="purchase-order" type="application/xml"> <purchaseorder xmlns="http://example.mozilla.org/purchaseorderml"> <lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> <script> function rundemo() { var ordersource = document.getelementbyid("purchase-order").textcontent; var parser = new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); var lineitems = doc.getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "lineitem"); var firstprice = lineitems[0].getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "price")[0].textcontent; document.body.textcontent =...
...for this demo, you must create an external document called purchase_order.xml: <!doctype html> <html> <head> <title>xml data block demo</title> <script> function rundemo() { var doc = document.getelementbyid("purchase-order").contentdocument; var lineitems = doc.getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "lineitem"); var firstprice = lineitems[0].getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "price")[0].textcontent; document.getelementbyid("output-box").textcontent = "the purchase order contains " + lineitems.length + " line items.
Developing New Mozilla Features - Archive of obsolete content
once you’re familiar with an area, do the completely unexpected and write a piece of documentation.
... designate someone on your team to be involved with the mozilla.org cvs repository on a regular basis the ease of integrating your feature will increase if someone on your team is intimately involved with the source tree.
...if you absolutely don't have the resources to do this, then plan for extra integration time.
Editor Embedding Guide - Archive of obsolete content
the first parameter is the nsidomwindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading.
... getcommandstate "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "state_enabled" (boolean) docommand no parameters example normal underline cmd_tt toggles teletype style (monospace font) on selection.
... getcommandstate "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "state_enabled" (boolean) docommand no parameters example normal teletype cmd_strikethrough toggles strikethrough style on selection.
Syncing custom preferences - Archive of obsolete content
when preferences sync is enabled, firefox sync will synchronize preferences between the same application based on a whitelist.
...to sync preferences between firefoxes, fennecs, thunderbirds, etc., ensure the prefs are whitelisted.
... the whitelist is determined as follows: for each services.sync.prefs.sync.<pref> preference that is set to true, firefox sync will sync the <pref> preference.
Introducing the Audio API extension - Archive of obsolete content
mple</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> the mozaudioavailable event as the audio is played, sample data is made available to the audio layer and the audio buffer (size defined in mozframebufferlength) gets filled with those samples.
... rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; } function audioavailable(event) { var framebuffer = event.framebuffer; var t = event.time; var text = "samples at: " + t + "\n"; text += framebuffer[0] + " " + framebuffer[1]; raw.innerhtml = text; } var raw = document.getelementbyid('raw'); var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> creating an audio stream it is also possible to create and setup an <audio> element for raw writing from script (i.e., without a src attribut...
... <audio id="a1" src="song.ogg" controls> </audio> <script> var a1 = document.getelementbyid('a1'), a2 = new audio(), buffers = []; function loadedmetadata() { // mute a1 audio.
PyDOM - Archive of obsolete content
for example, let's say you have xul similar to pyxultest: top-level script code says something like: button = document.getelementbyid("some-button") button.foo = 0 and the button itself might look like: <button id="some-button" label="click here" onclick="event.target.foo += 1; print 'foo is now', event.target.foo"/> note that (a) we have stuck an arbitrary attribute on a dom element and (b) in all cases (e.g., event handler and top-level script), the dom node needs to be explicitly specified - the globals a...
...the event handler could also have used getelementbyid - the point is that both the event handler and top-level script share the same namespace.
... using python ideally, you just tell mozilla you are using python, and magically you can use python instead of javascript.
Supporting private browsing mode - Archive of obsolete content
this interface is deprecated since firefox 20, and will probably be completely removed in firefox 21.see supporting per-window private browsing for details.
...let docroot = document.documentelement; if (docroot.hasattribute("privatebrowsingmode")) { // private browsing mode is enabled } if (docroot.getattribute("privatebrowsingmode") == "temporary") { // private browsing mode is temporary } if (docroot.getattribute("privatebrowsingmode") == "permanent") { // private browsing mode is permanent for this session } turning private browsing on and off extensions can turn private b...
... from that point until we restore the original value of the private browsing mode setting, things are done privately.
Tamarin build documentation - Archive of obsolete content
windows 32 and 64 bit mac osx 10.4, 10.5 on ppc mac osx 10.5, 10.6 on intel linux 32 and 64 bit solaris 10 on sparc android 2.2 on arm windows mobile 6.5 mips (linux) sh4 (linux) getting the tamarin source the tamarin source resides in mercurial at tamarin central.
... intel macs build correctly by setting archs=i386.
... this is a shared resource, each request takes approximately 2+ hours to run so please use wisely.
Tamarin Build System Documentation - Archive of obsolete content
the test phase takes approximately 1 hour 45 minutes.
... the buildbot scripts are located in the tamarin repository, get a current copy in your test repository cd into the build/buildbot/slaves directory: cd build/buildbot/slaves copy the your platform scripts directory into the scripts directory and cd into the new scripts directory: cp -r mac-intel-10_5/scripts .
...ory, test/run-smokes.txt, assume the start directory is test format is cd testdir; command to run test above the test should be a # comment describing why the test in the smokes, when test failed, possibly a bugzilla bug the tests can be run by following the above instructions for running buildbot scripts locally and executing the all/run-smoke-tests.sh as a rule any test failure should be immediately added to the top of the smoke test list so the list is prioritized how to exclude tests from acceptance or mark them as known failures?
Tamarin-central rev 703:2cee46be9ce0 - Archive of obsolete content
testing summary acceptance tests have passed on the following supported platforms: * windows, 32 & 64 bit * mac ox x ppc & intel, 32 bit * linux, 32 bit * windows mobile arm version asc-4200 of the actionscript compiler was used for all tests.
... osdefault-jitinterpretedaggressive jit mac (os/x 10.4 intel, 2ghz dual core)tc-703 vs tc-700: 0.0%tc-703 vs flash10: 1.1% slowertc-703 vs tc-700: 17.4% fastertc-703 vs flash10: 165.3% fastertc-703 vs tc-700: 0.1% fastertc-703 vs flash10: 0.8% slower windows (xp pro, 2.13ghz dual core)tc-703 vs tc-700: 0.6% fastertc-703 vs flash10: 0.8% fastertc-703 vs tc-700: 16.4% fastertc-703 vs flash10: 148.7% fastertc-703 vs tc-700: 0.1% slowertc-703 vs flash10: 5.2% faster linux (ubuntu linux...
... osdefault-jitinterpretedaggressive jit mac (os/x 10.4 intel, 2ghz dual core)tc-703 vs tc-700: 2.0% smallertc-703 vs tc-663: 7.8% smallertc-703 vs tc-700: 7.1% largertc-703 vs tc-663: 14.6% largertc-703 vs tc-700: 16.4% largertc-703 vs tc-663: 2.1% larger windows (xp pro, 2.13ghz dual core)tc-703 vs tc-700: 3.2% largertc-703 vs tc-663: 7.6% largertc-703 vs tc-700: 3.9% largertc-703 vs tc-663: 12.4% largertc-703 vs tc-700: 3.3% largertc-703 vs tc-6...
The new nsString class implementation (1999) - Archive of obsolete content
disclaimer: i absolutely hate string classes.
... nsautostring use these locally in cases where you don't want to incur heap allocation unless absolutely necessary.
...the i18n folks will tell you it's better to use a wide string and convert to 1-byte forms for this purpose even though there is a performance penalty for doing so.
Using XPInstall to Install Plugins - Archive of obsolete content
by refreshing your plugin, you're ensuring that the plugin is available for use immediately, without obliging the user to restart their browser.
...// by passing 'true' we are telling the install script to block // on the execution of the installable, and do it synchronously // must call performinstall to make it all happen...
...xpinstall can therefore be the "agent of delivery" to streamline the download of the exe software, but ultimately, the logic of installation and uninstallation will be handled by exe, which can then create files and registry entries and also clean up after itself upon removal.
collapse - Archive of obsolete content
before when the grippy is clicked, the element immediately before the splitter in the same parent is collapsed so that its width or height is 0.
... after when the grippy is clicked, the element immediately after the splitter in the same parent is collapsed so that its width or height is 0.
... both either the element immediately before the splitter, or the element immediately after the splitter can be collapsed, if the size of that element would fall below the minimum size due to the position of the splitter.
Building accessible custom components in XUL - Archive of obsolete content
<caption>it looks like a column header, but it's not</caption> so, before we do anything else, we need to tell assistive technologies that all of these unrelated elements are actually related.
...<code> var gfocuscell = null; function install_handlers() { var spreadsheet = window.document.getelementbyid('accjaxspreadsheet'); spreadsheet.addeventlistener('focus', spreadsheet_focus, true); spreadsheet.addeventlistener('click', spreadsheet_click, true); } function spreadsheet_focus(e) { if (e.target.tagname == 'grid') { if (!gfocuscell) { gfocuscell = e.target.getelementsbytagname('label')[0]; } gfocuscell.focus(); } else { gfocu...
...<code> function install_handlers() { var spreadsheet = window.document.getelementbyid('accjaxspreadsheet'); spreadsheet.addeventlistener('keypress', spreadsheet_keypress, true); spreadsheet.addeventlistener('focus', spreadsheet_focus, true); spreadsheet.addeventlistener('click', spreadsheet_click, true); } </code> with this new event handler and associated helper functions, we can navigate between cells and headers using the arrow keys.
Dynamically modifying XUL-based user interface - Archive of obsolete content
the most well known dom method is probably document.getelementbyid(), which returns an element, given its id.
...var element = document.getelementbyid("someelement"); while(element.haschildnodes()){ element.removechild(element.firstchild); } inserting menu items to a menu this example adds two new menu items to a <menupopup>: to the start and to the end of it.
... function createmenuitem(alabel) { const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var item = document.createelementns(xul_ns, "menuitem"); // create a new xul menuitem item.setattribute("label", alabel); return item; } var popup = document.getelementbyid("mypopup"); // a <menupopup> element var first = createmenuitem("first item"); var last = createmenuitem("last item"); popup.insertbefore(first, popup.firstchild); popup.appendchild(last); you can also use appendchild() and insertbefore() to move existing elements.
ContextMenus - Archive of obsolete content
function checkcontextmenu(event) { if (event.target.localname == "textbox") event.preventdefault(); } function init() { var container = document.getelementbyid("container"); container.addeventlistener("contextmenu", checkcontextmenu, true); } the 'checkcontextmenu' function checks to see if the textbox was the target of the context menu and, if so, cancels the event using the preventdefault method.
... <script> function showhidedeleteitem() { var deleteitem = document.getelementbyid("delete"); var rows = document.getelementbyid("rows"); deleteitem.hidden = (rows.childnodes.length == 0); } </script> <menupopup id="inssel-menu" onpopupshowing="showhidedeleteitem()"> <menuitem label="insert"/> <menuitem id="delete" label="delete"/> </menupopup> in this example, the showhidedeleteitem function is called when the popupshowing event is fired.
... var element = aevent.target.triggernode; var isimage = (element instanceof components.interfaces.nsiimageloadingcontent && element.currenturi); document.getelementbyid("enlarge").hidden = !isimage; document.getelementbyid("details").hidden = !isimage; } </script> <menupopup id="contentareacontextmenu" onpopupshowing="showhideitems(event)"> <menuitem label="copy"/> <menuitem id="enlarge" label="enlarge image"/> <menuitem id="details" label="image details"/> </menupopup> <browser src="http://www.mozilla.org" context="contentareacontextmenu"/> ...
PopupEvents - Archive of obsolete content
<script> function openfilemenu() { var filemenu = document.getelementbyid("file-menu"); filemenu.addeventlistener("popupshown", filemenuopened, false); filemenu.open = true; } function filemenuopened(event) { if (event.target != document.getelementbyid("file-menupopup")) return; var filemenu = document.getelementbyid("file-menu"); filemenu.removeeventlistener("popupshown", filemenuopened, false); var openmenu = document.getelementbyid("open-...
...<panel onpopuphiding="document.getelementbyid('search').value = '';"> <textbox id="search"/> <button label="search" oncommand="dosearch();"/> </panel> you can prevent a popup from hiding by calling the event's preventdefault method.
...you can tell that the entire chain is closed when the topmost menu receives a popuphidden event.
Property - Archive of obsolete content
mmandmanager completedefaultindex container contentdocument contentprincipal contenttitle contentview contentvieweredit contentviewerfile contentwindow contextmenu control controller controllers crop current currentindex currentitem currentnotification currentpage currentpane currentset currenturi customtoolbarcount database datasources date dateleadingzero datevalue decimalplaces decimalsymbol defaultbutton defaultvalue description dir disableautocomplete disableautocomplete disableautoselect disabled disablekeynavigation dlgtype docshell documentcharsetinfo editable editingcolumn editingrow editingsession editor editortype emptytext deprecated since gecko 2 enablecolumndrag eventnode fir...
...rwhilesearching image increment inputfield inverted is24hourclock ispm issearching iswaiting itemcount label labelelement lastpermanentchild lastselected left linkedpanel listboxobject locked markupdocumentviewer max maxheight maxlength maxrows maxwidth menu menuboxobject menupopup min minheight minresultsforpopup minwidth minute minuteleadingzero mode month monthleadingzero name next nomatch notificationshidden object observes onfirstpage onlastpage open ordinal orient pack pagecount pageid pageincrement pageindex pagestep parentcontainer palette persist persistence placeholder pmindicator popup popupboxobject popupopen position predicate preferenceelements prefe...
...ebprogress width wizardpages wraparound year yearleadingzero related dom element properties dom:element.attributes dom:element.baseuri dom:element.childelementcount dom:element.childnodes dom:element.children dom:element.clientheight dom:element.clientleft dom:element.clienttop dom:element.clientwidth dom:element.clonenode dom:element.firstchild dom:element.firstelementchild dom:element.lastchild dom:element.lastelementchild dom:element.localname dom:element.namespaceuri dom:element.nextelementsibling dom:element.nextsibling dom:element.nodename dom:element.nodetype dom:element.nodevalue dom:element.ownerdocument dom:element.parentnode dom:element.prefix dom:element.previouselementsibling dom:element.previoussibling dom:element...
Template Builder Interface - Archive of obsolete content
getservice(components.interfaces.nsirdfservice); var ds = rdf.getdatasource("http://www.xulplanet.com/ndeakin/tests/xul/template-guide-streets.rdf"); var tree = document.getelementbyid("thetree"); tree.database.adddatasource(ds); tree.builder.rebuild(); this is the typical way to add a datasource to an element, in this case to the tree with the id 'thetree'.
...fortunately in this situation, you can just set the datasources attribute (or the corresponding property) to the datasources that you want.
... for instance: var tree = document.getelementbyid("thetree"); tree.datasources = "template-guide-photos5.rdf template-guide-streets.rdf"; this will also change the datasources used.
Textbox (XPFE autocomplete) - Archive of obsolete content
this attribute only works correctly in seamonkey 1.x; for thunderbird and seamonkey 2.0 you should also set the enablehistory attribute; as of gecko 2.0 this attribute is completely superseded by it.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
... related interfaces nsiaccessibleprovider, nsidomxulmenulistelement ...
Box Objects - Archive of obsolete content
the layout object associated with an element can be removed and a completely different type of object created just by changing the css display property, among others.
...example 2 : source view <script> function showpositionandsize() { var labelbox = document.getelementbyid('thelabel').boxobject; alert("position is (" + labelbox.x + "," + labelbox.y + ") and size is (" + labelbox.width + "," + labelbox.height + ")"); } </script> <button label="hide" oncommand="document.getelementbyid('thelabel').hidden = true;"/> <button label="show" oncommand="document.getelementbyid('thelabel').hidden = false;"/> <button label="collapse...
..." oncommand="document.getelementbyid('thelabel').collapsed = true;"/> <button label="uncollapse" oncommand="document.getelementbyid('thelabel').collapsed = false;"/> <button label="show position/size" oncommand="showpositionandsize();"/> <label id="thelabel" value="i am a label"/> note that if you hide and collapse the label, it will be treated as hidden.
Creating Dialogs - Archive of obsolete content
var somefile=document.getelementbyid('enterfile').value; window.opendialog("chrome://findfile/content/showdetails.xul","showmore", "chrome",somefile); in this example the dialog showdetails.xul is displayed.
...for example: var fl = window.arguments[0]; document.getelementbyid('thefile').value = fl; this is an effective way to pass values to the new window.
...ion label="select favourite fruit"/> <radio id="orange" label="oranges because they are fruity"/> <radio id="violet" selected="true" label="strawberries because of their colour"/> <radio id="yellow" label="bananas because they are pre-packaged"/> </groupbox> </dialog> the buttons elements can be accessed with the following javascript // the accept button var acceptbutt = document.documentelement.getbutton("accept") more examples more examples in dialogs and prompts (code snippets).
Focus and Selection - Archive of obsolete content
example 2 : source view <script> function displayfocus(){ var elem=document.getelementbyid('sbar'); elem.setattribute('value','enter your phone number.'); } </script> <textbox id="tbox1"/> <textbox id="tbox2" onfocus="displayfocus();"/> <description id="sbar" value=""/> the focus event, when it occurs, will call the displayfocus function.
...example 3 : source view <window id="focus-example" title="focus example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init(){ addeventlistener("focus",setfocusedelement,true); } function setfocusedelement(){ var focused = document.commanddispatcher.focusedelement; document.getelementbyid("focused").value = focused.tagname; } </script> <hbox> <label control="username" value="user name:"/> <textbox id="username"/> </hbox> <button label="hello"/> <checkbox label="remember this decision"/> <label id="focused" value="-no focus-"/> </window> in this example, a focus event handler is attached the window.
...the following example demonstrates this: example 5 : source view <textbox id="addr"/> <button label="focus" oncommand="document.getelementbyid('addr').focus()"/> or, you can use the methods advancefocus and rewindfocus on the command dispatcher.
Skinning XUL Files by Hand - Archive of obsolete content
in the very near future, it will be possible to skin xul files dynamically and completely -- by pressing a button, selecting a skin from a menu, or by accepting a skin from over the web.
...the skin will reside in a single css file, appropriately named drxul.css.
...what you have done manually in this article will be done dynamically and much more completely by a mechanism called thechrome registry.
Tree Box Objects - Archive of obsolete content
example 1 : source view <script> function doscroll(){ var value = document.getelementbyid("tbox").value; var tree = document.getelementbyid("thetree"); var boxobject = tree.boxobject; boxobject.queryinterface(components.interfaces.nsitreeboxobject); boxobject.scrolltorow(value); } </script> <tree id="thetree" rows="4"> <treecols> <treecol id="row" label="row" primary="true" flex="1"/> </treecols> <treechildren> <treeitem label="row 0"/> <treeitem l...
... example 2 : source view <script> function updatefields(event){ var row = {}, column = {}, part = {}; var tree = document.getelementbyid("thetree"); var boxobject = tree.boxobject; boxobject.queryinterface(components.interfaces.nsitreeboxobject); boxobject.getcellat(event.clientx, event.clienty, row, column, part); if (column.value && typeof column.value != "string") column.value = column.value.id; document.getelementbyid("row").value = row.value; document.getelementbyid("column").value = column.value; ...
... document.getelementbyid("part").value = part.value; } </script> <tree id="thetree" flex="1" onmousemove="updatefields(event);"> <treecols> <treecol id="utensil" label="utensil" primary="true" flex="1"/> <treecol id="count" label="count" flex="1"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="fork"/> <treecell label="5"/> </treerow> </treeitem> <treeitem> <treerow> <treecell label="knife"/> <treecell label="2"/> </treerow> </treeitem> <treeitem> <treerow> <treecell label="spoon"/> <treecell label="8"/> </treerow> </treeitem> </treechildren> </tree> <label value="row:"/> <label id="row"/> <label value="column:"/> <label id="column"/> <label value="...
Tree View Details - Archive of obsolete content
function init() { document.getelementbyid("elementlist").view = treeview; } the custom tree view will need to implement a number of methods, of which the important ones will be examined individually.
... whether opening or closing a row, we need to tell the tree to repaint the twisty in the new state.
... cycleheader: function(col, elem) {}, selectionchanged: function() {}, cyclecell: function(idx, column) {}, performaction: function(action) {}, performactiononcell: function(action, index, column) {}, getrowproperties: function(idx, prop) {}, getcellproperties: function(idx, column, prop) {}, getcolumnproperties: function(column, element, prop) {}, }; function init() { document.getelementbyid("elementlist").view = treeview; } ]]></script> </window> next, we'll look in more detail at the tree box object.
XUL Event Propagation - Archive of obsolete content
for example, if an event handler at the menu is handling an event raised by one of the menu items, then the menu should be able to identify the raising element and take the appropriate action, as in the following example, where a javascript function determines which menuitem was selected and responds appropriately: <script> function docmd(el) { v = el.getattribute("value"); if (v == "new") alert("new clicked"); else if (v == "open") alert("open clicked"); else alert("close clicked"); } </script> ...
...in another example, an onload event handler for a xul window can register a box element to capture all the click events that are raised from its child elements: var bbox = document.getelementbyid("bigbox"); if (bbox) bbox.addeventlistener("click", function() { alert('captured'); }, true); ...
...the syntax for this in xul is as follows: element = document.getelementbyid("id of the element"); element.addeventlistener(event name, event handler function, whether to register a capturing listener); the event handler code argument can be in-line code or a function.
preference - Archive of obsolete content
type getelementvalue(in domelement element); retrieves the value that should be written to preferences based on the current state of the supplied element.
... void setelementvalue(in domelement element); initializes the supplied element from the value stored in the preference.
... inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode()...
radiogroup - Archive of obsolete content
attributes disabled, focused, preference, tabindex, value properties accessibletype, disabled, focuseditem, itemcount, selectedindex, selecteditem, tabindex, value methods appenditem, checkadjacentelement, getindexofitem, getitematindex, insertitemat, removeitemat examples <radiogroup> <radio id="orange" label="red"/> <radio id="violet" label="green" selected="true"/> <radio id="yellow" label="blue"/> </radiogroup> attributes disabled type: boolean indicates whether the element is disabled or not.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
... checkadjacentelement( dir ) return type: no return value deselects the currently selected radio button in the group and selects the one adjacent to it.
tree - Archive of obsolete content
ArchiveMozillaXULtree
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
... column: function getcellchecked(tree, columnid) { var arr = []; var column = tree.columns.getnamedcolumn(columnid); for (var i = 0; i < tree.view.rowcount; i++) { if (tree.view.getcellvalue(i, column) == 'true') arr.push(i); } return arr; } to get the text value for a specific column (for example column 'age') from the currently focused row in the tree: var t = document.getelementbyid('mytree'); document.title = t.view.getcelltext(t.currentindex,t.columns.getnamedcolumn('age')); to select the checkbox and display the cell's text value, you can use code like the following.
...-tree-cell-text(selected) { color: #000000; } treechildren::-moz-tree-cell-text(odd, selected) { color: #000000; } treechildren::-moz-tree-row(hover) {background-color: #ffffaa !important;} treechildren:-moz-tree-column { border-right:1px solid rgb(220,220,220) !important; } the javascript to get the text for the selected row/rows: function getrowcellvalues() { var tree = document.getelementbyid('mytree'); for (var i = 0; i < tree.view.rowcount; i++) { if (tree.view.getcellvalue(i, tree.columns.getcolumnat(0)) == 'true'){ alert(tree.view.getcelltext(i, tree.columns.getnamedcolumn("name"))); } } } this way, you can get the tree cell values of the selected checkbox of the corresponding row.
Application Update - Archive of obsolete content
as far as i can tell enabling the options --enable-updater and --enable-update-packaging on your configure will build you mar.
...other apps may wish to show this ui, and supply // a whatsnewurl field in their brand.properties that contains a link to a page // which tells users what's new in this new update.
... update.xml the format is outlined here process as best i can tell here's how the update process works.
Getting started with XULRunner - Archive of obsolete content
here is the application root chrome.manifest: manifest chrome/chrome.manifest step 6: set up preferences the prefs.js file tells xulrunner the name of the xul file to use as the main window.
... main.js: function showmore() { document.getelementbyid("more-text").hidden = false; } for more information about xul see: xul.
... alternative: run xul apps with firefox with firefox 3 and later, you can tell the firefox executable to run a xul application from the command line.
How to enable locale switching in a XULRunner application - Archive of obsolete content
modify the application preferences first, you need to tell xulrunner that your application wishes to ignore the default os locale and that it will do its own choosing instead.
...itoolkitchromeregistry); var selectedlocale = xulchromereg.getselectedlocale("localeswitchdemo"); var availablelocales = toolkitchromereg.getlocalesforpackage("localeswitchdemo"); // render locale menulist by iterating through the query result from getlocalesforpackage() const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var localelistbox = document.getelementbyid("locale-listbox"); var selecteditem = null; while(availablelocales.hasmore()) { var locale = availablelocales.getnext(); var listitem = document.createelementns(xul_ns, "listitem"); listitem.setattribute("value", locale); listitem.setattribute("label", locale); if (locale == selectedlocale) { // is this the current locale?
... var localelistbox = document.getelementbyid("locale-listbox"); var newlocale = localelistbox.selecteditem.value; // write preferred locale to local user config var prefs = components.classes["@mozilla.org/preferences-service;1"].
Adobe Flash - Archive of obsolete content
fortunately, mach-o browsers based on netscape gecko expose this information in their user-agent string.
... performance and flash as is the case with any plug-in content, flash content has the potential to slow down or even completely stall not just the tab it's running in, but the entire browser and even the entire computer it's being used on.
... var myflash = document.getelementbyid("myflash").setvariable("myvar", sendtext); a more expanded code example that shows how example 2 was created is shown in this source listing.
Encryption and Decryption - Archive of obsolete content
encryption is the process of transforming information so it is unintelligible to anyone but the intended recipient.
... decryption is the process of transforming encrypted information so that it is intelligible again.
...on the other hand, symmetric-key ciphers can achieve approximately the same level of strength with an 80-bit key for most algorithms.
SSL and TLS - Archive of obsolete content
because the key size is so large, there are approximately 3.7 * 1050 possible keys.
...the rc4 and rc2 ciphers have 128-bit encryption, which permits approximately 3.4 * 1038 possible keys.
...des 56-bit encryption permits approximately 7.2 * 1016 possible keys.
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
unfortunately, a few browsers don't get this right, and end up flowing the cards as a single vertical column instead of putting the fish side by side.
... floating fish with the cards set up to float, the next step was to place the images appropriately.
...: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {border: 1px solid #339; border-left: 5px double #339; background: #eec url(body-bg-tan.jpg) bottom left no-repeat fixed; color: #339;} finishing the style adding the background to the heading containing the name of the fish created three problems: the double border was completely covered up by the image.
Using the Right Markup to Invoke Plugins - Archive of obsolete content
for instance, the param name="movie" tells the flash plugin the location of the swf file to start playing.
...at a minimum, web authors will have to nest some alternate text inside their object elements telling users where to obtain the missing component.
...47, which don't understand the <param name="movie" value="animation.swf"> param element, which is supposed to tell the flash player which animation to start playing.
Game distribution - Game development
direct link distribution and instant play you don't have to tell people to search for your game in an app store with html5 games.
...the biggest desktop store for games is definitely steam — indie developers can get on steam via the steam direct program.
... other alternative tools are: intel xdk — an exciting alternative, similar to cocoonio.
Game promotion - Game development
website and blog you should definitely create your own website containing all the information about your games, so people can see what you've worked on.
...remember to not be too pushy on telling everyone about your games — you're not a walking advertisement.
... if you want to learn more about the etiquette of contacting the press you should definitely check out how to contact press - a great guide from pixel prospector, and the video game journaliser site curated by them for the list of sites to contact.
Building up a basic demo with A-Frame - Game development
dd this just before the closing </a-scene> element: <a-camera position="0 1 4" cursor-visible="true" cursor-scale="2" cursor-color="#0095dd" cursor-opacity="0.5"> </a-camera> we've also defined a cursor for the given camera, using the cursor-* attributes (by default it is invisible.) — we've set its scale so it will more easily visible, its color, and some opacity so it won't completely covering the objects behind it.
...the duration is set to 4 seconds, and it will be repeated indefinitely.
...again, the animation is being repeated indefinitely.
Mobile accessibility - Learn web development
long gone are the days when mobile devices ran completely different web technologies to desktop browsers, forcing developers to use browser sniffing and serve them completely separate sites (although quite a few companies still detect usage of mobile devices and serve them a separate mobile domain).
...there are certain situations where zooming might break the ui; in such cases, if you feel that you absolutely need to disable zoom, you should provide some other kind of equivalent, such as a control for increasing the text size in a way that doesn't break your ui.
...for example: types number, tel, and email display suitable virtual keyboards for entering numbers/telephone numbers.
What is accessibility? - Learn web development
people with cognitive impairments cognitive impairment refers to a broad range of disabilities, from people with intellectual disabilities who have the most-limited capabilities, to all of us as we age and have difficulty thinking and remembering.
... in the u.s., “intellectual disabilities” is the new term for “mental retardation.” in the u.k., “intellectual disabilities” is commonly “learning disabilities” or “learning difficulties”.
... so while the wcag is a set of guidelines, your country will probably have laws governing web accessibility, or at least the accessibility of services available to the public (which could include websites, television, physical spaces, etc.) it is a good idea to find out what your laws are.
Cascade and inheritance - Learn web development
while working through this lesson may seem less immediately relevant and a little more academic than some other parts of the course, an understanding of these things will save you much pain later on!
...however, we strongly recommend that you never use it unless you absolutely have to.
...this is definitely the most complicated thing we've covered so far in the course, and is something that even professional web developers sometimes find tricky.
CSS values and units - Learn web development
this takes a value from 0–100%, where 0 is no light (it will appear completely black) and 100% is full light (it will appear completely white) we can update the rgb example to use hsl colors like this: just as rgb has rgba, hsl has an hsla equivalent, which gives you the same ability to specify the alpha channel.
...these keywords are more accurately described as identifiers, a special value that css understands.
...we can't do this calculation beforehand because we don't know what 20% of the parent will be, so we use calc() to tell the browser to do it for us.
What is a Domain Name? - Learn web development
tlds tell users the general purpose of the service behind the domain name.
...most of them provide a “whois” service that tells you whether a domain name is available.
... if your computer does not know which ip is behind the mozilla.org name, it goes on to ask a dns server, whose job is precisely to tell your computer which ip address matches each registered domain name.
Define terms with HTML - Learn web development
special case: abbreviations it's best to mark abbreviations specially with <abbr>, so that screen readers read them appropriately and so that you can operate on all abbreviations uniformly.
...the contents of title are completely hidden from your users, unless they're using a mouse and they happen to hover over the abbreviation.
...the matching description follows immediately, contained within one or more <dd> elements.
Document and website structure - Learn web development
this is the one part of the website that definitely will vary from page to page!
... this is because visuals don't tell the whole story.
... note: colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind.
What’s in the head? Metadata in HTML - Learn web development
you should see something like this: it should now be completely obvious where the <h1> content appears, and where the <title> content appears!
... it may change over time): <meta name="description" content="the mdn web docs site provides information about open web technologies including html, css, and apis for both web sites and progressive web apps."> now search for "mdn web docs" in your favorite search engine (we used google.) you'll notice the description <meta> and <title> element content used in the search result — definitely worth having!
... note: in google, you will see some relevant subpages of mdn web docs listed below the main homepage link — these are called sitelinks, and are configurable in google's webmaster tools — a way to make your site's search results better in the google search engine.
HTML table basics - Learn web development
LearnHTMLTablesBasics
unfortunately, a lot of people used to use html tables to lay out web pages, e.g.
...fortunately, table headers and cells have the colspan and rowspan attributes, which allow us to do just those things.
... providing common styling to columns there is one last feature we'll tell you about in this article before we move on.
Making decisions in your code — conditionals - Learn web development
if you want to go outside, make sure to put some sunscreen on.'; } } even though the code all works together, each if...else statement works completely independently of the other one.
...0; } .output li { display: block; float: left; width: 25%; border: 2px solid white; padding: 5px; height: 40px; background-color: #4a2db6; color: white; } 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'); let code = textarea.value; let userentry = textarea.value; function updatecode() { eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = jssolution; solution.value = 'show solution'; ...
...extcolor; }</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); let code = textarea.value; let userentry = textarea.value; function updatecode() { eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = jssolution; solution.value = 'show solution'; ...
Fetching data from the server - Learn web development
the ajax model involves using a web api as a proxy to more intelligently request data rather than just having the browser reload the entire page.
... request.onload = function() { poemdisplay.textcontent = request.response; }; the above is all set up for the xhr request — it won't actually run until we tell it to, which is done using the send() method.
... effectively, the function passed into then() is a chunk of code that won't run immediately.
Useful string methods - Learn web development
em); } } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); let code = textarea.value; let userentry = textarea.value; function updatecode() { eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = jssolution; solution.value = 'show solution'; ...
...stitem); } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); let code = textarea.value; let userentry = textarea.value; function updatecode() { eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = jssolution; solution.value = 'show solution'; ...
...titem); } </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="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; } const textarea = document.getelementbyid('code'); const reset = document.getelementbyid('reset'); const solution = document.getelementbyid('solution'); let code = textarea.value; let userentry = textarea.value; function updatecode() { eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; userentry = textarea.value; solutionentry = jssolution; solution.value = 'show solution'; ...
Object-oriented JavaScript for beginners - Learn web development
you can also define the same feature separately in different classes, as each definition of that feature will be in a different namespace.
...fortunately, javascript provides us with a handy shortcut, in the form of constructor functions — let's make one now!
... let's look at the constructor calls again: let person1 = new person('bob'); let person2 = new person('sarah'); in each case, the new keyword is used to tell the browser we want to create a new object instance, followed by the function name with its required parameters contained in parentheses, and the result is stored in a variable — very similar to how a standard function is called.
CSS performance optimization - Learn web development
to create a non-blocking css link, move the not-immediately used styles, such as print styles, into separate file, add a <link> to the html mark up, and add a media query, in this case stating it's a print stylesheet.
...tell the browser when the style sheet should be applied by adding a media attribute with the media query.
... will-change property the css will-change property tells browsers which properties of an element are expected to change enabling browsers to set up optimizations before the element is actually changed, improving performance by doing potentially expensive work before it is required.
Ember interactivity: Events, classes and state - Learn web development
add the new line shown below to your header.hbs file: <input class='new-todo' aria-label='what needs to be done?' placeholder='what needs to be done?' autofocus {{on 'keydown' this.onkeydown}} > this new attribute is inside double curly braces, which tells you it is part of ember's dynamic templating syntax.
... coming back to our browser tab with the app running, we can type whatever we want, and when we hit enter we'll be greeted with an alert message telling us exactly what we typed.
...whenever you enter a new todo item, a new list item appears below the text input, but unfortunately it always says "buy movie tickets".
Introduction to client-side frameworks - Learn web development
the code that will render our items on the page might read something like this: function rendertodolist() { const frag = document.createdocumentfragment(); state.tasks.foreach(task => { const item = buildtodoitemel(task.id, task.name); frag.appendchild(item); }); while (todolistel.firstchild) { todolistel.removechild(todolistel.firstchild); } todolistel.appendchild(frag); } we've now got well over thirty lines of code dedicated just to the ui – just to the step of rendering something in the dom – and at no point do we add classes that we could use later to style our list-items!
...this snippet reduces approximately thirty-two lines of code down to six lines.
...no matter how you build for the web, the end result, the layer that your users ultimately interact with, is html.
Starting our Svelte Todo list app - Learn web development
for example: <button class="btn toggle-btn" aria-pressed="true"> <span class="visually-hidden">show</span> <span>all</span> <span class="visually-hidden">tasks</span> </button> here, aria-pressed tells assistive technology (like screen readers) that the button can be in one of two states: pressed or unpressed.
... the aria-labelledby attribute tells assistive technologies that we're treating our <h2> with an id of list-heading as the label that describes the purpose of the list beneath it.
... moreover, our editor can display this warning even before calling the compiler: you can tell svelte to ignore this warning for the next block of markup with a comment beginning with svelte-ignore, like this: <!-- svelte-ignore a11y-missing-attribute --> <img height="32" width="88" src="https://udn.realityripple.com/samples/b0/98dase3c7d.png"> note: with vscode you can automatically add this ignore comment by clicking on the quick fix...
Getting started with Svelte - Learn web development
.gitignore: tells git which files or folder to ignore from the project — useful if you decide to include your app in a git repo.
...this configuration file tells rollup how to compile and build your app.
... using the svelte repl a repl (read–eval–print loop) is an interactive environment that allows you to enter commands and immediately see the results — many programming languages provide a repl.
Focus management with Vue refs - Learn web development
however, it also means you often should not edit your html elements directly through native browser apis (like document.getelementbyid) when using frameworks, because it results in the vdom and real dom going out of sync.
...because vue is trying to optimize and batch changes, it won't immediately update the dom when we set isediting to false.
... mounted() { const labelinputref = this.$refs.labelinput; labelinputref.focus(); } now when you activate the "edit" button with your keyboard, focus should immediately be moved to the edit <input>.
Introduction to cross browser testing - Learn web development
on the other hand, it is not ok for a site to work fine for sighted users, but be completely inaccessible for visually impaired users because their screen reader application can't read any of the information stored on it.
...as a web developer, you need to agree on a range of browsers and devices that the code definitely needs to work on with the site owner, but beyond that, you need to code defensively to give other browsers the best chance possible of being able to use your content.
...this situation is a lot less bad than it used to be; back when ie4 and netscape 4 were competing to be the dominant browser in the 1990s, browser companies deliberately implemented things differently to each other to try to gain competitive advantage, which made life hell for developers.
Setting up your own test automation environment - Learn web development
lambdatest getting selenium tests to run remotely on lambdatest is very simple.
... browser.executescript("lambda-status=failed");​​​​​​ browserstack getting selenium tests to run remotely on browserstack is easy.
... if you now go back to your browserstack automation dashboard page, you should see your test session available, as before, but with the updated data attached to it: sauce labs getting selenium tests to run remotely on sauce labs is also very simple, and very similar to browserstack albeit with a few syntactic differences.
Introducing a complete toolchain - Learn web development
this tells the npm tool that these particular dependencies are only needed for development (npm therefore lists them in the package.json file under devdependencies, not dependencies).
... if the browser tries to run the source javascript it will immediately complain; the project needs a build tool to transform the source code to something the browser can consume without issue.
... you could also try using eslint and prettier too — try deliberately removing a load of the whitespace from one of your files and try put prettier on it to clean it up, or introduce a syntax error into one of your javascript files and see what errors eslint gives you when you try to use parcel to build it again.
Software accessibility: Where are we today?
unfortunately, the unit is not currently produced, although there is occasional talk of resurrecting this useful device.
...ideally, intelligent decisions are made, so the user does not have to wade through as much non-relevant data.
...however, all these solutions fell short of providing people with disabilities with a working environment which was completely accessible and usable by them.
Command line options
see the article on remotely debugging firefox desktop.
... -osint tells the application that it is being launched by the os shell.
... -requestpending tells the application that there will be a windows dde request to open the same url specified on the command line.
How Mozilla's build system works
config.status is charged with the task of telling a tool how to build the tree.
...think of each moz.build file as a data structure telling the build system what to do.
...these are how the execution of a moz.build file tells the build system what to do.
Cross Process Object Wrappers
*/ var button = content.document.getelementbyid("click-me"); button.addeventlistener("mouseover", function (event) { sendasyncmessage("my-addon-message", {}, { element : event.target }); }, false); // chrome script /* load the frame script, then listen for the message.
... performance although the wrapper looks just like an object completely contained in the chrome script scope, it's really just a reference to an object in the content process.
...the content process can respond immediately to the cpow call: there is still a performance cost to the cpow in this situation, because the cpow call is an ipc call instead of a simple property access in the same process.
Performance best practices for Firefox front-end engineers
normally, the changes to the dom just result in the standard style calculation occurring immediately after the javascript has finished running during the 16ms window, inside the "style" step.
... it should be possible to write a test that gets the nsidomwindowutils for a browser window, records the number of styleflushes, then synchronously calls the function that you want to test, and immediately after checks the styleflushes attribute again.
...normally, however, the changes to the dom just result in the standard style calculation that occurs immediately after the javascript has finished running during the 16ms window.
Gecko SDK
issues with the os x sdk if you need to use the xpidl utility to compile idl files on os x, it's likely that you will receive a strange error when running the tool that looks something along the lines of this: dyld: library not loaded: /opt/local/lib/libintl.3.dylib referenced from: /users/varmaa/xulrunner-sdk/bin/./xpidl reason: image not found trace/bpt trap unfortunately, this is caused by a problem with the sdk build process which cannot currently be resolved (see bugzilla bug #430274).
... mac intel gecko 1.8 sdk the official mac 1.8 sdk is a ppc version.
... this is an unofficial intel build.
How to get a stacktrace for a bug report
a stacktrace will tell mozilla developers what crashed and provide a starting point for investigating its cause.
...be sure that you check the "tell mozilla about this crash" checkbox and click the restart button.
...tell us the id of the report you submitted.
Extending a Protocol
it's quite involved and, unfortunately, all steps need to be done before we can successfully recompile.
...unfortunately, it's not really fully documented anywhere - and the ipdl parser gets easily confused (hence us excluding comments below).
...scroll to the end and add private member: refptr<echochild> mechochild; } // namespace dom } // namespace mozilla navigator.cpp - getechochild() now, add the following includes at the top of the file: #include "mozilla/dom/echochild.h" #include "mozilla/dom/windowglobalchild.h" to the "ns_impl_cycle_collection_unlink_begin(navigator)" we can now tell gecko that mechochild can participate, so let's add: ns_impl_cycle_collection_unlink(mechochild) now, the getechochild() private method will do the intial setup for us.
AsyncShutdown.jsm
for instance, at the end of phase profilebeforechange, no service is permitted to write to the profile directory (with the exception of telemetry).
... sendtelemetry read only phase telemetry is being sent.
... this phase represents the last chance for telemetry to write data.
Sqlite.jsm
since sqlite.jsm manages statements for you, it can perform intelligent actions like purging all cached statements not in use, freeing memory in the process.
...this is a glorified wrapper around the pragma shrink_memory statement, which tells sqlite to shrink its memory usage (by clearing caches, etc).
...consumers of this api can call the cancel function should they want to immediately abort the execution of the statement.
Localizing with Koala
also, searchbar.dtd is no longer displayed in the "compare" view, as it has been completely translated.
... here's a quick summary of what the output of the comparison means: files: "unmodified" - the file is completely translated.
...also, removing files works in a similar manner: not only do you have to delete the file, but also you need to tell mercurial to stop tracking the file with "hg remove".
Localizing without a specialized tool
with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation.
...x-testing: unchanged: 2 changed: 3 missinginfiles: 6117 missing: 13 0% of entries changed the beauty of the compare-locales output is that it tells you all the missing files and which files you need to add and localize.
... for instance, enter the proper translation for the line "add %s" cmd_addfoundengine=add "%s" with these two string examples translated, you can now test your work to see immediately where you have translated.
Mozilla Web Developer FAQ
you should not rely on mozilla’s document.all support on new pages.) the method document.getelementbyid() can be used instead.
...the correct way to access an element by id is to call the document.getelementbyid() method with the id as a string as the argument.
...for example, the existence of document.getelementbyid() can be checked as follows: if(document.getelementbyid) { /* code that uses document.getelementbyid() */ } why doesn’t mozilla display my alt tooltips?
Mozilla Quirks Mode Behavior
(this also applies to getelementsbyclassname.) stylesheets linked in the document with an advisory mime type of text/css will still be treated as css even if the server gives a content-type header other than text/css.
... in quirks mode, text-decoration is propagated into floating and absolutely positioned elements.
...i don't follow the code in nscssrenderingborders well enough to tell, though.] in quirks mode a fixed width specified on a table cell resets the nowrap attribute.
BloatView
| 24 48| 3086 2| 279 |messagepump | 8 8| 30 1| 285 |mutex | 20 60| 89987 3| 302 |pcompositorchild | 412 412| 1 1| 308 |pimagebridgechild | 416 416| 1 1| the first line tells you the pid of the leaking process, along with the type of process.
...that means no one is looking at them, and we won't be able to tell if someone introduces a leak.
... to do so, the xpcom_mem_log_classes environment variable should be set to the name of the class from the bloatview table: xpcom_mem_log_classes=myclass mach mochitest [options] multiple class names can be specified by setting xpcom_mem_log_classes to a comma-separated list of names: xpcom_mem_log_classes=myclass,myotherclass,deliberatelyleakedclass mach mochitest [options] test harness scripts typically accept a --setenv option for specifying environment variables, which may be more convenient in some cases: mach mochitest --setenv=xpcom_mem_log_classes=myclass [options] for getting allocation stacks in automation, you can add the appropriate --setenv options to the test configurations for the platforms you're interested in.
Refcount tracing and balancing
warning: you should never use this without xpcom_mem_log_classes and/or xpcom_mem_log_objects, because without some filtering the logging will be completely useless due to how slow the browser will run and how large the logs it produces will be.
... what this little tree is telling you is that you leak one refcount overall on object 0x00253ab0.
...the make-tree.pl script accepts an option --ignore-balanced, which tells it not to bother printing out the children of a node whose balance factor is zero.
Scroll-linked effects
<body style="height: 5000px" onscroll="document.getelementbyid('toolbar').style.top = math.max(100, window.scrolly) + 'px'"> <div id="toolbar" style="position: absolute; top: 100px; width: 100px; height: 20px; background-color: green"></div> </body> this implementation of sticky positioning relies on the scroll event listener to reposition the "toolbar" div.
... } else if (math.abs(destination - window.scrolly) < 200) { scrollto(window.scrollx, window.scrolly + ((destination - window.scrolly) / 2)); settimeout(snap, 20, destination); } } var timeoutid = null; addeventlistener("scroll", function() { if (timeoutid) cleartimeout(timeoutid); timeoutid = settimeout(snap, 200, parseint(document.getelementbyid('snaptarget').style.top)); }, true); </script> <div id="snaptarget" class="snaptarget" style="position: relative; top: 200px; width: 100%; height: 200px; background-color: green"></div> </body> in this example, there is a scroll event listener which detects if the scroll position is within 200 pixels of the top of the "snaptarget" div.
...in order to do so, we need you (yes, you!) to tell us more about the kinds of scroll-linked effects you are trying to implement, so that we can find good ways to support them in the compositor.
about:memory
(the filename will have a .json.gz suffix.) you can then attach or upload the file appropriately.
...if you find any particular tree overwhelming, it can be helpful to collapse all the sub-trees immediately below the root, and then gradually expand the sub-trees of interest.
... all javascript memory usage for an add-on is measured separately and shown in this sub-tree.
Performance
adding a new telemetry probe information on how to add a new measurement to the telemetry performance-reporting system profiling javascript with shark (obsolete - replaced by instruments) how to use the mac os x shark profiler to profile javascript code in firefox 3.5 or later.
... tools/power/rapl (mac, linux) tools/power/rapl is a command-line utility in the mozilla codebase that uses the intel rapl interface to gather direct power estimates for the package, cores, gpu and memory.
... intel power gadget (windows, mac, linux) intel power gadget provides real-time graphs for package and processor rapl estimates.
AsyncTestUtils extended framework
returning false tells the asynchronous driver that it should yield control up to the top-level.
...we do not mark the folders as offline and therefore do not attempt to download the messages so that they are immediately available for offline use.
...we mark the folders as offline and download the messages so that they are immediately available for offline use.
About NSPR
this allows a minimal timer period in of approximately 12 hours.
...use of 64 bits allows a representation of times approximately in the range of -30000 to the year 30000.
...depending on the platform, the functions may be implemented almost entirely in the nspr runtime or simply shims that call immediately into the host operating system's offerings.
NSPR Contributor Guide
see also: xxx ownership of your contribution when you contribute something to nspr, you must have intellectual property rights to that contribution.
...if you snatched it from somewhere else, tell us where; show us where the right to incorporate it into nspr exists.
...we may tell you that you have a good idea; we may say that it really is not a good candidate for inclusion in nspr; we may give you suggestions on what would make it more generalized, hence a good candidate for inclusion in nspr.
PRIntervalTime
it should therefore never be used for intervals greater than approximately 6 hours.
...they indicate that the process should wait no time (return immediately) or wait forever (never time out), respectively.
...at that rate, a 32-bit register will overflow in approximately 28 hours, making the maximum useful interval approximately 6 hours.
NSS_3.12_release_notes.html
k_fetching cert_rev_m_forbid_network_fetching cert_rev_m_allow_implicit_default_source cert_rev_m_ignore_implicit_default_source cert_rev_m_skip_test_on_missing_source cert_rev_m_require_info_on_missing_source cert_rev_m_ignore_missing_fresh_info cert_rev_m_fail_on_missing_fresh_info cert_rev_m_stop_testing_on_fresh_info cert_rev_m_continue_testing_on_fresh_info cert_rev_mi_test_each_method_separately cert_rev_mi_test_all_local_information_first cert_rev_mi_no_overall_info_requirement cert_rev_mi_require_some_fresh_info_available cert_policy_flag_no_mapping cert_policy_flag_explicit cert_policy_flag_no_any cert_enable_ldap_fetch cert_enable_http_fetch new macro in utilrename.h: smime_aes_cbc_128 the nssckbi pkcs #11 module's version changed to 1.70.
...bug 217538: softoken databases cannot be shared between multiple processes bug 294531: design new interfaces for certificate path building and verification for libpkix bug 326482: nss ecc performance problems (intel) bug 391296: need an update helper for shared databases bug 395090: remove duplication of pkcs7 code from pkix_pl_httpcertstore.c bug 401026: need to provide a way to modify and create new pkcs #11 objects.
...own failure in p7sign bug 324878: crlutil -l outputs false crl names bug 337010: oom crash [[@ nsc_digestkey] dereferencing possibly null att bug 343231: certutil issues certs for invalid requests bug 353371: klocwork 91117 - null pointer dereference in cert_certchainfromcert bug 353374: klocwork 76494 - null ptr derefs in cert_formatname bug 353375: klocwork 76513 - null ptr deref in nsscertificatelist_docallback bug 353413: klocwork 76541 free uninitialized pointer in cert_findcerturlextension bug 353416: klocwork 76593 null ptr deref in nsscryptokiprivatekey_setcertificate bug 353423: klocwork bugs in nss/lib/pk11wrap/dev3hack.c bug 353739: klocwork null ptr dereferences in instance.c bug 353741: klocwork cascading memory leak in mpp_make_prime bug 353742: klocwork null ptr dereference in ...
NSS tools : certutil
-p phone specify a contact telephone number to include in new certificates or certificate requests.
...this request is submitted separately to a certificate authority and is then approved by some mechanism (automatically or by human review).
...the keys generated for certificates are stored separately, in the key database.
NSS_3.12.3_release_notes.html
nss_use_decoded_cka_ec_point boolean (any non-empty value to enable) tells nss to send ec key points across the pkcs#11 interface in the non-standard unencoded format that was used by default before nss 3.12.3.
... nss_use_shexp_in_cert_name boolean (any non-empty value to enable) tells nss to allow shell-style wildcard patterns in certificates to match ssl server host names.
... bug 484425: need accessor function to retrieve symkey handle bug 484466: sec_error_invalid_args with nss_enable_pkix_verify=1 bug 485127: bltest crashes when attempting rc5_cbc or rc5_ecb bug 485140: wrong command line flags used to build intel-aes.s with solaris gas for x86_64 bug 485370: crash bug 485713: files added by red hat recently have missing texts in license headers.
certutil
-p phone specify a contact telephone number to include in new certificates or certificate requests.
...this request is submitted separately to a certificate authority and is then approved by some mechanism (automatically or by human review).
...the keys generated for certificates are stored separately, in the key database.
Index
the allocation will then be retried (and may still fail.) 68 js::setoutofmemorycallback jsapi reference, reference, référence(2), spidermonkey unlike the error reporter, which is only called if the exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called immediately at the oom site to allow the embedding to capture the current state of heap allocation before anything is freed.
... 288 js_getelement jsapi reference, spidermonkey js_getelement examines a specified js object, obj, and its prototype chain, for an element or numeric property numbered index.
... 454 js_setelement jsapi reference, spidermonkey js_setelement assigns a value to a numeric property of an object.
64-bit Compatibility
amd64 pointers if mucking with pointers on amd64 (or em64-t/intel64), it is important to keep in mind an invariant that bits 63-48 must be sign-extended from bit 47.
...lir safety it is not immediately clear from reading lir which opcodes should be used for 64-bit safety.
...to help form well-typed lir, there is a special opcode called lir_float which specifies that the associated constant value is definitely floating-point.
Garbage collection
if so, the engine must immediately restart a full, non-incremental gc in order to reclaim some memory and continue execution.
...this is easily done by simply marking new objects immediately upon allocation during an incremental gc, thus the name allocate-black.
...there are also functions to commit or decommit memory, i.e., tell the os that certain pages are not being used and can be thrown away instead of paged to disk.
Tracing JIT
it is correspondingly very simple: register allocation is done immediately, step-by-step as code is being generated.
...the associated fragment is placed in the monitor's fragment table and the monitor returns to monitoring mode, with a high likelihood of immediately transitioning to executing mode on the next bytecode interpreted.
...if that pc has itself grown hot, the monitor will immediately transition to recording mode starting with the exiting pc.
JIT Optimization Outcomes
arrayrange could not accurately calculate the range attributes of an inline array creation.
... accessnottypedarray accessnotstring statictypedarrayuint32 statictypedarraycantcomputemask outofbounds getelemstringnotcached nonnativereceiver indextype setelemnondensenontanotcached nosimdjitsupport optimization failed because simd jit support was not enabled.
...xedreadexpando icgetpropstub_unboxedarraylength icgetpropstub_typedarraylength icgetpropstub_domproxyshadowed icgetpropstub_domproxyunshadowed icgetpropstub_genericproxy icgetpropstub_argumentslength icsetpropstub_slot icsetpropstub_genericproxy icsetpropstub_domproxyshadowed icsetpropstub_domproxyunshadowed icsetpropstub_callsetter icsetpropstub_addslot icsetpropstub_setunboxed icgetelemstub_readslot icgetelemstub_callgetter icgetelemstub_readunboxed icgetelemstub_dense icgetelemstub_densehole icgetelemstub_typedarray icgetelemstub_argselement icgetelemstub_argselementstrict icsetelemstub_dense icsetelemstub_typedarray icnamestub_readslot icnamestub_callgetter call inlining outcomes optimization outcomes of attempts to inline function calls.
JSAPI User Guide
argc tells how many actual arguments the caller passed, and js_argv(cx, vp) returns an array of those arguments.
...any object you leave lying around will be destroyed if you don't tell the jsapi you're still using it.
...the rest of this section tells how you can control scripts' access to data and functionality.
JSAPI reference
gcharsz added in spidermonkey 1.8.5 obsolete since jsapi 33 js_getstringcharszandlength added in spidermonkey 1.8.5 obsolete since jsapi 33 js_getflatstringchars obsolete since jsapi 33 js_makestringimmutable obsolete since javascript 1.8.5 js_encodecharacters obsolete since jsapi 19 js_cstringsareutf8 obsolete since jsapi 19 js_setcstringsareutf8 obsolete since jsapi 19 interning strings tells the spidermonkey engine to reuse existing string objects when possible.
...alreadyhasownelement added in spidermonkey 1.8 js_alreadyhasownproperty added in spidermonkey 1.8 js_alreadyhasownucproperty added in spidermonkey 1.8 js_alreadyhasownpropertybyid added in spidermonkey 1.8.1 js_defineproperty js_defineucproperty js_definepropertybyid added in spidermonkey 1.8.1 js_defineproperties js_enumerate js_forwardgetpropertyto added in spidermonkey 17 js_forwardgetelementto added in spidermonkey 17 js_getpropertydescriptor added in spidermonkey 31 js_getpropertydescriptorbyid added in spidermonkey 1.8.1 js_getownpropertydescriptor added in spidermonkey 31 js_getownpropertydescriptorbyid added in spidermonkey 31 js_getownucpropertydescriptor added in spidermonkey 45 js_setallnonreservedslotstoundefined added in spidermonkey 24 js_aliasproperty obsole...
... jsgetmethodop obsolete since javascript 1.8.5 jssetmethodop obsolete since javascript 1.8.5 jsenumeratevaluesop obsolete since javascript 1.8.5 jsconcatenateop obsolete since javascript 1.8.5 arrays js_newarrayobject js_isarrayobject js_getarraylength js_setarraylength js_defineelement js_deleteelement js_getelement js_haselement js_setelement js_hasarraylength obsolete since jsapi 8 js_aliaselement obsolete since jsapi 8 js_lookupelement obsolete since jsapi 37 js_deleteelement2 obsolete since jsapi 39 functions calling a function or a method of an object: class js::callargs added in spidermonkey 17 js::callargsfromvp added in spidermonkey 17 js::call added in spidermonkey 17 js::cons...
Web Replay
the data stream should have enough error checking in place that we can immediately detect if the replay has gone out of sync with the recording.
... these threads idle until the recording/replaying content tries to 'create' them, then they run their main function, and after completing it will idle indefinitely.
... a simpler way of telling that a redirection is needed for a function is that the replay tests crash inside it while replaying.
An Overview of XPCOM
in addition to writing well-commented code that tells the client developer the rules about init(), the developer can take a couple steps to make this contract even clearer.
...in this way, construction and initialization can be completely hidden from clients of the class.
... the example in encapsulating the constructor is a simple and stateless version of factories, but real world programming isn't usually so simple, and in general factories need to store state.
Mozilla internal string guide
the 8-bit and 16-bit string classes have completely separate base classes, but share the same apis.
...unfortunately mozilla::result is not versatile enough to be used here.) bulkwrite() returns a mozilla::bulkwritehandle<t>, where t is either char or char16_t.
...fortunately, the getter_copies() function makes this very easy.
Components.utils.exportFunction
es to the argument that are made in the exported function will affect the original object that was passed in: // privileged scope: for example, a content script function changemyname(user) { user.name = "bill"; } exportfunction(changemyname, contentwindow, { defineas: "changemyname" }); // less-privileged scope: for example, a page script var user = {name: "jim"}; var test = document.getelementbyid("test"); test.addeventlistener("click", function() { console.log(user.name); // "jim" window.changemyname(user); console.log(user.name); // "bill" }, false); note that this is subject to the normal rules of xrays: for example, an expando property added to a dom node will not be visible in the original object.
...xrays: // privileged scope: for example, a content script function loguser(user) { // console.log(user.getuser()); // error console.log(user.wrappedjsobject.getuser()); // "bill" } exportfunction(loguser, contentwindow, { defineas: "loguser" }); // less-privileged scope: for example, a page script var user = {getuser: function() {return "bill";}} var test = document.getelementbyid("test"); test.addeventlistener("click", function() { window.loguser(user); }, false); passing functions as arguments if functions are given as arguments, these are also passed as xrays.
... callbacks into the exported function just works, making the allowcallbacks option redundant: // privileged scope: for example, a content script function loguser(getuser) { console.log(getuser()); // "bill" } exportfunction(loguser, unsafewindow, { defineas: "loguser" }); // less-privileged scope: for example, a page script function getuser() { return "bill"; } var test = document.getelementbyid("test"); test.addeventlistener("click", function() { window.loguser(getuser); }, false); cross-origin checking when the exported function is called each argument, including this, is checked to make sure that the caller subsumes that argument.
mozITXTToHTMLConv
last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) inherits from nsistreamconverter implemented by @mozilla.org/txttohtmlconv;1 as a service: var ios = components.classes["@mozilla.org/txttohtmlconv;1"] .getservice(components.interfaces.mozitxttohtmlconv); method overview unsigned long citeleveltxt(in wstring line, out unsigned long loglinestart) void findurlinplaintext(in wstring text, in long alength, in long apos, out long astartpos, out long aendpos) wstring scanhtml(in wstring text, in unsigned long whattodo) wstring scantxt(in wstring text, in unsigned long whattodo) constants conversion control attributes these bits allow you to control the ...
... citeleveltxt() returns the "cite level" of the specified text; that is, it indicates how many levels of email reply quotes are used, when the text uses "quote" characters (such as ">") at the beginning of the line to indicate cite levels.
... unsigned long citeleveltxt( in wstring line, out unsigned long loglinestart ); parameters line the original line of text, which may begin with one or more cite characters such as ">".
nsIDOMNSHTMLDocument
e(in domstring commandid); boolean querycommandsupported(in domstring commandid); domstring querycommandtext(in domstring commandid); obsolete since gecko 14.0 domstring querycommandvalue(in domstring commandid); void releaseevents(in long eventflags); void routeevent(in nsidomevent evt); void write(); obsolete since gecko 2.0 void writeln(); obsolete since gecko 2.0 attributes attribute type description alinkcolor domstring same as body.alink bgcolor domstring same as body.bgcolor compatmode domstring returns "backcompat" if the document is in quirks mode or "css1compat" if the document is in full standards or almost standards mode.
... embeds nsidomhtmlcollection equivalent to getelementsbytagname("embed") read only.
... writeln() obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) void writeln( [optional] in domstring text ); parameters text the string to write to the document.
nsIEditor
; output methods astring outputtostring(in astring formattype, in unsigned long flags); example: // flags are declared in base/public/nsidocumentencoder.idl // outputselectiononly = 1, outputformatted = 2, // outputraw = 4, outputbodyonly = 8, // outputpreformatted = 16, outputwrap = 32, // outputformatflowed = 64, outputabsolutelinks = 258, // outputencodew3centities = 256, outputcrlinebreak = 512, // outputlflinebreak = 1024, outputnoscriptcontent = 2048, // outputnoframescontent = 4096, outputnoformattinginpre = 8192, // outputencodebasicentities=16384, outputencodelatin1entities=32768, // outputencodehtmlentities=65536, outputpersistnbsp=131072 editorapi.outputtostring('text/html', 2); editorapi.outputtos...
...ditorobserver(in nsieditorobserver observer);obsolete since gecko 18 void seteditorobserver(in editactionlistener observer); void removeeditorobserver(in nsieditorobserver observer obsolete since gecko 18); void addeditactionlistener(in nsieditactionlistener listener); void removeeditactionlistener(in nsieditactionlistener listener); void adddocumentstatelistener(in nsidocumentstatelistener listener); void removedocumentstatelistener(in nsidocumentstatelistener listener); debug methods void dumpcontenttree(); void debugdumpcontent() ; void debugunittests(out long outnumtests, out long outnumtestsfailed); [notxpcom] boolean ismodifiablenode(in nsidomnode anode); constants load flags ...
... rootelement nsidomelement read only.
nsIIDNService
converttodisplayidn() normalizes a hostname into utf-8 format if the hostname is in the idn whitelist.
... if the hostname isn't in the whitelist, it's converted into ace format.
...this is useful if you need to normalize a hostname separately from converting it to display format.
nsIJSON
this method accepts slightly more than the exact json syntax; details of extra accepted syntax are deliberately not described.
...this method accepts slightly more than the exact json syntax; details of extra accepted syntax are deliberately not described.
...this method accepts slightly more than the exact json syntax; details of extra accepted syntax are deliberately not described.
nsIProcess
kill() immediately terminates the process represented by the nsiprocess object.
... void run( in boolean blocking, [array, size_is(count)] in string args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately.
... void runw( in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately.
nsISeekableStream
inherits from: nsisupports last changed in gecko 1.7 method overview void seek(in long whence, in long long offset); void seteof(); long long tell(); constants constant value description ns_seek_set 0 specifies that the offset is relative to the start of the stream.
... tell() this method reports the current offset, in bytes, from the start of the stream.
... long long tell(); parameters none.
nsISupports proxies
this is definitely bad.
...for instance, if you need to not only use an object remotely, but also have it created remotely, use the second api.
...calls on object created with this flag will return immediately and you will lose all return information.
Using nsIDirectoryService
although you will not customize these locations, you may need to tell xpcom where its /bin directory is.
...in this case you will also need to tell the system of the location of dlls that are linked against.
...if you are registering it yourself it is very important to register it immediately after calling ns_initxpcom.
Working with Multiple Versions of Interfaces
unfortunately we compiled this in the latest sdk, and so this magic number happens to be: "244e4c67-a1d3-44f2-9cab-cdaa31b68046" whereas, inside firefox 2, the iid it happens to know about is: "663ca4a8-d219-4000-925d-d8f66406b626".
...fortunately there is a plan of action that we can follow to rectify this.
...since these classes don't use vtables this means i'm probably, no i can be more positive, definitely calling the wrong method.
XPIDL
as far as i can tell, these properties also apply to typedefs.
...an out parameter is essentially an auxiliary return value, although these are moderately cumbersome to use from script contexts and should therefore be avoided if reasonable.
...script code callers can ignore the value of array parameter, but implementors must still set the values appropriately.
LDAP Support
in such a scenario, it may be hard to tell which person you really want to send the message to.
...this can be accomplished by setting the following preferences: user_pref("mail.autocomplete.commentcolumn", 2); user_pref("ldap_2.servers.directoryname.autocomplete.commentformat", "[ou]"); the first preference tells us to use a comment column in the type down (the default value is 0 for no comment), and that the value for the comment is a custom string unique to each directory.
... address book attribute ldap attribute firstname givenname lastname sn lastname surname displayname cn displayname commonname displayname displayname nickname xmozillanickname primaryemail mail secondemail xmozillasecondemail workphone telephonenumber homephone homephone faxnumber fax faxnumber facsimiletelephonenumber pagernumber pager pagernumber pagerphone cellularnumber mobile cellularnumber cellphone cellularnumber carphone workaddress postofficebox workaddress streetaddress workcity l wo...
Add to iPhoto
if (document.getelementbyid("contentareacontextmenu")) { document.getelementbyid("contentareacontextmenu").addeventlistener("popupshowing", iphoto.onpopup, false); } responding when the context menu is clicked when the user right-clicks an image, our handler gets called: onpopup: function() { var node = iphoto.getcurrentnode(); var item = document.getelementbyid("add-to-iphoto_menuitem"); if (item) { ...
...if this is null or undefined, we immediately return null, indicating there is no node associated with the context menu.
... null, null, null); var appstr = "file:///applications/iphoto.app"; var appstrcf = corefoundation.cfstringcreatewithcharacters(null, appstr, appstr.length); var appurl = corefoundation.cfurlcreatewithstring(null, appstrcf, null); corefoundation.cfrelease(appstrcf); var b = corefoundation.cfurlgetfsref(appurl, ref.address()); if (!b) { var stringsbundle = document.getelementbyid("string-bundle"); alert(stringsbundle.getstring('alert_download_error_string')); } else { var array = ctypes.cast(mutablearray, corefoundation.cfarrayref); appservices.lsopenurlswithrole(array, 0, null, appparams.address(), null, 0); } corefoundation.cfrelease(appurl); // clean up corefoundation.cfrelease(array); } appservices.shutdown(); c...
Flash Activation: Browser Comparison - Plugins
this can be done by calling a javascript function when the plugin is activated: function plugincreated() { // we don't need to see the plugin, so hide it by resizing var plugin = document.getelementbyid('myplugin'); plugin.height = 0; plugin.width = 0; plugin.callpluginmethod(); } the html, by default, specifies the flash object to be a size that makes it visible, like this: <!-- give the plugin an initial size so it is visible --> <object type="application/x-shockwave-flash" data="myapp.swf" id="myplugin" width="300" height="300"> <param name="callback" value="plugincre...
... using a script callback to determine when a plugin is activated similarly, a site's script shouldn't attempt to script a plugin immediately upon creation.
...html with a callback that calls the javascript function plugincreated(), like this: <object type="application/x-my-plugin" data="somedata.mytype" id="myplugin"> <param name="callback" value="plugincreated()"> </object> the plugincreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make: function plugincreated() { document.getelementbyid('myplugin').callpluginmethod(); } ...
Set a breakpoint - Firefox Developer Tools
continue to here: when stepping through code, this option tells the debugging to continue execution through to this point.
... other context menu options worth mentioning are: disable breakpoint: turn it off, but don't remove it completely.
...now when execution pauses, you can view relevant variables immediately.
Aggregate view - Firefox Developer Tools
for example, the entry for array tells us that there are four array objects in the snapshot.
... let's get an allocation trace: open the memory tool check "record call stacks" load https://mdn.github.io/performance-scenarios/dom-allocs/alloc.html take a snapshot select "view/aggregate" select "group by/call stack" you should see something like this: this is telling us that 93% of the total heap snapshot was allocated in functions called from "alloc.js", line 35 (our initial createtoolbars() call).
... let's see what the example looks like when we select "inverted call stack": now at the top we can immediately see the createtoolbarbutton() call accounting for 89% of the heap usage in our page.
Dominators view - Firefox Developer Tools
dominators tree panel the dominators tree tells you which objects in the snapshot are retaining the most memory.
...immediately underneath that is an entry for: every gc root node.
... immediately under each gc root, you'll see all the nodes for which this root is the immediate dominator.
Work with animations - Firefox Developer Tools
for example, try clicking on the bar for img#icon's animation: this is telling us that two properties were modified: filter and transform.
...it doesn't make much sense to try to animate a geometric property and a translation at the same time — the two effects won't be synchronized — so the transform property is deliberately not handed over to the compositor to handle.
... the animation inspector will tell you this — look at it now and you'll see that: the white lightning bolt icon in the bar has been replaced with a grey lightning bolt icon, to indicate that only some of the relevant properties are being optimized by the compositor.
Console messages - Firefox Developer Tools
async stack frames stack traces show stack frames for async functions separately from those for synchronous functions.
... synchronous and asynchronous reflows if a change is made that invalidates the current layout — for example, the browser window is resized or some javascript modifies an element's css — the layout is not recalculated immediately.
...for example, code like this will cause an immediate, synchronous, reflow, when it calls window.getcomputedstyle(thing).height: var thing = document.getelementbyid("the-thing"); thing.style.display = "inline-block"; var thingheight = window.getcomputedstyle(thing).height; because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the dom, because every time you read back a style that has been invalidated by a previous write call, you force a synchronous reflow.
AudioParam.setTargetAtTime() - Web APIs
if it is less than or equal to audiocontext.currenttime, the parameter will start changing immediately.
...the decay rate as defined by the timeconstant parameter is exponential; therefore the value will never reach target completely, but after each timestep of length timeconstant, the value will have approached target by another 1-e-1≈63.2%1 - e^{-1} \approx 63.2%.
... if you absolutely need to reach the target value by a specific time, you can use audioparam.exponentialramptovalueattime().
Using dynamic styling information - Web APIs
<html> <head> <title>simple style example</title> <script type="text/javascript"> function alterstyle(elem) { elem.style.background = 'green'; } function resetstyle(elemid) { elem = document.getelementbyid(elemid); elem.style.background = 'white'; } </script> <style type="text/css"> #p1 { border: solid blue 2px; } </style> </head> <body> <!-- passes a reference to the element's object as parameter 'this'.
... more important than the two properties noted here is the use of the style object to set individual style properties on an element: <!doctype html> <html> <head> <title>style property example</title> <link rel="stylesheet" href="example.css" type="text/css"> <script type="text/javascript"> function stilo() { document.getelementbyid('d').style.color = 'orange'; } function resetstyle() { document.getelementbyid('d').style.color = 'black'; } </script> </head> <body> <div id="d" class="thunder">thunder</div> <button onclick="stilo()">click here to change text color</button> <button onclick="resetstyle()">reset text color</button> </body> </html> the media and type of the style may or ...
... var el = document.getelementbyid('some-element'); el.setattribute('style', 'background-color:darkblue;'); be aware, however, that setattribute removes all other style properties that may already have been defined in the element's style object.
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
here we have a whitelist containing the names of the caches we want to keep (cachewhitelist).
... we return the keys of the caches in the cachestorage object using keys(), then check each key to see if it is in the whitelist.
... then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.keys().then(function(keylist) { return promise.all(keylist.map(function(key) { if (cachewhitelist.indexof(key) === -1) { return caches.delete(key); } }); }) ); }); specifications specification status comment service workersthe definition of 'cachestorage: keys' in that specification.
CanvasRenderingContext2D.globalAlpha - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.globalalpha = 0.5; ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); ctx.fillstyle = 'red'; ctx.fillrect(50, 50, 100, 100); result overlaying transparent shapes this example illustrates the effect of overlaying multiple transparent shapes on top of each other.
...if we were to increase the step count (and thus draw more circles), the background would eventually disappear completely from the center of the image.
... <canvas id="canvas" width="150" height="150"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw background ctx.fillstyle = '#fd0'; ctx.fillrect(0, 0, 75, 75); ctx.fillstyle = '#6c0'; ctx.fillrect(75, 0, 75, 75); ctx.fillstyle = '#09f'; ctx.fillrect(0, 75, 75, 75); ctx.fillstyle = '#f30'; ctx.fillrect(75, 75, 75, 75); ctx.fillstyle = '#fff'; // set transparency value ctx.globalalpha = 0.2; // draw transparent circles for (let i = 0; i < 7; i++) { ctx.beginpath(); ctx.arc(75, 75, 10 + 10 * i, 0, math.pi * 2, true); ctx.fill(); } screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.globalalpha' in that specification.
CanvasRenderingContext2D.lineCap - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(20, 20); ctx.linewidth = 15; ctx.linecap = 'round'; ctx.lineto(100, 100); ctx.stroke(); result comparison of line caps in this example three lines are drawn, each with a different value for the linecap property.
...it's drawn completely flush with the guides.
... <canvas id="canvas" width="150" height="150"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const linecap = ['butt', 'round', 'square']; // draw guides ctx.strokestyle = '#09f'; ctx.beginpath(); ctx.moveto(10, 10); ctx.lineto(140, 10); ctx.moveto(10, 140); ctx.lineto(140, 140); ctx.stroke(); // draw lines ctx.strokestyle = 'black'; for (let i = 0; i < linecap.length; i++) { ctx.linewidth = 15; ctx.linecap = linecap[i]; ctx.beginpath(); ctx.moveto(25 + i * 50, 10); ctx.lineto(25 +...
CanvasRenderingContext2D.setLineDash() - Web APIs
syntax ctx.setlinedash(segments); parameters segments an array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units).
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // dashed line ctx.beginpath(); ctx.setlinedash([5, 15]); ctx.moveto(0, 50); ctx.lineto(300, 50); ctx.stroke(); // solid line ctx.beginpath(); ctx.setlinedash([]); ctx.moveto(0, 100); ctx.lineto(300, 100); ctx.stroke(); result some common patterns this example illustrates a variety of common line dash patterns.
... function drawdashedline(pattern) { ctx.beginpath(); ctx.setlinedash(pattern); ctx.moveto(0, y); ctx.lineto(300, y); ctx.stroke(); y += 20; } const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let y = 15; drawdashedline([]); drawdashedline([1, 1]); drawdashedline([10, 10]); drawdashedline([20, 5]); drawdashedline([15, 3, 3, 3]); drawdashedline([20, 3, 3, 3, 3, 3, 3, 3]); drawdashedline([12, 3, 3]); // equals [12, 3, 3, 12, 3, 3] result specifications specification status comment html living standardthe definition of '...
CanvasRenderingContext2D.shadowColor - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowoffsetx = 10; ctx.shadowoffsety = 10; // filled rectangle ctx.fillrect(20, 20, 100, 100); // stroked rectangle ctx.linewidth = 6; ctx.strokerect(170, 20, 100, 100); result shadows on translucent shapes a shadow's opacity is affected by the transparency level of its parent object (even wh...
...en shadowcolor specifies a completely opaque value).
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'rgba(255, 0, 0, .8)'; ctx.shadowblur = 8; ctx.shadowoffsetx = 30; ctx.shadowoffsety = 20; // filled rectangle ctx.fillstyle = 'rgba(0, 255, 0, .2)'; ctx.fillrect(10, 10, 150, 100); // stroked rectangle ctx.linewidth = 10; ctx.strokestyle = 'rgba(0, 0, 255, .6)'; ctx.strokerect(10, 10, 150, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowc...
CanvasRenderingContext2D.stroke() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); result re-stroking paths typically, you'll want to call beginpath() for each new thing you want to stroke.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // first sub-path ctx.linewidth = 26; ctx.strokestyle = 'orange'; ctx.moveto(20, 20); ctx.lineto(160, 20); ctx.stroke(); // second sub-path ctx.linewidth = 14; ctx.strokestyle = 'green'; ctx.moveto(20, 80); ctx.lineto(220, 80); ctx.stroke(); // third sub-path ctx.linewidth = 4; ctx.strokestyle = 'pink'; ctx.moveto(20, 140); ctx.lineto(280, 140); ctx.stroke(); result...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 16; ctx.strokestyle = 'red'; // stroke on top of fill ctx.beginpath(); ctx.rect(25, 25, 100, 100); ctx.fill(); ctx.stroke(); // fill on top of stroke ctx.beginpath(); ctx.rect(175, 25, 100, 100); ctx.stroke(); ctx.fill(); result specifications specification status comment html living standardthe definition of 'canvasrend...
CanvasRenderingContext2D - Web APIs
basic example to get a canvasrenderingcontext2d instance, you must first have an html <canvas> element to work with: <canvas id="my-house" width="300" height="300"></canvas> to get the canvas' 2d rendering context, call getcontext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getelementbyid('my-house'); const ctx = canvas.getcontext('2d'); with the context in hand, you can draw anything you like.
... this code draws a house: // set line width ctx.linewidth = 10; // wall ctx.strokerect(75, 140, 150, 110); // door ctx.fillrect(130, 190, 40, 60); // roof ctx.beginpath(); ctx.moveto(50, 140); ctx.lineto(150, 60); ctx.lineto(250, 140); ctx.closepath(); ctx.stroke(); the resulting drawing looks like this: reference drawing rectangles there are three methods that immediately draw rectangles to the canvas.
... gradients and patterns canvasrenderingcontext2d.createlineargradient() creates a linear gradient along the line given by the coordinates represented by the parameters.
Constraint validation API - Web APIs
you should not rely on it to completely sanitize data received by the server.
... extensions to other interfaces the constraint validation api extends the interfaces for the form-associated elements listed below with a number of new properties and methods (elements that can have a form attribute that indicates their form owner): htmlbuttonelement htmlfieldsetelement htmlinputelement htmlobjectelement htmloutputelement htmlselectelement htmltextareaelement properties validity a read-only property that returns a validitystate object, whose properties represent validation errors for the value of that element.
...elements with the htmlobjectelement interface are never candidates for constraint validation.
Content Index API - Web APIs
content indexing allows developers to tell the browser about their specific offline content.
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const ...
...listelem = document.createelement('ul'); for (const entry of entries) { const listitem = document.createelement('li'); const anchorelem = document.createelement('a'); anchorelem.innertext = entry.title; anchorelem.setattribute('href', entry.url); listelem.append(listitem); } readinglistelem.append(listelem); } } unregistering indexed content below is an asynchronous function, that removes an item from the content index.
Document.createElement() - Web APIs
addelement; function addelement () { // create a new div element const newdiv = document.createelement("div"); // and give it some content const newcontent = document.createtextnode("hi there and greetings!"); // add the text node to the newly created div newdiv.appendchild(newcontent); // add the newly created element and its content into the dom const currentdiv = document.getelementbyid("div1"); document.body.insertbefore(newdiv, currentdiv); } web component example the following example snippet is taken from our expanding-list-web-component example (see it live also).
... in this case, our custom element extends the htmlulistelement, which represents the <ul> element.
... // create a class for the element class expandinglist extends htmlulistelement { constructor() { // always call super first in constructor super(); // constructor definition left out for brevity ...
Document Object Model (DOM) - Web APIs
transformelement svgcircleelement svgclippathelement svgcolorprofileelement svgcomponenttransferfunctionelement svgcursorelement svgdefselement svgdescelement svgelement svgellipseelement svgfeblendelement svgfecolormatrixelement svgfecomponenttransferelement svgfecompositeelement svgfeconvolvematrixelement svgfediffuselightingelement svgfedisplacementmapelement svgfedistantlightelement svgfedropshadowelement svgfefloodelement svgfefuncaelement svgfefuncbelement svgfefuncgelement svgfefuncrelement svgfegaussianblurelement svgfeimageelement svgfemergeelement svgfemergenodeelement svgfemorphologyelement svgfeoffsetelement svgfepointlightelement svgfespecularlightingelement svgfespotlightelement svgfetileelement svgfeturbulenceelement svgfilterelement svgfil...
...terprimitivestandardattributes svgfontelement svgfontfaceelement svgfontfaceformatelement svgfontfacenameelement svgfontfacesrcelement svgfontfaceurielement svgforeignobjectelement svggelement svggeometryelement svgglyphelement svgglyphrefelement svggradientelement svggraphicselement svghatchelement svghatchpathelement svghkernelement svgimageelement svglineargradientelement svglineelement svgmarkerelement svgmaskelement svgmeshelement svgmeshgradientelement svgmeshpatchelement svgmeshrowelement svgmetadataelement svgmissingglyphelement svgmpathelement svgpathelement svgpatternelement svgpolylineelement svgpolygonelement svgradialgradientelement svgrectelement svgscriptelement svgsetelement svgsolidcolorelement svgstope...
...lement svgstyleelement svgsvgelement svgswitchelement svgsymbolelement svgtextcontentelement svgtextelement svgtextpathelement svgtextpositioningelement svgtitleelement svgtrefelement svgtspanelement svguseelement svgunknownelement svgviewelement svgvkernelement svg data type interfaces here are the dom apis for data types used in the definitions of svg properties and attributes.
EffectTiming.iterations - Web APIs
the default value is 1, indicating that it should only play once, but you can set it to any floating-point value (including positive infinity defaults to 1, and can also take a value of infinity to make it loop infinitely.
...any value from 0 (don't play the animation at all) to positive infinity (run the animation indefinitely) is supported.
... examples in the forgotten key example, alice waves her arm up and down the entire time the page is open by passing infinity as the value for her iterations property: // get alice's arm, and wave it up and down document.getelementbyid("alice_arm").animate([ { transform: 'rotate(10deg)' }, { transform: 'rotate(-40deg)' } ], { easing: 'steps(2, end)', iterations: infinity, direction: 'alternate', duration: 600 }); specifications specification status comment web animationsthe definition of 'iterations' in that specification.
Element: compositionend event - Web APIs
bubbles yes cancelable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionend', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="examp...
...clear</button> </div> css 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.queryselector('input[type="text"]'); const log = document.queryselector('.event-log-contents'); const clearlog = document.queryselector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', ...
...handleevent); inputelement.addeventlistener('compositionupdate', handleevent); inputelement.addeventlistener('compositionend', handleevent); result specifications specification status ui events working draft ...
Element: compositionstart event - Web APIs
bubbles yes cancelable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionstart', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="exa...
...clear</button> </div> css 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.queryselector('input[type="text"]'); const log = document.queryselector('.event-log-contents'); const clearlog = document.queryselector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', ...
...handleevent); inputelement.addeventlistener('compositionupdate', handleevent); inputelement.addeventlistener('compositionend', handleevent); result specifications specification status ui events working draft ...
Element: compositionupdate event - Web APIs
bubbles yes cancelable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionupdate', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="ex...
...clear</button> </div> css 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.queryselector('input[type="text"]'); const log = document.queryselector('.event-log-contents'); const clearlog = document.queryselector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', ...
...handleevent); inputelement.addeventlistener('compositionupdate', handleevent); inputelement.addeventlistener('compositionend', handleevent); result specifications specification status ui events working draft ...
Element.getBoundingClientRect() - Web APIs
empty border-boxes are completely ignored.
...scripts without access to these properties can use code like this: // for scrollx (((t = document.documentelement) || (t = document.body.parentnode)) && typeof t.scrollleft == 'number' ?
... t : document.body).scrollleft // for scrolly (((t = document.documentelement) || (t = document.body.parentnode)) && typeof t.scrolltop == 'number' ?
Element.getClientRects() - Web APIs
function addclientrectsoverlay(elt) { /* absolutely position a div over each client rect so that its border width is the same as the rectangle's width.
...*/ var rects = elt.getclientrects(); for (var i = 0; i != rects.length; i++) { var rect = rects[i]; var tablerectdiv = document.createelement('div'); tablerectdiv.style.position = 'absolute'; tablerectdiv.style.border = '1px solid red'; var scrolltop = document.documentelement.scrolltop || document.body.scrolltop; var scrollleft = document.documentelement.scrollleft || document.body.scrollleft; tablerectdiv.style.margin = tablerectdiv.style.padding = '0'; tablerectdiv.style.top = (rect.top + scrolltop) + 'px'; tablerectdiv.style.left = (rect.left + scrollleft) + 'px'; // we want rect.width to be the border width, so content width is 2px less.
... tablerectdiv.style.width = (rect.width - 2) + 'px'; tablerectdiv.style.height = (rect.height - 2) + 'px'; document.body.appendchild(tablerectdiv); } } (function() { /* call function addclientrectsoverlay(elt) for all elements with assigned class "withclientrectsoverlay" */ var elt = document.getelementsbyclassname('withclientrectsoverlay'); for (var i = 0; i < elt.length; i++) { addclientrectsoverlay(elt[i]); } })(); result specifications specification status comment css object model (cssom) view modulethe definition of 'element.getclientrects()' in that specification.
Element.hasPointerCapture() - Web APIs
syntax targetelement.haspointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object.
... examples <html> <script> function downhandler(ev) { const el = document.getelementbyid("target"); // element 'target' will receive/capture further events el.setpointercapture(ev.pointerid); /* ...
... } } function init() { const el = document.getelementbyid("target"); el.onpointerdown = downhandler; } </script> <body onload="init();"> <div id="target">touch this element with a pointer.</div> </body> </html> specifications specification status comment pointer events – level 2the definition of 'haspointercapture()' in that specification.
Element.outerHTML - Web APIs
WebAPIElementouterHTML
nomodificationallowederror an attempt was made to set outerhtml on an element which is a direct child of a document, such as document.documentelement.
... examples getting the value of an element's outerhtml property: html <div id="d"> <p>content</p> <p>further elaborated</p> </div> javascript var d = document.getelementbyid("d"); console.log(d.outerhtml); // the string '<div id="d"><p>content</p><p>further elaborated</p></div>' // is written to the console window replacing a node by setting the outerhtml property: html <div id="container"> <div id="d">this is a div.</div> </div> javascript var container = document.getelementbyid("container"); var d = document.getelementbyid("d"); console.log(container.firstchild.nodename); // logs "div" d.outerhtml = "<p>this paragraph replaced the original div.</p>"; console.log(container.firstchild.nodename); // logs "p" // the #d div is no longer part of the document tree, // the ne...
...for example: var div = document.createelement("div"); div.outerhtml = "<div class=\"test\">test</div>"; console.log(div.outerhtml); // output: "<div></div>" also, while the element will be replaced in the document, the variable whose outerhtml property was set will still hold a reference to the original element: var p = document.getelementsbytagname("p")[0]; console.log(p.nodename); // shows: "p" p.outerhtml = "<div>this div replaced a paragraph.</div>"; console.log(p.nodename); // still "p"; the returned value will contain html escaped attributes: var anc = document.createelement("a"); anc.href = "https://developer.mozilla.org?a=b&c=d"; console.log(anc.outerhtml); // output: "<a href='https://developer.mozilla.org?a=b&amp;...
Element.scrollHeight - Web APIs
quisque sit amet tellus et enim bibendum varius et a orci.
...us: 5px; width: 600px; padding: 5px; border: 2px #7fdf55 solid; } #rules { width: 600px; height: 130px; padding: 5px; border: #2a9f00 solid 2px; border-radius: 5px; } javascript function checkreading () { if (checkreading.read) { return; } checkreading.read = this.scrollheight - this.scrolltop === this.clientheight; document.registration.accept.disabled = document.getelementbyid("nextstep").disabled = !checkreading.read; checkreading.noticebox.innerhtml = checkreading.read ?
... "thank you." : "please, scroll and read the following text."; } onload = function () { var otoberead = document.getelementbyid("rules"); checkreading.noticebox = document.createelement("span"); document.registration.accept.checked = false; checkreading.noticebox.id = "notice"; otoberead.parentnode.insertbefore(checkreading.noticebox, otoberead); otoberead.parentnode.insertbefore(document.createelement("br"), otoberead); otoberead.onscroll = checkreading; checkreading.call(otoberead); } specifications specification status comment css object model (cssom) view modulethe definition of 'element.scrollheight' in that specification.
Event.preventDefault() - Web APIs
the event interface's preventdefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
...this example demonstrates how to prevent that from happening: javascript document.queryselector("#id-checkbox").addeventlistener("click", function(event) { document.getelementbyid("output-box").innerhtml += "sorry!
...first, listen for keypress events: var mytextbox = document.getelementbyid('my-textbox'); mytextbox.addeventlistener('keypress', checkname, false); the checkname() function, which looks at the pressed key and decides whether to allow it: function checkname(evt) { var charcode = evt.charcode; if (charcode != 0) { if (charcode < 97 || charcode > 122) { evt.preventdefault(); displaywarning( "please use lowercase letters only." ...
ExtendableEvent.waitUntil() - Web APIs
the extendableevent.waituntil() method tells the event dispatcher that work is ongoing.
...in service workers, waituntil() tells the browser that work is ongoing until the promise settles, and it shouldn't terminate the service worker if it wants that work to complete.
...this gives the service worker time to update database schemas and delete outdated caches, so other events can rely on a completely upgraded state.
Using Fetch - Web APIs
a headers object is a simple multi-map of names to values: const content = 'hello world'; const myheaders = new headers(); myheaders.append('content-type', 'text/plain'); myheaders.append('content-length', content.length.tostring()); myheaders.append('x-custom-header', 'processthisimmediately'); the same can be achieved by passing an array of arrays or an object literal to the constructor: const myheaders = new headers({ 'content-type': 'text/plain', 'content-length': content.length.tostring(), 'x-custom-header': 'processthisimmediately' }); the contents can be queried and retrieved: console.log(myheaders.has('content-type')); // true console.log(myheaders.has('set-cookie...
...')); // false myheaders.set('content-type', 'text/html'); myheaders.append('x-custom-header', 'anothervalue'); console.log(myheaders.get('content-length')); // 11 console.log(myheaders.get('x-custom-header')); // ['processthisimmediately', 'anothervalue'] myheaders.delete('x-custom-header'); console.log(myheaders.get('x-custom-header')); // [ ] some of these operations are only useful in serviceworkers, but they provide a much nicer api for manipulating headers.
... request bodies can be set by passing body parameters: const form = new formdata(document.getelementbyid('login-form')); fetch('/login', { method: 'post', body: form }); both request and response (and by extension the fetch() function), will try to intelligently determine the content type.
File and Directory Entries API - Web APIs
only for accessing files which are selected by the user in a file <input> element (see htmlinputelement as well) or when a file or directory is provided to the web site or app using drag and drop.
... the htmlinputelement.webkitentries property lets you access the filesystemfileentry objects for the currently selected files, but only if they are dragged-and-dropped onto the file chooser (bug 1326031).
... if htmlinputelement.webkitdirectory is true, the <input> element is instead a directory picker, and you get filesystemdirectoryentry objects for each selected directory.
GlobalEventHandlers.ondragend - Web APIs
syntax var dragendhandler = targetelement.ondragend; return value dragendhandler the dragend event handler for element targetelement.
...data("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's border to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragenter_handler(ev) { console.log("dragenter"); // change the source element's background color for enter events ev.currenttarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.l...
... var el=document.getelementbyid("target"); el.style.background = "pink"; } function dragexit_handler(ev) { console.log("dragexit"); // change the source element's border back to green to signify a dragexit event ev.currenttarget.style.background = "green"; } function init() { // set handlers for the source's enter/leave/end/exit events var el=document.getelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <...
GlobalEventHandlers.ondragenter - Web APIs
syntax var dragenterhandler = targetelement.ondragenter; return value dragenterhandler the dragenter event handler for element targetelement.
...data("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's border to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragenter_handler(ev) { console.log("dragenter"); // change the source element's background color for enter events ev.currenttarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.l...
... var el=document.getelementbyid("target"); el.style.background = "pink"; } function dragexit_handler(ev) { console.log("dragexit"); // change the source element's border back to green to signify a dragexit event ev.currenttarget.style.background = "green"; } function init() { // set handlers for the source's enter/leave/end/exit events var el=document.getelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <...
GlobalEventHandlers.ondragexit - Web APIs
syntax var dragexithandler = targetelement.ondragexit; return value dragexithandler the dragexit event handler for element targetelement.
...data("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's border to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragenter_handler(ev) { console.log("dragenter"); // change the source element's background color for enter events ev.currenttarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragleave"); // change the source element's border back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { console.l...
... var el=document.getelementbyid("target"); el.style.background = "pink"; } function dragexit_handler(ev) { console.log("dragexit"); // change the source element's border back to green to signify a dragexit event ev.currenttarget.style.background = "green"; } function init() { // set handlers for the source's enter/leave/end/exit events var el=document.getelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <...
GlobalEventHandlers.ondragleave - Web APIs
syntax var dragleavehandler = targetelement.ondragleave; return value dragleavehandler the dragleave event handler for element targetelement.
...", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's background color to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragenter_handler(ev) { console.log("dragenter"); // change the source element's background color for enter events ev.currenttarget.style.background = "yellow"; } function dragleave_handler(ev) { console.log("dragleave"); // change the source element's background color back to white ev.currenttarget.style.background = "white"; } function dragend_handler(ev) { ...
... var el=document.getelementbyid("target"); el.style.background = "pink"; } function dragexit_handler(ev) { console.log("dragexit"); // change the source element's background color back to green to signify a dragexit event ev.currenttarget.style.background = "green"; } function init() { // set handlers for the source's enter/leave/end/exit events var el=document.getelementbyid("source"); el.ondragenter = dragenter_handler; el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</co...
HTMLCanvasElement.toBlob() - Web APIs
var canvas = document.getelementbyid('canvas'); canvas.toblob(function(blob) { var newimg = document.createelement('img'), url = url.createobjecturl(blob); newimg.onload = function() { // no longer need to read the blob so it's revoked url.revokeobjecturl(url); }; newimg.src = url; document.body.appendchild(newimg); }); note that here we're creating a png image; if you add a second parameter to ...
... var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconname) { return function(b) { var a = document.createelement('a'); a.textcontent = 'download'; document.body.appendchild(a); a.style.display = 'block'; ...
... var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconname) { return function(b) { var r = new filereader(); r.onloadend = function () { // r.result contains the arraybuffer.
HTMLImageElement.complete - Web APIs
the read-only htmlimageelement interface's complete attribute is a boolean value which indicates whether or not the image has completely loaded.
... syntax let doneloading = htmlimageelement.complete; value a boolean value which is true if the image has completely loaded; otherwise, the value is false.
... the image is considered completely loaded if any of the following are true: neither the src nor the srcset attribute is specified.
HTMLMediaElement.play() - Web APIs
usage notes although the term "autoplay" is usually thought of as referring to pages that immediately begin playing media upon being loaded, web browsers' autoplay policies also apply to any script-initiated playback of media, including calls to play().
... if the user agent is configured not to allow automatic or script-initiated playback of media, calling play() will cause the returned promise to be immediately rejected with a notallowederror.
... example this example demonstrates how to confirm that playback has begun and how to gracefully handle blocked automatic playback: let videoelem = document.getelementbyid("video"); let playbutton = document.getelementbyid("playbutton"); playbutton.addeventlistener("click", handleplaybutton, false); playvideo(); async function playvideo() { try { await videoelem.play(); playbutton.classlist.add("playing"); } catch(err) { playbutton.classlist.remove("playing"); } } function handleplaybutton() { if (videoelem.paused) { playvideo();...
HTMLTableElement.insertRow() - Web APIs
to insert the row into a specific <tbody>: let specific_tbody = document.getelementbyid(tbody_id); let row = specific_tbody.insertrow(index) note: insertrow() inserts the row directly into the table.
... the row does not need to be appended separately as would be the case if document.createelement() had been used to create the new <tr> element.
... html <table id="my-table"> <tr><td>row 1</td></tr> <tr><td>row 2</td></tr> <tr><td>row 3</td></tr> </table> javascript function addrow(tableid) { // get a reference to the table let tableref = document.getelementbyid(tableid); // insert a row at the end of the table let newrow = tableref.insertrow(-1); // insert a cell in the row at index 0 let newcell = newrow.insertcell(0); // append a text node to the cell let newtext = document.createtextnode('new bottom row'); newcell.appendchild(newtext); } // call addrow() with the table's id addrow('my-table'); result specifications ...
HTML Drag and Drop API - Web APIs
res adding the draggable attribute and the ondragstart global event handler, as shown in the following code sample: <script> function dragstart_handler(ev) { // add the target element's id to the data transfer object ev.datatransfer.setdata("text/plain", ev.target.id); } window.addeventlistener('domcontentloaded', () => { // get the element by id const element = document.getelementbyid("p1"); // add the ondragstart event listener element.addeventlistener("dragstart", dragstart_handler); }); </script> <p id="p1" draggable="true">this element is draggable.</p> for more information, see: draggable attribute reference drag operations guide define the drag's data the application is free to include any number of data items in a drag operation.
... <script> function dragover_handler(ev) { ev.preventdefault(); ev.datatransfer.dropeffect = "move"; } function drop_handler(ev) { ev.preventdefault(); // get the id of the target and add the moved element to the target's dom const data = ev.datatransfer.getdata("text/plain"); ev.target.appendchild(document.getelementbyid(data)); } </script> <p id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">drop zone</p> note that each handler calls preventdefault() to prevent additional event processing for this event (such as touch events or pointer events).
...r.setdata("application/my-app", ev.target.id); ev.datatransfer.dropeffect = "move"; } function dragover_handler(ev) { ev.preventdefault(); ev.datatransfer.dropeffect = "move" } function drop_handler(ev) { ev.preventdefault(); // get the id of the target and add the moved element to the target's dom const data = ev.datatransfer.getdata("application/my-app"); ev.target.appendchild(document.getelementbyid(data)); } </script> <p id="p1" draggable="true" ondragstart="dragstart_handler(event)">this element is draggable.</p> <div id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">drop zone</div> for more information, see: performing a drop drag end at the end of a drag operation, the dragend event fires at the source element — the element that was the tar...
Using IndexedDB - Web APIs
the request here was generated with a call to indexeddb.open(), so request.result is an instance of idbdatabase, and you definitely want to save that for later.
... the behavior described above is new, and is only available as of the following browser releases: firefox 50, google chrome 31 (approximately).
...actionfailure("invalid key"); return; } key = number(key); deletepublication(key); } }); $('#clear-store-button').click(function(evt) { clearobjectstore(); }); var search_button = $('#search-list-button'); search_button.click(function(evt) { displaypublist(); }); } opendb(); addeventlisteners(); })(); // immediately-invoked function expression (iife) test the online live demo note: window.indexeddb.open() is asynchronous; the method will finish running long before the success event is fired.
Intersection Observer API - Web APIs
one thing the intersection observer api can't tell you: the exact number of pixels that overlap or specifically which ones they are; however, it covers the much more common use case of "if they intersect by somewhere around n%, i need to do something." intersection observer concepts and usage the intersection observer api allows you to configure a callback that is called: (1) whenever one element, called the target, intersects either the devi...
...id; wrapper.appendchild(document.importnode(template, true)); // set up the observer for this box observeroptions.threshold = thresholdsets[i]; observers[i] = new intersectionobserver(intersectioncallback, observeroptions); observers[i].observe(document.queryselector("#" + boxid)); } // scroll to the starting position document.scrollingelement.scrolltop = wrapper.firstelementchild.getboundingclientrect().top + window.scrolly; document.scrollingelement.scrollleft = 750; } intersectioncallback = (entries) => { entries.foreach((entry) => { let box = entry.target; let visiblepct = (math.floor(entry.intersectionratio * 100)) + "%"; box.queryselector(".topleft").innerhtml = visiblepct; box.queryselector(".topright").innerhtml = visiblepct; box...
...for a threshold value of 0.0 (default) the callback is called approximately upon transition of the boolean value of isintersecting.
MediaStreamConstraints.audio - Web APIs
this tells getusermedia() that we require an audio track, but we don't care about any specifics beyond that.
...css content body { font: 14px "open sans", "arial", sans-serif; } audio { margin-top: 20px; border: 1px solid black; width: 160px; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let audioelement = document.getelementbyid("audio"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ audio: true }).then(stream => audioelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see ...
...css content body { font: 14px "open sans", "arial", sans-serif; } audio { margin-top: 20px; border: 1px solid black; width: 160px; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let audioelement = document.getelementbyid("audio"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ audio: { samplesize: 8, echocancellation: true } }).then(stream => audioelement.srcobject = stream) .catch(err => log(err.
MediaStreamConstraints.video - Web APIs
this tells getusermedia() that we require a video track, but we don't care about any specifics beyond that.
...d="log"></div> css content body { font: 14px "open sans", "arial", sans-serif; } video { margin-top: 20px; border: 1px solid black; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: true }).then(stream => videoelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we se...
...d="log"></div> css content body { font: 14px "open sans", "arial", sans-serif; } video { margin-top: 20px; border: 1px solid black; } .button { cursor: pointer; width: 160px; border: 1px solid black; font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: { width: 160, height: 120, framerate: 15 } }).then(stream => videoelement.srcobject = stream) .catc...
Node.nextSibling - Web APIs
WebAPINodenextSibling
the node.nextsibling read-only property returns the node immediately following the specified one in their parent's childnodes, or returns null if the specified node is the last child in the parent element.
... element.nextelementsibling may be used to obtain the next element skipping any whitespace nodes, other between-element text, or comments.
... example <div id="div-1">here is div-1</div> <div id="div-2">here is div-2</div> <script> var el = document.getelementbyid('div-1').nextsibling, i = 1; console.group('siblings of div-1:'); while (el) { console.log(i, '.
Node.removeChild() - Web APIs
WebAPINoderemoveChild
in the second syntax form, however, there is no oldchild reference kept, so assuming your code has not kept any other reference to the node elsewhere, it will immediately become unusable and irretrievable, and will usually be automatically deleted from memory after a short time.
... examples simple examples given this html: <div id="top"> <div id="nested"></div> </div> to remove a specified element when knowing its parent node: let d = document.getelementbyid("top"); let d_nested = document.getelementbyid("nested"); let throwawaynode = d.removechild(d_nested); to remove a specified element without having to specify its parent node: let node = document.getelementbyid("nested"); if (node.parentnode) { node.parentnode.removechild(node); } to remove all children from an element: let element = document.getelementbyid("top"); while (element...
....firstchild) { element.removechild(element.firstchild); } causing a typeerror <!--sample html code--> <div id="top"> </div> <script type="text/javascript"> let top = document.getelementbyid("top"); let nested = document.getelementbyid("nested"); // throws uncaught typeerror let garbage = top.removechild(nested); </script> causing a notfounderror <!--sample html code--> <div id="top"> <div id="nested"></div> </div> <script type="text/javascript"> let top = document.getelementbyid("top"); let nested = document.getelementbyid("nested"); // this first call correctly removes the node let garbage = top.removechild(nested); // throws uncaught notfounderror garbage = top.removechild(nested); </script> specifications specification status comment ...
Node.textContent - Web APIs
WebAPINodetextContent
note: to get all of the text and cdata data for the whole document, one could use document.documentelement.textcontent.
...you can use textcontent to get the element's text content: let text = document.getelementbyid('diva').textcontent; // the text variable is now: 'this is some text!' ...
... or set the element's text content: document.getelementbyid('diva').textcontent = 'this text is different!'; // the html for diva is now: // <div id="diva">this text is different!</div> specifications specification status comment domthe definition of 'node.textcontent' in that specification.
NonDocumentTypeChildNode.previousElementSibling - Web APIs
the nondocumenttypechildnode.previouselementsibling read-only property returns the element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list.
... syntax prevnode = elementnodereference.previouselementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <li>this is a list item</li> <li>this is another list item</li> <div id="div-03">here is div-03</div> <script> let el = document.getelementbyid('div-03').previouselementsibling; document.write('<p>siblings of div-03</p><ol>'); while (el) { document.write('<li>' + el.nodename + '</li>'); el = el.previouselementsibling; } document.write('</ol>'); </script> this example outputs the following into the page when it loads: siblings of div-03 1.
...div polyfills polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can be used to add support to ie8: // source: https://github.com/alhadis/snippets/blob/master/js/polyfills/ie8-child-elements.js if(!("previouselementsibling" in document.documentelement)){ object.defineproperty(element.prototype, "previouselementsibling", { get: function(){ var e = this.previoussibling; while(e && 1 !== e.nodetype) e = e.previoussibling; return e; } }); } polyfill for internet explorer 9+ and safari // source: https://github.com/jserz/js_piece/blob/master/dom/nondocumenttypechildnode/previouselementsibling/previouselementsibling.md (function (arr) { arr.foreach(function (item) { if (...
NonDocumentTypeChildNode - Web APIs
nondocumenttypechildnode.previouselementsibling read only returns the element immediately prior to this node in its parent's children list, or null if there is no element in the list prior to this node.
... nondocumenttypechildnode.nextelementsibling read only returns the element immediately following this node in its parent's children list, or null if there is no element in the list following this node.
...the previouselementsibling and nextelementsibling are now defined on the latter.
ParentNode - Web APIs
parentnode.firstelementchild read only returns the first node which is both a child of this parentnode and is also an element, or null if there is none.
... parentnode.lastelementchild read only returns the last node which is both a child of this parentnode and is an element, or null if there is none.
...the parentnode.firstelementchild, parentnode.lastelementchild, and parentnode.childelementcount properties are now defined on the latter.
PerformanceResourceTiming.fetchStart - Web APIs
the fetchstart read-only property represents a timestamp immediately before the browser starts to fetch the resource.
... if there are http redirects the property returns the time immediately before the user agent starts to fetch the final resource in the redirection.
... syntax resource.fetchstart; return value a domhighrestimestamp immediately before the browser starts to fetch the resource.
PerformanceResourceTiming.redirectEnd - Web APIs
the redirectend read-only property returns a timestamp immediately after receiving the last byte of the response of the last redirect.
... when fetching a resource, if there are multiple http redirects, and any of the redirects have an origin that is different from the current document, and the timing allow check algorithm passes for each redirected resource, this property returns the time immediately after receiving the last byte of the response of the last redirect; otherwise, zero is returned.
... syntax resource.redirectend; return value a timestamp immediately after receiving the last byte of the response of the last redirect.
RTCConfiguration - Web APIs
otherwise, both the rtp and rtcp candidates are returned, separately.
... "require" tells the ice agent to gather ice candidates for only rtp, and to multiplex rtcp atop them.
...one obvious benefit to providing your own is identity key continuity—if you use the same certificate for subsequent calls, the remote peer can tell you're the same caller.
RTCDTMFSender.toneBuffer - Web APIs
dtmf tone characters the digits 0-9 these characters represent the digit keys on a telephone keypad.
... the letters a-d these characters represent the "a" through "d" keys which are part of the dtmf standard but not included on most telephones.
... the pound/hash sign ("#") and the asterisk ("*") these correspond to the similarly-labeled keys which are typically on the bottom row of the telephone keypad.
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
tone characters the digits 0-9 these characters represent the digit keys on a telephone keypad.
... the letters a-d these characters represent the "a" through "d" keys which are part of the dtmf standard but not included on most telephones.
... the pound/hash sign ("#") and the asterisk ("*") these correspond to the similarly-labeled keys which are typically on the bottom row of the telephone keypad.
RTCPeerConnection.onaddstream - Web APIs
the event is sent immediately after the call setremotedescription() and doesn't wait for the result of the sdp negotiation.
...the first time an event occurs may be nearly immediately after the remote end of the connection is set using rtcpeerconnection.setremotedescription(); it doesn't wait for a particular stream to be accepted or rejected using sdp negotiation.
... pc.onaddstream = function(event) { document.getelementbyid("received_video").srcobject = event.stream; document.getelementbyid("hangup-button").disabled = false; }; you can also use addeventlistener() to add a handler for addstream events to an rtcpeerconnection.
RTCPeerConnection.setRemoteDescription() - Web APIs
because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by calling setremotedescription() does not immediately take effect.
... function handleoffer(msg) { createmypeerconnection(); mypeerconnection.setremotedescription(msg.description).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(stream) { document.getelementbyid("local_video").srcobject = stream; return mypeerconnection.addstream(stream); }) .then(function() { return mypeerconnection.createanswer(); }) .then(function(answer) { return mypeerconnection.setlocaldescription(answer); }) .then(function() { // send the answer to the remote peer using the signaling server }) .catch(handlegetusermediaerror); } after creat...
...ing our rtcpeerconnection and saving it as mypeerconnection, we pass the description included in the received offer message, msg, directly into setremotedescription() to tell the user agent's webrtc layer what configuration the caller has proposed using.
SVGTextPathElement - Web APIs
roke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggraphicselement</text></a><polyline points="301,89 291,84 291,94 301,89" stroke="#d4dde4" fill="none"/><line x1="291" y1="89" x2="261" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgtextcontentelement" target="_top"><rect x="51" y="65" width="210" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="156" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextcontentelement</text></a><polyline points="51,89 41,84 41,94 51,89" stroke="#d4dde4" fill="none"/><line x1="41" y1="89" ...
... properties this interface also inherits properties from its parent interface, svgtextcontentelement, and also implements properties of svgurireference.
... methods this interface does not provide any specific methods, but implements those of its parent, svgtextcontentelement, and also implements methods of svgurireference.
Storage Access API - Web APIs
as an example, federated logins often require access to authentication cookies stored in first-party storage, and will require the user to sign in on each site separately (or completely break) if those cookies are not available.
...design properties unique to firefox are summarized here: if the embedded origin tracker.example has already obtained first-party storage access on the top-level origin foo.example, and the user visits a page from foo.example embedding a page from tracker.example again in less than 30 days, the embedded origin will have storage access immediately when loading.
... if a page from top-level origin foo.example embeds more than one <iframe> from tracker.example, and one of those <iframe>s uses the storage access api in order to obtain storage access successfully, all other iframes from tracker.example on foo.example top-level origins will immediately gain storage access as well, without needing to call requeststorageaccess() separately.
Streams API concepts - Web APIs
when a stream later in the chain is still busy and isn't yet ready to accept more chunks, it sends a signal backwards through the chain to tell earlier transform streams (or the original source) to slow down delivery as appropriate so that you don't end up with a bottleneck anywhere.
...if it is too low, our readablestream can tell its underlying source to stop sending data, and we backpressure along the stream chain.
... if later on the consumer again wants to receive data, we can use the pull method in the stream creation to tell our underlying source to feed our stream with data.
Using readable streams - Web APIs
the first object can contain up to five members, only the first of which is required: start(controller) — a method that is called once, immediately after the readablestream is constructed.
...bytestreams will be covered separately in a future tutorial, as they are somewhat different in purpose and use case to regular (default) streams.
... if you wanted to completely get rid of the stream and discard any enqueued chunks, you'd use readablestream.cancel() or readablestreamdefaultreader.cancel().
Using writable streams - Web APIs
the second object is optional, and allows you to specify a custom queueing strategy to use for your stream, which takes the form of an instance of bytelengthqueuingstrategy or countqueuingstrategy.
... the first object can contain up to four members, all of which are optional: start(controller) — a method that is called once, immediately after the writablestream is constructed.
... when abort is called, any previously enqueued chunks are just thrown away immediately and then the stream is moved to an errored state.
Multi-touch interaction - Web APIs
function set_handlers(name) { // install event handlers for the given element var el=document.getelementbyid(name); el.ontouchstart = start_handler; el.ontouchmove = move_handler; // use same handler for touchcancel and touchend el.ontouchcancel = end_handler; el.ontouchend = end_handler; } function init() { set_handlers("target1"); set_handlers("target2"); set_handlers("target3"); set_handlers("target4"); } move/pinch/zoom handler this function provides very basic support for 2-to...
...false : true; } function log(name, ev, printtargetids) { var o = document.getelementsbytagname('output')[0]; var s = name + ": touches = " + ev.touches.length + " ; targettouches = " + ev.targettouches.length + " ; changedtouches = " + ev.changedtouches.length; o.innerhtml += s + " "; if (printtargetids) { s = ""; for (var i=0; i < ev.targettouches.length; i++) { s += "...
... id = " + ev.targettouches[i].identifier + " "; } o.innerhtml += s; } } function clearlog(event) { var o = document.getelementsbytagname('output')[0]; o.innerhtml = ""; } related topics and resources pointer events ...
VisualViewport - Web APIs
for an <iframe>, visual viewport metrics like visualviewport.width always correspond to layout viewport metrics like document.documentelement.clientwidth.
... var bottombar = document.getelementbyid('bottombar'); var viewport = window.visualviewport; function resizehandler() { if (viewport.scale > 1.3) bottombar.style.display = "none"; else bottombar.style.display = "block"; } window.visualviewport.addeventlistener('resize', resizehandler); simulating position: device-fixed this example, also taken from the visual viewport readme, shows how to use this api to sim...
... var bottombar = document.getelementbyid('bottombar'); var viewport = window.visualviewport; function viewporthandler() { var layoutviewport = document.getelementbyid('layoutviewport'); // since the bar is position: fixed we need to offset it by the visual // viewport's offset from the layout viewport origin.
A basic 2D WebGL animation example - Web APIs
let uscalingfactor; let uglobalcolor; let urotationvector; let avertexposition; // animation timing let previoustime = 0.0; let degreespersecond = 90.0; initializing the program is handled through a load event handler called startup(): window.addeventlistener("load", startup, false); function startup() { glcanvas = document.getelementbyid("glcanvas"); gl = glcanvas.getcontext("webgl"); const shaderset = [ { type: gl.vertex_shader, id: "vertex-shader" }, { type: gl.fragment_shader, id: "fragment-shader" } ]; shaderprogram = buildshaderprogram(shaderset); aspectratio = glcanvas.width/glcanvas.height; currentrotation = [0, 1]; currentscale = [1.0, aspectratio]; vert...
...the usage hint gl.static_draw is specified, telling webgl that the data will be set only one time and never modified, but will be used repeatedly.
... function compileshader(id, type) { let code = document.getelementbyid(id).firstchild.nodevalue; let shader = gl.createshader(type); gl.shadersource(shader, code); gl.compileshader(shader); if (!gl.getshaderparameter(shader, gl.compile_status)) { console.log(`error compiling ${type === gl.vertex_shader ?
Adding 2D content to a WebGL context - Web APIs
mat4.translate(modelviewmatrix, // destination matrix modelviewmatrix, // matrix to translate [-0.0, 0.0, -6.0]); // amount to translate // tell webgl how to pull out the positions from the position // buffer into the vertexposition attribute.
...e const offset = 0; // how many bytes inside the buffer to start from gl.bindbuffer(gl.array_buffer, buffers.position); gl.vertexattribpointer( programinfo.attriblocations.vertexposition, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexposition); } // tell webgl to use our program when drawing gl.useprogram(programinfo.program); // set the shader uniforms gl.uniformmatrix4fv( programinfo.uniformlocations.projectionmatrix, false, projectionmatrix); gl.uniformmatrix4fv( programinfo.uniformlocations.modelviewmatrix, false, modelviewmatrix); { const offset = 0; const vertexcount = 4; gl.dra...
...after that, we bind the square's vertex buffer to the attribute the shader is using for avertexposition and we tell webgl how to pull the data out of it.
Using DTMF with WebRTC - Web APIs
webrtc currently ignores these payloads; this is because webrtc's dtmf support is primarily intended for use with legacy telephone services that rely on dtmf tones to perform tasks such as: teleconferencing systems menu systems voicemail systems entry of credit card or other payment information passcode entry note: while the dtmf is not sent to the remote peer as audio, browsers may choose to play the corresponding tone to the local user as part of their user experience, since users are typically used to hear...
... if you'd like to know more about how this works, read rfc 3550: rtp: a transport protocol for real-time applications and rfc 4733: rtp payload for dtmf digits, telephony tones, and telephony signals.
... dialing once the connection is open our design requires that when the connection is established, we immediately send the dtmf string.
Inputs and input sources - Web APIs
generally speaking, the selectstart and selectend events tell you when you might want to display something to the user indicating that the primary action is going on.
... the select event, on the other hand, is the event that tells your code that the user has completed the action they want to complete.
...because we are managing the avatar's position as defined by the keyboard and mouse in addition to anything the xr hardware might be doing, we need to maintain that information separately and apply it as a transform before rendering the avatar (or the world from the avatar's point of view).
Using Web Workers - Web APIs
terminating a worker if you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's terminate method: myworker.terminate(); the worker thread is killed immediately.
... listeners[event.data.querymethodlistener].apply(instance, event.data.querymethodarguments); } else { this.defaultlistener.call(instance, event.data); } } } // your custom "queryable" worker var mytask = new queryableworker('my_task.js'); // your custom "listeners" mytask.addlistener('printstuff', function (result) { document.getelementbyid('firstlink').parentnode.appendchild(document.createtextnode('the difference is ' + result + '!')); }); mytask.addlistener('doalert', function (time, unit) { alert('worker waited for ' + time + ' ' + unit + ' :-)'); }); </script> </head> <body> <ul> <li><a id="firstlink" href="javascript:mytask.sendquery('getdifference', 5, 3);">what is the difference between 5 an...
... the html code <!doctype html> <html> <head> <meta charset="utf-8" /> <title>test threads fibonacci</title> </head> <body> <div id="result"></div> <script language="javascript"> var worker = new worker('fibonacci.js'); worker.onmessage = function(event) { document.getelementbyid('result').textcontent = event.data; dump('got: ' + event.data + '\n'); }; worker.onerror = function(error) { dump('worker error: ' + error.message + '\n'); throw error; }; worker.postmessage('5'); </script> </body> </html> the web page creates a div element with the id result , which gets used to display the result, then spawns the worker.
Worker.prototype.postMessage() - Web APIs
ker, msg:', msg); switch (msg.data.atopic) { case 'do_sendmainarrbuff': sendmainarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } myworker.addeventlistener('message', handlemessagefromworker); // ok lets create the buffer and send it var arrbuf = new arraybuffer(8); console.info('arrbuf.bytelength pre transfer:', arrbuf.bytelength); myworker.postmessage( { atopic: 'do_sendworkerarrbuff', abuf: arrbuf // the array buffer that we passed to the transferrable section 3 lines below }, [ arrbuf // the array buffer we created 9 lines above ] ); console.info('arrbuf.bytelength post transfer:', arrbuf.bytelength); worker code self.onmessage = functi...
...on (msg) { switch (msg.data.atopic) { case 'do_sendworkerarrbuff': sendworkerarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } function sendworkerarrbuff(abuf) { console.info('from worker, pre send back abuf.bytelength:', abuf.bytelength); self.postmessage({atopic:'do_sendmainarrbuff', abuf:abuf}, [abuf]); console.info('from worker, post send back abuf.bytelength:', abuf.bytelength); } output logged arrbuf.bytelength pre transfer: 8 bootstrap.js:40 arrbuf.bytelength post transfer: 0 bootstrap.js:42 from worker, pre send back abuf.bytelength: 8 myworker.js:5:2 incoming message from worke...
...} bootstrap.js:20 got back buf in main thread, abuf.bytelength: 8 bootstrap.js:12 from worker, post send back abuf.bytelength: 0 myworker.js:7:2 bytelength goes to 0 as it is transferred.
WritableStream.WritableStream() - Web APIs
underlyingsink can contain the following: start(controller) optional this is a method, called immediately when the object is constructed.
... note: you could define your own custom queuingstrategy, or use an instance of bytelengthqueuingstrategy or countqueuingstrategy for this object value.
... the promise returned by the sink's write() method (line 40) tells the writablestream and its writer when to resolve defaultwriter.ready.
Sending and Receiving Binary Data - Web APIs
var oreq = new xmlhttprequest(); oreq.open("get", "/myfile.png", true); oreq.responsetype = "arraybuffer"; oreq.onload = function (oevent) { var arraybuffer = oreq.response; // note: not oreq.responsetext if (arraybuffer) { var bytearray = new uint8array(arraybuffer); for (var i = 0; i < bytearray.bytelength; i++) { // do something with each byte in the array } } }; oreq.send(null); you can also read a binary file as a blob by setting the string "blob" to the responsetype property.
...this tells the browser not to parse it, and to let the bytes pass through unprocessed.
... var req = new xmlhttprequest(); req.open("post", url, true); // set headers and mime-type appropriately req.setrequestheader("content-length", 741); req.sendasbinary(abody); line 4 sets the content-length header to 741, indicating that the data is 741 bytes long.
XRView - Web APIs
WebAPIXRView
it's computed by inverting then transposing the model view matrix: mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); teleporting an object to programmatically move and/or rotate (often referred to as teleporting) an object, you need to create a new reference space for that object which applies a transform that encapsulates the desired changes.
... the createteleporttransform() function returns the transform needed to move and rotate an object whose current situation is described by the reference space refspace to a new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes.
... vec3.cross(vecx, vecy, cubeorientation); vec3.cross(vecy, cubeorientation, vecx); // now compute the transform that teleports the object to the // specified point and save a copy of it to display to the user // later; otherwise we probably wouldn't need to save mousematrix // at all.
Using the aria-invalid attribute - Accessibility
the aria-invalid attribute is used to indicate that the value entered into an input field does not conform to the format expected by the application.this may include formats such as email addresses or telephone numbers.
... <input name="name" id="name" aria-required="true" aria-invalid="false" onblur="checkvalidity('name', ' ', 'invalid name entered (requires both first and last name)');"/> <br /> <input name="email" id="email" aria-required="true" aria-invalid="false" onblur="checkvalidity('email', '@', 'invalid e-mail address');"/> note that it is not necessary to validate the fields immediately on blur; the application could wait until the form is submitted (though this is not necessarily recommended).
... the snippet below shows a very simple validation function, which only checks for the presence of a particular character (in the real world, validation will likely be more sophisticated): function checkvalidity(aid, asearchterm, amsg){ var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (invalid) { elem.setattribute("aria-invalid", "true"); updatealert(amsg); } else { elem.setattribute("aria-invalid", "false"); updatealert(); } } the snippet below shows the alert functions, which add (or remove) the error message: function updatealert(msg) { var oldalert = document.getelementbyid("alert"); if (oldalert) { document.body.removechild(oldalert); } if (msg) { var ne...
ARIA Test Cases - Accessibility
when the user changes the state, the new state should be spoken immediately.
... in virtual buffer mode, the slider exists in the virtual buffer as a single entity, and any images or text that create the sliders appearance are not presented to the user separately.
... as expandable items are opened and closed, the state change should be announced immediately.
ARIA: button role - Accessibility
color: white; cursor: default; } [role="button"]:hover, [role="button"]:focus, [role="button"]:active { background-color: white; color: navy; } ul { list-style: none; } javascript function handlecommand(event) { // handles both mouse clicks and keyboard // activate with enter or space // get the new name value from the input element let newnameinput = document.getelementbyid('newname'); let name = newnameinput.value; newnameinput.value = ''; // clear the text field newnameinput.focus(); // give the text field focus to enable entering and additional name.
... let list = document.getelementbyid('namelist'); list.appendchild(listitem); } } toggle button example in this snippet a <span> element is converted to a toggle button using the button role and the aria-pressed attribute.
...); } function handlebtnkeydown(event) { // check to see if space or enter were pressed if (event.key === " " || event.key === "enter" || event.key === "spacebar") { // "spacebar" for ie11 support // prevent the default action to stop scrolling when space is pressed event.preventdefault(); togglebutton(event.target); } } function togglebutton(element) { var audio = document.getelementbyid('audio'); // check to see if the button is pressed var pressed = (element.getattribute("aria-pressed") === "true"); // change aria-pressed to the opposite state element.setattribute("aria-pressed", !pressed); // toggle the play state of the audio file if(pressed) { audio.pause(); } else { audio.play(); } } result accessibility concerns buttons are interacti...
::backdrop - CSS: Cascading Style Sheets
the ::backdrop css pseudo-element is a box the size of the viewport which is rendered immediately beneath any element being presented in full-screen mode.
... when multiple elements have been placed into full-screen mode, the backdrop is drawn immediately beneath the frontmost such element, and on top of the older full-screen elements.
...the ::backdrop pseudo-element makes it possible to obscure, style, or completely hide everything located below the element when it's the topmost one in the top layer.
color-gamut - CSS: Cascading Style Sheets
srgb the output device can support approximately the srgb gamut or more.
... p3 the output device can support approximately the gamut specified by the dci p3 color space or more.
... rec2020 the output device can support approximately the gamut specified by the itu-r recommendation bt.2020 color space or more.
scan - CSS: Cascading Style Sheets
WebCSS@mediascan
rather, it means the process by which an image is painted onto a television screen (or other device).
... interlace the device draws odd lines and even lines alternately.
... some televisions use interlaced scanning.
At-rules - CSS: Cascading Style Sheets
WebCSSAt-rule
/* general structure */ @identifier (rule); /* example: tells browser to use utf-8 character set */ @charset "utf-8"; there are several at-rules, designated by their identifiers, each with a different syntax: @charset — defines the character set used by the style sheet.
... @import — tells the css engine to include an external style sheet.
... @namespace — tells the css engine that all its content must be considered prefixed with an xml namespace.
CSS Containment - CSS: Cascading Style Sheets
it tells the browser that the internal layout of the element is totally separate from the rest of the page, and that everything about the element is painted inside its bounds.
...by using contain: layout you can tell the browser it only needs to check this element — everything inside the element is scoped to that element and does not affect the rest of the page, and the containing box establishes an independent formatting context.
... another advantage is that if the containing box is offscreen, the browser does not need to paint its contained elements — these must also be offscreen as they are contained completely by that box.
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
if you want flexbox to completely ignore the size of the item when doing space distribution then set flex-basis to 0.
... this essentially tells flexbox that all the space is up for grabs, and to share it out in proportion.
...you don’t usually want your content to disappear completely or for boxes to get smaller than their minimum content, so the above rules make sense in terms of sensible behaviour for content that needs to be shrunk in order to fit into a container.
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
as the items can grow, they will expand larger than 160 px in order to fill each row completely.
...the container will need to have a height in order that the items will start wrapping and creating new columns, and items will stretch taller to fill each column completely.
... there is no method in flexbox to tell items in one row to line up with items in the row above — each flex line acts like a new flex container.
Viewport concepts - CSS: Cascading Style Sheets
if you query the width or height of the window and document in chrome or firefox, you may get: document.documentelement.clientwidth /* 1200 */ window.innerwidth /* 1200 */ window.outerwidth /* 1200 */ document.documentelement.clientheight /* 800 */ window.innerheight /* 800 */ window.outerheight /* 900 */ there are several dom properties that can help you query viewport size, and other similar lengths: the document element's element.clientwidth is the inner width of a document in css pixels, including ...
...when zoomed in you may get: document.documentelement.clientwidth /* 800 */ window.innerwidth /* 800 */ window.outerwidth /* 800 in firefox, 1200 in chrome */ document.documentelement.clientheight /* 533 */ window.innerheight /* 533 */ window.outerheight /* 596 in firefox, 900 in chrome */ the viewport was originally 1200 x 800 pixels.
...to tell a mobile browser to use the viewport width instead of the default 980px as the width of the screen, developers can include a viewport meta tag, like the following: <meta name="viewport" content="width=device-width"> the width property controls the size of the viewport.
align-items - CSS: Cascading Style Sheets
aseline alignment */ align-items: baseline; align-items: first baseline; align-items: last baseline; /* overflow alignment (for positional alignment only) */ align-items: safe center; align-items: unsafe center; /* global values */ align-items: inherit; align-items: initial; align-items: unset; values normal the effect of this keyword is dependent of the layout mode we are in: in absolutely-positioned layouts, the keyword behaves like start on replaced absolutely-positioned boxes, and as stretch on all other absolutely-positioned boxes.
... in static position of absolutely-positioned layouts, the keyword behaves as stretch.
...option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe self-end">safe self-end</option> <option value="unsafe self-end">unsafe self-end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div> javascript var values = document.getelementbyid('values'); var display = document.getelementbyid('display'); var container = document.getelementbyid('container'); values.addeventlistener('change', function (evt) { container.style.alignitems = evt.target.value; }); display.addeventlistener('change', function (evt) { container.classname = evt.target.value; }); result specifications specification status commen...
align-self - CSS: Cascading Style Sheets
normal the effect of this keyword is dependent of the layout mode we are in: in absolutely-positioned layouts, the keyword behaves like start on replaced absolutely-positioned boxes, and as stretch on all other absolutely-positioned boxes.
... in static position of absolutely-positioned layouts, the keyword behaves as stretch.
... formal definition initial valueautoapplies toflex items, grid items, and absolutely-positioned boxesinheritednocomputed valueauto computes to itself on absolutely-positioned elements, and to the computed value of align-items on the parent (minus any legacy keywords) on all other boxes, or start if the box has no parent.
animation-delay - CSS: Cascading Style Sheets
the animation can start later, immediately from its beginning, or immediately and partway through the animation.
... a negative value causes the animation to begin immediately, but partway through its cycle.
... for example, if you specify -1s as the animation delay time, the animation will begin immediately but will start 1 second into the animation sequence.
<easing-function> - CSS: Cascading Style Sheets
steps( n, <direction> ) steps(2, jump-start) steps(2, start) steps(4, jump-end) steps(4, end) steps(5, jump-none) steps(3, jump-both) steps-start the equivalent of steps(1, jump-start) steps-end the equivalent of steps(1, jump-end) step-start the animation jumps immediately to its final state, where it stays until the end.
...ground-color: blue; 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.queryselector('select'); const startbtn = document.queryselector('button'); const divelem = document.queryselector('div > div'); startbtn.addeventlistener('click', () => { if(startbtn.textcontent === 'start animation') { divelem.style.animationname = 'move-right'; startbtn.textcontent = 'stop animation'; divelem.style.animationtimingfunction = selectelem.value; } els...
...e { divelem.style.animationname = 'unset'; startbtn.textcontent = 'start animation'; } }); selectelem.addeventlistener('change', () => { divelem.style.animationtimingfunction = selectelem.value; }); result cubic-bezier() function examples these cubic bézier curves are valid for use in css: /* the canonical bézier curve with four <number> in the [0,1] range.
font-language-override - CSS: Cascading Style Sheets
/* keyword value */ font-language-override: normal; /* <string> values */ font-language-override: "eng"; /* use english glyphs */ font-language-override: "trk"; /* use turkish glyphs */ /* global values */ font-language-override: initial; font-language-override: inherit; font-language-override: unset; by default, html's lang attribute tells browsers to display glyphs designed specifically for that language.
... values normal tells the browser to use font glyphs that are appropriate for the language specified by the lang attribute.
... <string> tells the browser to use font glyphs that are appropriate for the language specified by the string.
font - CSS: Cascading Style Sheets
WebCSSfont
line-height must immediately follow font-size, preceded by "/", like this: "16px/3" font-family must be the last value specified.
...setpropcont { margin-bottom: 1em; } .curcss { border: none; border-bottom: 1px solid black; text-align: center; width: 80px; } .mandatory { border-bottom-color: red; } .cf:before, .cf:after { content: " "; display: table; } .cf:after { clear: both; } .tar { width: 40px; text-align: right; } .fontfamily { display: inline-block; } javascript var textareas = document.getelementsbyclassname("curcss"), shorttext = "", getcheckedvalue, setcss, getproperties, injectcss; getproperties = function () { shorttext = getcheckedvalue("font_style") + " " + getcheckedvalue("font_variant") + " " + getcheckedvalue("font_weight") + " " + getcheckedvalue("font_size") + getcheckedvalue("line_height") + " " + getcheckedvalue(...
..."font_family"); return shorttext; } getcheckedvalue = function(radio_name) { oradio = document.forms[0].elements[radio_name]; for (var i = 0; i < oradio.length; i++) { if(oradio[i].checked) { var propinput = "input_" + radio_name, curelemname = "input_" + radio_name, curelem = document.getelementbyid(curelemname); curelem.value = oradio[i].value; return oradio[i].value; } } } setcss = function () { getproperties(); injectcss(shorttext); } injectcss = function(cssfragment) { old = document.body.getelementsbytagname("style"); if (old.length > 1) { old[1].parentelement.removechild(old[1]); } css = document.createelement("style"); css.innerhtml = ".fontshorthand{font: " + cssfragment + "}"; document.body.appendchild(cs...
justify-items - CSS: Cascading Style Sheets
for absolutely-positioned elements, it aligns the items inside their containing block on the inline axis, accounting for the offset values of top, left, bottom, and right.
... values auto the value used is the value of the justify-items property of the parents box, unless the box has no parent, or is absolutely positioned, in these cases, auto represents normal.
... in absolutely-positioned layouts, the keyword behaved like start on replaced absolutely-positioned boxes, and as stretch on all other absolutely-positioned boxes.
place-items - CSS: Cascading Style Sheets
ace-items: right normal; /* baseline alignment */ place-items: baseline normal; place-items: first baseline auto; place-items: last baseline normal; place-items: stretch auto; /* global values */ place-items: inherit; place-items: initial; place-items: unset; values auto the value used is the value of the justify-items property of the parents box, unless the box has no parent, or is absolutely positioned, in these cases, auto represents normal.
... in absolutely-positioned layouts, the keyword behaved like start on replaced absolutely-positioned boxes, and as stretch on all other absolutely-positioned boxes.
...="left auto">left auto</option> <option value="right normal">right normal</option> <option value="baseline normal">baseline normal</option> <option value="first baseline auto">first baseline auto</option> <option value="last baseline normal">last baseline normal</option> <option value="stretch auto">stretch auto</option> </select> </div> javascript var values = document.getelementbyid('values'); var display = document.getelementbyid('display'); var container = document.getelementbyid('container'); values.addeventlistener('change', function (evt) { container.style.placeitems = evt.target.value; }); display.addeventlistener('change', function (evt) { container.classname = evt.target.value; }); css #container { height:200px; width: 240px; place-items: cen...
place-self - CSS: Cascading Style Sheets
normal the effect of this keyword is dependent of the layout mode we are in: in absolutely-positioned layouts, the keyword behaves like start on replaced absolutely-positioned boxes, and as stretch on all other absolutely-positioned boxes.
... in static position of absolutely-positioned layouts, the keyword behaves as stretch.
... formal definition initial valueas each of the properties of the shorthand:align-self: autojustify-self: autoapplies toblock-level boxes, absolutely-positioned boxes, and grid itemsinheritednocomputed valueas each of the properties of the shorthand:align-self: auto computes to itself on absolutely-positioned elements, and to the computed value of align-items on the parent (minus any legacy keywords) on all other boxes, or start if the box has no parent.
right - CSS: Cascading Style Sheets
WebCSSright
syntax /* <length> values */ right: 3px; right: 2.4em; /* <percentage>s of the width of the containing block */ right: 10%; /* keyword value */ right: auto; /* global values */ right: inherit; right: initial; right: unset; values <length> a negative, null, or positive <length> that represents: for absolutely positioned elements, the distance to the right edge of the containing block.
... auto specifies that: for absolutely positioned elements, the position of the element is based on the left property, while width: auto is treated as a width based on the content; or if left is also auto, the element is positioned where it should horizontally be positioned if it were a static element.
... width of the containing blockcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoanimation typea length, percentage or calc(); formal syntax <length> | <percentage> | auto examples absolute and relative positioning using right html <div id="relative">relatively positioned</div> <div id="absolute">absolutely positioned</div> css #relative { width: 100px; height: 100px; background-color: #ffc7e4; position: relative; top: 20px; left: 20px; } #absolute { width: 100px; height: 100px; background-color: #ffd7c2; position: absolute; bottom: 10px; right: 20px; } result declaring both left and right when both left and right are declared, the element will stretch to meet bo...
Setting up adaptive streaming media sources - Developer guides
the mpd file tells the browser where the various pieces of media are located, it also includes meta data such as mimetype and codecs and there are other details such as byte-ranges in there too - it is an xml document and in many cases will be generated for you.
... </adaptationset> </period> </mpd> the mpd file tells the browser where the various pieces of media are located, it also includes meta data such as mimetype and codecs and there are other details such as byte-ranges in there too.
... note: you can also split out your audio and video streams into separate files, which can then be prioritised and served separately depending on bandwidth.
Creating a cross-browser video player - Developer guides
a number of variables pointing to html elements are required: var videocontainer = document.getelementbyid('videocontainer'); var video = document.getelementbyid('video'); var videocontrols = document.getelementbyid('video-controls'); as mentioned earlier, the browser's default controls now need to be disabled, and the custom controls need to be displayed: // hide the default controls video.controls = false; // display the user defined video controls videocontrols.style.display = 'block';...
... with that done, a variable pointing to each of the buttons is now required: var playpause = document.getelementbyid('playpause'); var stop = document.getelementbyid('stop'); var mute = document.getelementbyid('mute'); var volinc = document.getelementbyid('volinc'); var voldec = document.getelementbyid('voldec'); var progress = document.getelementbyid('progress'); var progressbar = document.getelementbyid('progress-bar'); var fullscreen = document.getelementbyid('fs'); using these handles, events can now be attached to each of the custom control buttons making them interactive.
... ideally, the correct value of the video's duration attribute is available when the loadedmetadata event is raised, which occurs when the video's metadata has been loaded: video.addeventlistener('loadedmetadata', function() { progress.setattribute('max', video.duration); }); unfortunately in some mobile browsers, when loadedmetadata is raised — if it even is raised — video.duration may not have the correct value, or even any value at all.
Using device orientation with 3D transforms - Developer guides
be applied to those values: the initial alpha value is 180 (device flat on the back, top of the screen pointing 12:00), so the rotatez value should be alpha - 180 the y axis of the screen coordinate system is inverted, such that translatey(100px) moves an element 100px down, so the rotatey value should be -gamma finally, the order of the three different rotations is very important to accurately convert an orientation to a 3d rotation: rotatez, then rotatex and then rotatey.
... here's a simple code snippet to sum it up: var elem = document.getelementbyid("view3d"); window.addeventlistener("deviceorientation", function(e) { // remember to use vendor-prefixed transform property elem.style.transform = "rotatez(" + ( e.alpha - 180 ) + "deg) " + "rotatex(" + e.beta + "deg) " + "rotatey(" + ( -e.gamma ) + "deg)"; }); orientation compensation compensating the orientation of the device can be useful to create parallax effects or augmented reality.
... this is achieved by inverting the previous order of rotations and negating the alpha value: var elem = document.getelementbyid("view3d"); window.addeventlistener("deviceorientation", function(e) { // again, use vendor-prefixed transform property elem.style.transform = "rotatey(" + ( -e.gamma ) + "deg)" + "rotatex(" + e.beta + "deg) " + "rotatez(" + - ( e.alpha - 180 ) + "deg) "; }); rotate3d to orientation should you ever need to convert a rotate3d axis-angle to orientation euler angles, you can use the following algorithm: // convert a rotate3d axis-angle to deviceorientation angles function orient( aa ) { var x = aa.x, y = aa.y, z = aa.z, a = aa.a, c = math.cos( aa.a ), s = math.sin( aa.a ), t = 1 - c, // axis-angle to rotation matr...
Rich-Text Editing in Mozilla - Developer guides
figure 3 : setting up rich-text editing html: <body onload="load()"> javascript: function load(){ getiframedocument("editorwindow").designmode = "on"; } function getiframedocument(aid){ // if contentdocument exists, w3c compliant (mozilla) if (document.getelementbyid(aid).contentdocument){ return document.getelementbyid(aid).contentdocument; } else { // ie return document.frames[aid].document; } } the example contains a doricheditcommand function that makes it easier to execute commands on the iframe's document and keeps the html code clean.
... figure 4 : executing rich editing commands html: <button onclick="doricheditcommand('bold')" style="font-weight:bold;">b</button> javascript: function doricheditcommand(aname, aarg){ getiframedocument('editorwindow').execcommand(aname,false, aarg); document.getelementbyid('editorwindow').contentwindow.focus() } example: a simple but complete rich text editor <!doctype html> <html> <head> <title>rich text editor</title> <script type="text/javascript"> var odoc, sdeftxt; function initdoc() { odoc = document.getelementbyid("textbox"); sdeftxt = odoc.innerhtml; if (document.compform.switchmode.checked) { setdocmode(true); } } function formatdoc(sc...
...ick="formatdoc('indent');" src="data:image/gif;base64,r0lgodlhfgawaomiaaaaadljwl9vj1ie35gjuaezxtdv3nha7p///////////////////////////////yh5baeaaagalaaaaaawabyaaaq7emljq704650b/x8gemmpgugwhjnzxodkso5oquogo5khbwwesymqscrdhu9voyk5tm9zspfsr9gsjwiaow==" /> <img class="intlink" title="hyperlink" onclick="var slnk=prompt('write the url here','http:\/\/');if(slnk&&slnk!=''&&slnk!='http://'){formatdoc('createlink',slnk)}" src="data:image/gif;base64,r0lgodlhfgawaomkab1chdrly19vj3morpgjuaezxrcztb/i19ha7pv8/f///////////////////////yh5baekaa8alaaaaaawabyaaary8mljq7046827/2byiqvhhg9pegvgiklydeuby/rle4fqf4dcj2aqxaijqdcwqcaebwiioemqbgsafhdagghgi9xghahmnoszgjkjei33uesv2+/4vd4taqa7" /> <img class="intlink" title="cut" onclick="formatdoc('cut');" src="data:image/gif;base64,r0lgodlhfgawaiqsab1chbfnsrjtysjywjljwkx...
Separate sites for mobile and desktop - Developer guides
finally, it also allows for completely different user experiences on desktop and mobile — they’re two different sites, after all!
... the bad unfortunately, this approach is not without its drawbacks.
...this is because you have the option of sending completely separate html, javascript, and css to phones and pcs.
HTML attribute: pattern - HTML: Hypertext Markup Language
the pattern attribute is an attribute of the text, tel, email, url, password, and search input types.
...user agents may use the title contents during constraint validation to tell the user that the pattern is not matched.
... examples given the following: <p> <label>enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>)- <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3"/> </label> </p> here we have 3 sections for a north american phone number with an im...
HTML attribute reference - HTML: Hypertext Markup Language
intrinsicsize <img> this attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute.
... loading <img>, <iframe> indicates if the element should be loaded lazily (loading="lazy") or loaded immediately (loading="eager").
...unfortunately, there are no clear rules and the way idl attributes behave in conjunction with their corresponding content attributes depends on the attribute.
<a>: The Anchor element - HTML: Hypertext Markup Language
WebHTMLElementa
links are not restricted to http-based urls — they can use any url scheme supported by browsers: sections of a page with fragment urls pieces of media files with media fragments telephone numbers with tel: urls email addresses with mailto: urls while web browsers may not support other url schemes, web sites can with registerprotocolhandler() hreflang hints at the human language of the linked url.
... linking to telephone numbers <a href="tel:+49.157.0156">+49 157 0156</a> <a href="tel:+1(555)5309">(555) 5309</a> tel: link behavior varies with device capabilities: cellular devices autodial the number.
... see rfc 3966 for syntax, additional features, and other details about the tel: url scheme.
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
it is always useful to include the file's mime type inside the type attribute, as the browser is able to instantly tell if it can play that file, and not waste time on it if not.
... element (opus) if it is able to play it; if not it falls back to the second (vorbis) and finally back to mp3: <audio controls> <source src="foo.opus" type="audio/ogg; codecs=opus"/> <source src="foo.ogg" type="audio/ogg; codecs=vorbis"/> <source src="foo.mp3" type="audio/mpeg"/> </audio> accessibility concerns audio with spoken dialog should provide both captions and transcripts that accurately describe its content.
... if automatic captioning services are used, it is important to review the generated content to ensure it accurately represents the source audio.
<dfn>: The Definition element - HTML: Hypertext Markup Language
WebHTMLElementdfn
this can be done by using the <dfn> and <abbr> elements in tandem, like this: html <p>the <dfn><abbr title="hubble space telescope">hst</abbr></dfn> is among the most productive scientific instruments ever constructed.
... it has been in orbit for over 20 years, scanning the sky and returning data and photographs of unprecedented quality and detail.</p> <p>indeed, the <abbr title="hubble space telescope">hst</abbr> has arguably done more to advance science than any device ever built.</p> note the <abbr> element nested inside the <dfn>.
... the former establishes that the term is an abbreviation ("hst") and specifies the full term ("hubble space telescope") in its title attribute.
<input type="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
(only the htmlinputelement’s checked idl attribute is updated.) note: unlike other input controls, a checkboxes value is only included in the submitted data if the checkbox is currently checked.
...if they are completely unrelated, then you can just deal with them all separately, as shown above.
...this is set using the htmlinputelement object's indeterminate property via javascript (it cannot be set using an html attribute): inputinstance.indeterminate = true; a checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers.
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
you can also get and set the date value in javascript using the htmlinputelement.value property, for example: <label for="bday-month">what month were you born in?</label> <input id="bday-month" type="month" name="bday-month" value="2017-06"> var monthcontrol = document.queryselector('input[type="month"]'); monthcontrol.value = '1978-06'; additional attributes in addition to the attributes common to <input> elements, month inputs offer the following attributes: ...
...its value can, however, still be changed from javascript code that directly sets the value of the htmlinputelement.value property.
...in order to detect whether the browser supports <input type="month">, we create a new <input> element, try setting its type to month, then immediately check what its type is set to.
<input type="text"> - HTML: Hypertext Markup Language
WebHTMLElementinputtext
if the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
...it only specifies approximately how many can be seen at a time.
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
if the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.
...its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
...it only specifies approximately how many can be seen at a time.
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
height the height of the video's display area, in css pixels (absolute values only; no percentages.) intrinsicsize this attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute.
... accessibility concerns videos should provide both captions and transcripts that accurately describe its content (see adding captions and subtitles to html5 video for more information on how to implement these).
... if automatic captioning services are used, it is important to review the generated content to ensure it accurately represents the source video.
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
<bdi> the html bidirectional isolate element (<bdi>) tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text.
... <template> the html content template (<template>) element is a mechanism for holding html that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using javascript.
... <tt> the obsolete html teletype text element (<tt>) creates inline text which is presented using the user agent's default monospace font face.
Preloading content with rel="preload" - HTML: Hypertext Markup Language
using as to specify the type of content to be preloaded allows the browser to: prioritize resource loading more accurately.
... you can see an example of this in our video example (see the full source code, and also the live version): <head> <meta charset="utf-8"> <title>video preload example</title> <link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4"> <link rel="preload" href="sintel-short.webm" as="video" type="video/webm"> </head> <body> <video controls> <source src="sintel-short.mp4" type="video/mp4"> <source src="sintel-short.webm" type="video/webm"> <p>your browser doesn't support html5 video.
... here is a <a href="sintel-short.mp4">link to the video</a> instead.</p> </video> </body> so in this case, browsers that support mp4s will preload and use the mp4, making the video player hopefully smoother/more responsive for users.
Evolution of HTTP - HTTP
a typical flow of requests, all through one single connection is now looking like this: get /docs/glossary/simple_header http/1.1 host: developer.mozilla.org user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language: en-us,en;q=0.5 accept-encoding: gzip, deflate, br referer: https://developer.mozilla.org/docs/glossary/simple_header 200 ok connection: keep-alive content-encoding: gzip content-type: text/html; charset=utf-8 date: wed, 20 jul 2016 10:55:30 gmt etag: "547fa...
...7e369ef56031dd3bff2ace9fc0832eb251a" keep-alive: timeout=5, max=1000 last-modified: tue, 19 jul 2016 00:59:33 gmt server: apache transfer-encoding: chunked vary: cookie, accept-encoding (content) get /static/img/header-background.png http/1.1 host: developer.cdn.mozilla.net user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 accept: */* accept-language: en-us,en;q=0.5 accept-encoding: gzip, deflate, br referer: https://developer.mozilla.org/docs/glossary/simple_header 200 ok age: 9578461 cache-control: public, max-age=315360000 connection: keep-alive content-length: 3077 content-type: image/png date: thu, 31 mar 2016 13:34:46 gmt last-modified: wed, 21 oct 2015 18:27:50 gmt server: apache (image content of 3077 bytes) http/1.1 was first publishe...
...he envisioned a web where people can add and move documents remotely, a kind of distributed file system.
Identifying resources on the Web - HTTP
https://developer.mozilla.org https://developer.mozilla.org/docs/learn/ https://developer.mozilla.org/search?q=url any of those urls can be typed into your browser's address bar to tell it to load the associated page (resource).
...common schemes are: scheme description data data uris file host-specific file names ftp file transfer protocol http/https hyper text transfer protocol (secure) javascript url-embedded javascript code mailto electronic mail address ssh secure shell tel telephone urn uniform resource names view-source source code of the resource ws/wss (encrypted) websocket connections authority www.example.com is the domain name or authority that governs the namespace.
... examples https://developer.mozilla.org/docs/learn tel:+1-816-555-1212 git@github.com:mdn/browser-compat-data.git ftp://example.org/resource.txt urn:isbn:9780141036144 mailto:help@supercyberhelpdesk.info specifications specification title rfc 7230, section 2.7: uniform resource identifiers hypertext transfer protocol (http/1.1): message syntax and routing ...
Index - HTTP
WebHTTPHeadersIndex
7 access-control-allow-credentials cors, http, reference, header the access-control-allow-credentials response header tells browsers whether to expose the response to frontend javascript code when the request's credentials mode (request.credentials) is "include".
... 84 large-allocation http, http header, non-standard, reference, response header, header the non-standard large-allocation response header tells the browser that the page being loaded is going to want to perform a large allocation.
... 103 strict-transport-security hsts, http, https, security, header the http strict-transport-security response header (often abbreviated as hsts) lets a web site tell browsers that it should only be accessed using https, instead of using http.
Strict-Transport-Security - HTTP
the http strict-transport-security response header (often abbreviated as hsts) lets a web site tell browsers that it should only be accessed using https, instead of using http.
...unfortunately, the access point you're using is actually a hacker's laptop, and they're intercepting your original http request and redirecting you to a clone of your bank's site instead of the real thing.
...should it be necessary to disable strict transport security, setting the max-age to 0 (over a https connection) will immediately expire the strict-transport-security header, allowing access via http.
An overview of HTTP - HTTP
WebHTTPOverview
http is stateless, but not sessionless http is stateless: there is no link between two requests being successively carried out on the same connection.
... this immediately has the prospect of being problematic for users attempting to interact with certain pages coherently, for example, using e-commerce shopping baskets.
... but while the core of http itself is stateless, http cookies allow the use of stateful sessions.
JavaScript data types and data structures - JavaScript
unfortunately, when the separator is used in one of the "list" elements, then, the list is broken.
...native implementations of them (including weakmaps) can have look-up performance that is approximately logarithmic to constant time.
...maps and weakmaps make it easy to privately bind data to an object.
Loops and iteration - JavaScript
you can think of a loop as a computerized version of the game where you tell someone to take x steps in one direction, then y steps in another.
...sical</option> <option>opera</option> </select> </p> <p><input id="btn" type="button" value="how many are selected?" /></p> </form> <script> function howmany(selectobject) { let numberselected = 0; for (let i = 0; i < selectobject.options.length; i++) { if (selectobject.options[i].selected) { numberselected++; } } return numberselected; } let btn = document.getelementbyid('btn'); btn.addeventlistener('click', function() { alert('number of options selected: ' + howmany(document.selectform.musictypes)); }); </script> do...while statement the do...while statement repeats until a specified condition evaluates to false.
... when you use break without a label, it terminates the innermost enclosing while, do-while, for, or switch immediately and transfers control to the following statement.
Regular expression syntax cheatsheet - JavaScript
if the multiline flag is set to true, also matches immediately after a line break character.
...if the multiline flag is set to true, also matches immediately before a line break character.
...for example, /e?le?/ matches the "el" in "angel" and the "le" in "angle." if used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).
async function - JavaScript
} async function concurrentstart() { console.log('==concurrent start with await=='); const slow = resolveafter2seconds() // starts timer immediately const fast = resolveafter1second() // starts timer immediately // 1.
...this runs 2 seconds after 1., immediately after 2., since fast is already resolved } function concurrentpromise() { console.log('==concurrent start with promise.all==') return promise.all([resolveafter2seconds(), resolveafter1second()]).then((messages) => { console.log(messages[0]) // slow console.log(messages[1]) // fast }) } async function parallel() { console.log('==parallel with await promise.all==') // start 2 "jobs" in parallel and wait for both of them to complete await promise.all([ (async()=>console.log(await resolveafter2seconds()))(), (async()=>console.log(await resolveafter1second()))() ]) } sequentialstart() // af...
... this highlights the subtle difference between return foo; and return await foo; — return foo immediately returns foo and never throws, even if foo is a promise that rejects.
Authoring MathML - MathML
html becomes verbose when your document contains advanced structures like lists or tables but fortunately there are many generators from simple notations, wysiwyg editors and other content management systems to help writing web pages.
... fallback for browsers without mathml support unfortunately, some browsers are not able to render mathml equations or only have a limited support.
...given a foo.tex latex file, you can use these simple commands: latexmlc --dest foo.html foo.tex # generate a html5 document foo.html latexmlc --dest foo.epub foo.tex # generate an epub document foo.epub to handle the case of browsers without mathml support, you can use the --javascript parameter to tell latexml to include one of the fallback scripts: latexmlc --dest foo.html --javascript=https://fred-wang.github.io/mathml.css/mspace.js foo.tex # add the css fallback latexmlc --dest foo.html --javascript=https://fred-wang.github.io/mathjax.js/mpadded-min.js foo.tex # add the mathjax fallback if your latex document is big, you might want to split it into several small pages rather than pu...
Image file type and format guide - Web media technologies
while other data representations are defined in the specification, they are not widely used and often completely unimplemented.
...svg files are ideal for diagrams, icons, and other images which can be accurately drawn at any size.
...these include cmyk, ycbcr, and others, making tiff a good choice for storing images intended for print, film, or television media.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
instead of showing the notification immediately though, best practice dictates that we should show the popup when the user requests it by clicking on a button: var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.requestpermission().then(function(result) { if(result === 'granted') { randomnotification(); } }); }); this shows a popup using the o...
...*/ }); the data can be retrieved and then shown as a notification to the user immediately.
... fetch('./register', { method: 'post', headers: { 'content-type': 'application/json' }, body: json.stringify({ subscription: subscription }), }); then the globaleventhandlers.onclick function on the subscribe button is defined: document.getelementbyid('doit').onclick = function() { const payload = document.getelementbyid('notification-payload').value; const delay = document.getelementbyid('notification-delay').value; const ttl = document.getelementbyid('notification-ttl').value; fetch('./sendnotification', { method: 'post', headers: { 'content-type': 'application/json' }, bo...
Graphic design for responsive sites - Progressive web apps (PWAs)
textual content is not a problem, as text boxes are innately responsive, but the picture starts to get ugly when you start including graphics and complex layouts on your pages — especially when those graphics and layouts need to adapt to different displays!
... programmatic images you should also try to use programmatic/vector graphics as much as possible, as they theoretically scale infinitely so will still look crisp at high resolutions.
...text is infinitely scalable on the web, and you can also use css text properties to style your web font icons, such as text-shadow and color.
Structural overview of progressive web apps - Progressive web apps (PWAs)
that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any new content is requested from the server (if it isn’t available in the cache already).
...var entry = template.replace(/pos/g,(i+1)) .replace(/slug/g,games[i].slug) .replace(/name/g,games[i].name) .replace(/author/g,games[i].author) .replace(/twitter/g,games[i].twitter) .replace(/website/g,games[i].website) .replace(/github/g,games[i].github); entry = entry.replace('<a href=\'http:///\'></a>','-'); content += entry; }; document.getelementbyid('content').innerhtml = content; then it registers a service worker: if ("serviceworker" in navigator) { navigator.serviceworker.register("/pwa-examples/js13kpwa/sw.js"); } after that, the app adds a handler for clicks on a button whose id is notifications; this handler requests permission to send notifications to the user, then generates and sends a random notification.
... var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.requestpermission().then(function(result) { if (result === 'granted') { randomnotification(); } }); }); the randomnotification() function follows, rounding out the last of the code in the file: function randomnotification() { var randomitem = math.floor(math.random()*games.length); var notiftitle = games[randomitem].name; var notifbody = 'created by '+games[randomitem].author+'.'; var notifimg = 'data/img/'+games[randomitem].slug+'.jpg'; var options = { body: notifbody, icon: notifimg } var notif = new notification(notiftitle, options); settimeout(randomnotification, 30000); } the service worker the last file we'll briefly look ...
Content type - SVG: Scalable Vector Graphics
the format of an rgb value in hexadecimal notation is a "#" immediately followed by either three or six hexadecimal characters.
...as defined in css2, a frequency value is a <number> immediately followed by a frequency unit identifier.
... time <time> a time value is a <number> immediately followed by a time unit identifier.
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
svgexternalresourcesrequired removed never implemented svgelement.viewportelement and svgelement.ownersvgelement nullable implementation status unknown svgelement.getpresentationattribute() removed never implemented (prototype removed in bug 921456) svgcolor and svgicccolor removed never implemented svgelement.focus(), svgelement.blur() not implemented (bug 778654) svgelement.tabindex implemented (bug 778654) doc...
... auto value for width and height in <image> implementation status unknown referencing entire document with <use> implementation status unknown lang attribute on <desc> and <title> implemented (bug 721920) css transforms on outermost <svg> not affecting svgsvgelement.currentscale or svgsvgelement.currenttranslate implementation status unknown rootelement attribute deprecated implementation status unknown svgelementinstance and svgelementinstancelist and corresponding attributes on svguseelement removed implementation status unknown <use> event flow following shadow dom spec.
...loop of a single closed path, effected by the startoffset attribute and text-anchor property implementation status unknown <tref> removed implementation status unknown <altglyph>, <altglyphdef>, <altglyphitem> and <glyphref> removed <altglyph>, <altglyphdef> and <altglyphitem> removed (bug 1260032), <glyphref> never really implemented (bug 1302693) svgtextcontentelement.selectsubstring() deprecated implementation status unknown getcomputedtextlength() not including dx and dy values implementation status unknown text in non-rendered elements not included in addressable characters implementation status unknown unknown elements in text render as unpositioned spans implementation status unknown offset distances of...
Scripting - SVG: Scalable Vector Graphics
WebSVGScripting
function myrect(x,y,w,h,message){ this.message=message this.rect=document.createelementns("http://www.w3.org/2000/svg","rect") this.rect.setattributens(null,"x",x) this.rect.setattributens(null,"y",y) this.rect.setattributens(null,"width",w) this.rect.setattributens(null,"height",h) document.documentelement.appendchild(this.rect) this.rect.addeventlistener("click",this,false) this.handleevent= function(evt){ switch (evt.type){ case "click": alert(this.message) break; } } } inter-document scripting: referencing embedded svg when using svg within html, adobe's svg viewer 3.0 automatically includes a window property called svgdocument that points to the svg docum...
... the best way to get access to the document representing an svg document is to look at htmliframeelement.contentdocument (if the document is presented in an <iframe>) or htmlobjectelement.contentdocument (if the document is presented in an <object> element), like this: var svgdoc = document.getelementbyid("iframe_element").contentdocument; in addition, the <iframe>, <embed>, and <object> elements offer a method, getsvgdocument(), which returns the xmldocument representing the element's embedded svg or null if the element doesn't represent an svg document.
... you can also use document.getelementbyid("svg_elem_name").getsvgdocument(), which gives the same result.
Subresource Integrity - Web security
however, using cdns also comes with a risk, in that if an attacker gains control of a cdn, the attacker can inject arbitrary malicious content into files on the cdn (or replace the files completely) and thus can also potentially attack all sites that fetch files from that cdn.
... using subresource integrity you use the subresource integrity feature by specifying a base64-encoded cryptographic hash of a resource (file) you’re telling the browser to fetch, in the value of the integrity attribute of any <script> or <link> element.
... subresource integrity with the <script> element you can use the following <script> element to tell a browser that before executing the https://example.com/example-framework.js script, the browser must first compare the script to the expected hash, and verify that there's a match.
Web security
connection security transport security layer (tls) the transport layer security (tls) protocol is the standard for enabling two networked applications or devices to exchange information privately and robustly.
...typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example.
...this is a way to opt out of mime type sniffing, or, in other words, to say that the mime types are deliberately configured.
Using custom elements - Web Components
first of all, we define our element's class, in the same manner as before: class expandinglist extends htmlulistelement { constructor() { // always call super first in constructor super(); // write element functionality in here ...
...the only real difference here is that our element is extending the htmlulistelement interface, and not htmlelement.
...some of these libraries are snuggsi ツ, x-tag, slim.js, litelement, smart, stencil and hyperhtml-element.
Web Components
shadow dom: a set of javascript apis for attaching an encapsulated "shadow" dom tree to an element — which is rendered separately from the main document dom — and controlling associated functionality.
...the associated dom interface is htmlslotelement.
... the slotchange event fired on an htmlslotelement instance (<slot> element) when the node(s) contained in that slot change.
Index - XSLT: Extensible Stylesheet Language Transformations
WebXSLTIndex
or use a download tool, those usually tell the mime type.
...this intelligent structuring is particularly important as more and more data transfers are automated and take place between highly heterogeneous machines linked by a network.
...to prevent a normally xsl:-prefixed literal result element (which should simply be copied as-is to the result tree) from being misunderstood by the processor, it is assigned a temporary namespace which is appropriately re-converted back to the xslt namespace in the output tree.
Understanding WebAssembly text format - WebAssembly
the first label inside the parenthesis tells you what type of node it is, and after that there is a space-separated list of either attributes or child nodes.
... webassembly could add an anyfunc type ("any" because the type could hold functions of any signature), but unfortunately this anyfunc type couldn’t be stored in linear memory for security reasons.
...since webassembly is typechecked, and the funcref can be potentially any function signature, we have to supply the presumed signature of the callee at the callsite, hence we include the $return_i32 type, to tell the program a function returning an i32 is expected.
Cross-domain Content Scripts - Archive of obsolete content
ame whose content is served from "http://en.m.wikipedia.org/": <!doctype html> <!-- page.html --> <html> <head></head> <body> <iframe id="wikipedia" src="http://en.m.wikipedia.org/"></iframe> </body> </html> the "page-script.js" file locates "today's featured article" and sends its content to "main.js": // page-script.js var iframe = window.document.getelementbyid("wikipedia"); var todaysfeaturedarticle = iframe.contentwindow.document.getelementbyid("mp-tfa"); self.postmessage(todaysfeaturedarticle.textcontent); for this to work, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://en.m.wikipedia.org/"] } the add-on should successfully retrieve the iframe's content.
...panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=your-api-key"; self.port.on("show", function () { var request = new xmlhttprequest(); request.open("get", url, true); request.onload = function () { var jsonresponse = json.parse(request.responsetext); var summary = getsummary(jsonresponse); var element = document.getelementbyid("forecast_summary"); element.textcontent = summary; }; request.send(); }); function getsummary(forecast) { return forecast.regionalfcst.fcstperiods.period[0].paragraph[0].$; } finally, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://datapoint.metoffice.gov.uk"] } content permissions and unsafewindow if ...
port - Archive of obsolete content
this example rewrites the content script in the port.removelistener() example so that it uses once(): // content-script.js function getfirstparagraph() { var paras = document.getelementsbytagname('p'); console.log(paras[0].textcontent); } self.port.once("get-first-para", getfirstparagraph); removelistener() you can use port.on() to listen for messages.
... // content-script.js function getfirstparagraph() { var paras = document.getelementsbytagname('p'); console.log(paras[0].textcontent); self.port.removelistener("get-first-para", getfirstparagraph); } self.port.on("get-first-para", getfirstparagraph); the result is that the paragraph is only logged the first time the button is clicked.
Porting the Library Detector - Archive of obsolete content
the library detector tells you which javascript frameworks the current web page is using.
...this means we'll need two additional content scripts: one in the widget's context, which listens for icon mouseover events and sends a message to main.js containing the name of the corresponding library: function setlibraryinfo(element) { self.port.emit('setlibraryinfo', element.target.title); } var elements = document.getelementsbytagname('img'); for (var i = 0; i &lt; elements.length; i++) { elements[i].addeventlistener('mouseover', setlibraryinfo, false); } one in the panel, which updates the panel's content with the library information: self.on("message", function(libraryinfo) { window.document.body.innerhtml = libraryinfo; }); finally main.js relays the library information from the widget to the pan...
SDK API Lifecycle - Archive of obsolete content
we will avoid breaking backwards compatibility unless absolutely necessary.
... all warnings should include links to further information about what to use instead of the deprecated module and when the module will be completely removed.
XUL Migration Guide - Archive of obsolete content
xul windows xul windows are used to define completely new windows to host user interface elements specific to the add-on.
...here's a really simple example add-on that modifies the browser chrome using window/utils: function removeforwardbutton() { var window = require("sdk/window/utils").getmostrecentbrowserwindow(); var forward = window.document.getelementbyid('forward-button'); var parent = window.document.getelementbyid('urlbar-container'); parent.removechild(forward); } require("sdk/ui/button/action").actionbutton({ id: "remove-forward-button", label: "remove forward button", icon: "./icon-16.png", onclick: removeforwardbutton }); there are more useful examples of this technique in the jetpack wiki's collection of third party...
self - Archive of obsolete content
note that the self module is completely different from the global self object accessible to content scripts, which is used by a content script to communicate with the add-on code.
...this data lives in the add-on's data/ directory, immediately below the package.json file.
content/symbiont - Archive of obsolete content
this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires this prope...
...this may have one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read...
remote/parent - Archive of obsolete content
ry current and future process processes.forevery(process => { // ask for the process id process.port.emit("fetchid"); // first argument is always the process, then the message payload process.port.once("id", (process, id) => { console.log("child process is remote:" + process.isremote); console.log("child process id:" + id); }); }); content frame manipulation this demonstrates telling every current frame to link to a specific anchor element: // remote.js const { frames } = require("sdk/remote/child"); // listeners receive the frame the event was for as the first argument frames.port.on("changelocation", (frame, ref) => { frame.content.location += "#" + ref; }); // main.js const { frames, remoterequire } = require("sdk/remote/parent"); remoterequire("./remote.js", mod...
...the module loads asynchronously but you can start sending messages to the module immediately.
stylesheet/utils - Archive of obsolete content
the sheets added takes effect immediately, and only on the document of the window given.
...the removal takes effect immediately.
window/utils - Archive of obsolete content
isdocumentloaded(window) check if the given window's document is completely loaded.
... parameters window : nsidomwindow returns boolean: true if the document is completely loaded.
jpmignore - Archive of obsolete content
if your project folder contains a lot of files that aren't necessary for the xpi to run, like documentation, jshint, etc., you can use .jpmignore as a whitelist instead of a blacklist.
... for example: .* * !/data/** !/lib/** !/locale/** !/node_modules/** !/package.json !/icon.png !/icon64.png !/copying !/bootstrap.js !/install.rdf this would include all editor backup files and similar in the whitelisted subdirectories, to avoid that you can append another blacklist after the whitelist.
Overview - Archive of obsolete content
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.
...when the user moves the mouse over an annotated element the matcher tells the main add-on code, which displays the annotation panel.
Bootstrapped extensions - Archive of obsolete content
you need to look up the relevant application ui elements by their id by calling document.getelementbyid(), then manipulate them to inject your ui.
... for example, you can get access to the menu bar in firefox with document.getelementbyid("main-menubar").
File I/O - Archive of obsolete content
you can tell files from folders by calling nsifile.isdirectory() and nsifile.isfile() methods on each entry.
...there might be races between different processes and/or threads, e.g., a file could be immediately created or deleted after you check the existence but before you can perform any other actions such as opening the file for reading or writing.
HTML in XUL for rich tooltips - Archive of obsolete content
var htmltip = { onload: function() { //at any point you can save an html string to a xul attribute for later injection into the tooltip document.getelementbyid("htmltip1").setattribute("tooltiphtml", "<font color='red'>red foo</font>") document.getelementbyid("htmltip2").setattribute("tooltiphtml", "<font color='green'>green foo</font>") }, onmousetooltip: function(event) { //get the html tooltip string assigned to the element that the mouse is over (which will soon launch the tooltip) var txt = event.target.getattribute("tooltiphtml"); ...
...// get the html div element that is inside the custom xul tooltip var div = document.getelementbyid("myhtmltipdiv"); //clear the html div element of any prior shown custom html while(div.firstchild) div.removechild(div.firstchild); //safely convert html string to a simple dom object, stripping it of javascript and more complex tags var injecthtml = components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(txt, false, null, div); //attach the dom object to the html div element div.appendchild(injecthtml); } } window.addeventlistener('load', htmltip.onload, false); in the xul overlay, xmlns:html is used to enable html tags to be used inside the xul.
QuerySelector - Archive of obsolete content
selector); }; alert(document.$('label')); // [object xulelement] ]]></script> document.prototype.$ = function (selector) { // only for plain xml return this.queryselector(selector); }; var foo = document.implementation.createdocument('somens', 'foo', null); // create an xml document <foo xmlns="somens"/> var bar = foo.createelementns('somens', 'bar'); // add <bar xmlns="somens"/> foo.documentelement.appendchild(bar); alert(foo.$('bar').nodename); // gives 'bar' element.prototype.$ = function (selector) { // works for html, xul, and plain xml return this.queryselector(selector); }; html example: <h1><a>test!<a/></h1> <script> element.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.getelementsbytagname('h1')[0].$('a').nodename); // 'a' ...
... xul example: <hbox><vbox/></hbox> <script type="text/javascript"><![cdata[ element.prototype.$ = function (selector) { return this.queryselector(selector); }; var xulns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; alert(document.getelementsbytagnamens(xulns, 'hbox')[0].$('vbox').nodename); // vbox ]]></script> xml example: <foo xmlns="somens"><bar/></foo> in document earlier var foo = document.getelementsbytagnamens('somens', 'foo')[0]; alert(foo.$('bar')); note that for plain xml, the # 'id' selector will not work with an 'id' attribute (since a such-named attribute need not necessarily be of type id in xml, though it is in html and xul), nor will it work with xml:id.
Tree - Archive of obsolete content
iew = tree.treeboxobject.view; for (var i = 0; i < treeview.rowcount; i++) { if (treeview.iscontainer(i) && treeview.iscontaineropen(i)) treeview.toggleopenstate(i); } getting the text from the selected row assuming the given <tree>: <tree id="my-tree" seltype="single" onselect="ontreeselected()"> use the following javascript: function ontreeselected(){ var tree = document.getelementbyid("my-tree"); var cellindex = 0; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(cellindex)); alert(celltext); } getting the tree item from the focused row assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document.getelementbyid("my-tree").view; var sel = view.selection.currentindex; //returns -1 if the ...
...for example, assuming the given <tree>: <tree id="my-tree" onclick="ontreeclicked(event)"> use the following javascript: function ontreeclicked(event){ var tree = document.getelementbyid("my-tree"); var tbo = tree.treeboxobject; // get the row, col and child element at the point var row = { }, col = { }, child = { }; tbo.getcellat(event.clientx, event.clienty, row, col, child); var celltext = tree.view.getcelltext(row.value, col.value); alert(celltext); } getting the selected indices of a multiselect tree var start = {}, end = {}, numranges = tree.view...
Displaying web content in an extension without security issues - Archive of obsolete content
for example, your template document might have this code: <style type="text/css"> #entrytemplate { display: none; } </style> <div id="entrytemplate"> <div class="title"></div> <div class="description"></div> </div> now to insert a new entry in the document you would do the following: var template = doc.getelementbyid("entrytemplate"); var entry = template.clonenode(true); entry.removeattribute("id"); entry.getelementsbyclassname("title")[0].textcontent = title; entry.getelementsbyclassname("description")[0].textcontent = description; template.parentnode.appendchild(entry); the important difference here is that the result will always have the same structure as the template tag.
...instead, nsiscriptableunescapehtml.parsefragment() method should be used that is meant for just that scenario: var target = entry.getelementsbyclassname("description")[0]; var fragment = components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(description, false, null, target); target.appendchild(fragment); this will add the html code to the specified node — minus all the potentially dangerous content.
Jetpack Processes - Archive of obsolete content
these processes are relatively lightweight, do not have access to xpcom, and can innately do little other than compute.
...to prevent such memory leaks, a process can either invalidate a handle, immediately preventing it from being passed as a message argument, or it can unroot the handle, allowing it to be passed as a message argument until all references to it are removed, at which point it is garbage collected.
Listening to events in Firefox extensions - Archive of obsolete content
domcontentloaded dispatched when the initial dom for the page is completely loaded.
...when this property is set to false, the unload handler, if present, fires immediately after the pagehide event.
Chapter 1: Introduction to Extensions - Archive of obsolete content
the add-ons manager handles the following tasks: safely installs and uninstalls add-ons makes sure add-ons are compatible with the version of firefox you're using manages a whitelist of sites trusted for installing add-ons helps troubleshoot add-ons by disabling them and offering a safe mode confirms and runs updates provides access to add-ons' settings dialogs provides access to add-ons' support sites development environment amenities initially, there wasn't adequate documentation available, and extension developers were largely left to fend for themselves1; howeve...
... extensions can add completely new features to firefox.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
figure 2 shows how setting align="center" pack="start" on two elements will result in completely different output with the only difference being the value for orient.
... var item = document.getelementbyid('menu-item-custom'); function handlecommandevent(aevent) { alert('ok'); item.removeeventlistener('command', handlecommandevent, false); item.parentnode.removechild(item); } item.addeventlistener('command', handlecommandevent, false); listing 11: additions and deletions using a dynamic event listener special menu items much like input elements in html, menuitem elements can ope...
Adding Events and Commands - Archive of obsolete content
<broadcasterset id="xulschoolhello-broadcasterset"> <broadcaster id="xulschoolhello-online-broadcaster" /> </broadcasterset> these elements are completely invisible, so you can put them anywhere.
... let onlinebroadcaster = document.getelementbyid("xulschoolhello-online-broadcaster"); onlinebroadcaster.setattribute("label", "something"); you can also have finer-grained control to this behavior by adding the observes element as a child to your observer node.
Adding menus and submenus - Archive of obsolete content
if your extension involves menus in any way, you should test it on mac os x to make sure everything works adequately.
...for example, you could have a menuitem that tells you the current time and is updated every second.
Adding windows and dialogs - Archive of obsolete content
you'll see that you can choose from a wide variety of buttons, associate any action you need to them, override their labels, and even add completely customized extra buttons.
...however, there are cases where the dialog contents are generated or expanded dynamically by your code, and you'll need to resize them appropriately.
Appendix A: Add-on Performance - Archive of obsolete content
}, how can you tell it works?
...this can be tricky for some add-ons, like ad or script blockers that need to check a whitelist or blacklist.
Appendix D: Loading Scripts - Archive of obsolete content
these tags are generally inserted into xul overlay files or other xul documents, after which they are automatically loaded into the context of the xul window in question and executed immediately and synchronously.
...problems can ensue if the script immediately attempts to access dom nodes.
Handling Preferences - Archive of obsolete content
the general philosophy in non-windows systems is that a change in a preference applies immediately.
...the element and its children are completely invisible, and their purpose is to list the preferences to be used in the window/pane.
Intercepting Page Loads - Archive of obsolete content
you can close the tab, redirect the tab to about:blank or another page, or tell the browser to stop loading this page, but in general you don't want to do this because it will be visible to the user and it will look like a bug.
...they may be useful in case you have most of your application logic in xpcom, or if you absolutely need a single point of inspection for loads.
Session store API - Archive of obsolete content
starting in firefox 3.5, notifications are sent after reading session store data and before using it, as well as immediately before writing it back to disk.
...this means that you cannot currently tell if a tab has been saved or restored.
Using the Stylesheet Service - Archive of obsolete content
in firefox 3, the changes take effect immediately, though some declarations (especially those affecting xul) won't work until a reload.
...@mozilla.org/content/style-sheet-service;1" in components.classes) { if(components.id('{41d979dc-ea03-4235-86ff-1e3c090c5630}') .equals(components.interfaces.nsistylesheetservice)) { // stylesheet service is available, but changes won't apply until reload // (firefox 1.5 and 2 behaviour) } else { // stylesheet service is available and changes will apply immediately // (firefox 3 behaviour) } } else { // stylesheet service is not available (pre-firefox 1.5 behaviour) } ...
Localizing an extension - Archive of obsolete content
we add to refreshinformation() the following code: var stringsbundle = document.getelementbyid("string-bundle"); var changestring = stringsbundle.getstring('changestring') + " "; var openstring = stringsbundle.getstring('openstring') + " "; var lowstring = stringsbundle.getstring('lowstring') + " "; var highstring = stringsbundle.getstring('highstring') + " "; var volumestring = stringsbundle.getstring('volumestring') + " "; this code gets a reference to the string bundle el...
...ement we added to stockwatcher2.xul by calling document.getelementbyid(), specifying the id "string-bundle".
Notes on HTML Reflow - Archive of obsolete content
the presentation shell does not process the command immediately.
...the purpose of the dirty reflow is to allow these individual reflows to be coalesced intelligently.
Visualizing an audio spectrum - Archive of obsolete content
<!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); } ...
...s before drawing spectrum ctx.clearrect(0,0, canvas.width, canvas.height); for (var i = 0; i < fft.spectrum.length; i++ ) { // multiply spectrum by a zoom value magnitude = fft.spectrum[i] * 4000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); // fft from dsp.js, see below var fft = function(buffersize, samplerate) { this.buffersize = buffersize; this.samplerate = samplerate; this.spectrum = new float32array(buffersize/2);...
Working with BFCache - Archive of obsolete content
the pagehide event tells you whether the page is going into bfcache; the pageshow tells you whether it's coming from bfcache.
...q: hmm, so what event tells me “you'll never get a pageshow so you can drop the megabytes of info you've saved in firebug side table for that page?” a: an observer notification with the topic "inner-window-destroyed" whose subject is an nsisupportspruint64 containing the window id of the inner window being destroyed.
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
the sections below tell you how to fetch, build and use the pluginhostctrl.dll .
... usage insert some html like this into your content: <object classid="clsid:dbb2de32-61f1-4f7f-beb8-a37f5bc24ee2" width="500" height="300"> <param name="type" value="video/quicktime"/> <param name="src" value="http://www.foobar.com/some_movie.mov"/> <!-- custom arguments --> <param name="loop" value="true"/> </object> the classid attribute tells ie to create an instance of the plug-in hosting control, the width and height specify the dimensions in pixels.
Creating a Firefox sidebar extension - Archive of obsolete content
the manifest also tells firefox that the extension has an overlay that needs to be merged into the browser.
...first, we need to tell firefox about your extension.
FAQ - Archive of obsolete content
unfortunately, yes.
...if a message appears in the preferences window telling you that it's an old skin, you're going to have to look over the code to see what changed.
Getting Started - Archive of obsolete content
css files the css files in these directories tell the browser how to display the buttons and other controls, where to put the images, what border and padding it should put around them, etc.
...<rdf:li resource="urn:mozilla:skin:myskin/1.0:communicator"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:editor"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:global"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:messenger"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:navigator"/> finally, in the last section of the contents.rdf file we need to tell mozilla what version this skin is compliant with.
In-Depth - Archive of obsolete content
the image that is listed there by default (chrome://navigator/skin/icons/btn1.gif) is actually a bunch of images grouped together in one file, so somewhere one of the css attributes is telling it what portion of the larger image to cut out and display.
...organizing images to organize all of your icons you can store them all in one image and then tell mozilla which portions to use.
Block and Line Layout Cheat Sheet - Archive of obsolete content
this is set by default for document, table cell inner, and absolutely positioned wrapper frames.
...this is set by default for document frames, area frames, table cell inner frames, absolutely positioned wrapper frames, and floated frames when the frame is created.
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
it immediately hands off to nsuriloader::openchannel.
...if it does so, we abort the entire dispatch process right here and cancel the necko request; we will not be getting a stream listener to stream data into, since the content handler has taken over completely.
Layout System Overview - Archive of obsolete content
in the case of the wysiwyg html editor, the user expects that the modifications they make to the document will appear immediately, not seconds later.
...frame construction is generally achieved by the use of stateless methods, but in some cases there is the need to provide context to frames created as children of a container.
JavaScript crypto - Archive of obsolete content
to enable your document to receive these events, you must first tell the crypto system you are interested by setting window.crypto.enablesmartcardevents to true.
...in fortezza cards pkcs11_mech_rc5_flag = 0x1<<7; pkcs11_mech_sha1_flag = 0x1<<8; pkcs11_mech_md5_flag = 0x1<<9; pkcs11_mech_md2_flag = 0x1<<10; pkcs11_mech_random_flag = 0x1<<27; //random number generator pkcs11_pub_readable_cert_flag = 0x1<<28; //stored certs can be read off the token w/o logging in pkcs11_disable_flag = 0x1<<30; //tell mozilla to disable this slot by default cipher flags reserved important for cryptomechanismflags 0x1<<11, 0x1<<12, ...
Monitoring downloads - Archive of obsolete content
onload: function() { // initialization code this.initialized = true; this.strings = document.getelementbyid("downloadlogger-strings"); this.dlmgr = components.classes["@mozilla.org/download-manager;1"] .getservice(components.interfaces.nsidownloadmanager); this.dlmgr.addlistener(downloadlogger); // open the database, placing its file in the profile directory this.dbfile = components.classes["@mozilla.org/file/directory_service;1"] .
...rofd", components.interfaces.nsifile); this.dbfile.append("downloadlogger.sqlite"); // get access to the storage service and open the database this.storageservice = components.classes["@mozilla.org/storage/service;1"] .getservice(components.interfaces.mozistorageservice); var dbconn = this.storageservice.opendatabase(this.dbfile); var loglist = document.getelementbyid("loglist"); var statement = dbconn.createstatement("select * from items"); // get all items in table try { while (statement.executestep()) { var row = document.createelement('listitem'); // add the cells to the row var cell = document.createelement('listcell'); var sourcestr = statement.getstring(0); row.setattribute("tooltiptext", sourc...
New Skin Notes - Archive of obsolete content
-- gandalf unfortunately the category styling is very much embedded into the mediawiki code.
...definitely need to fix for ie.
RDF Datasource How-To - Archive of obsolete content
more concretely, a datasource is a translator that can present information as a collection of rdf statements.
...the first question that you must answer is "should i use an existing vocabulary, or invent my own?" a reasonable answer is, "use an existing vocabulary unless you absolutely must invent your own." this will allow your datasource to be integrated with other datasources with a minimum of effort.
Remote XUL - Archive of obsolete content
however, there is a whitelist that lets you specify sites that can still use remote xul.
... the remote xul manager extension lets you manage this whitelist, which is maintained using nsipermissionmanager, by creating entries of type "allowxulxbl", like this: components.classes["@mozilla.org/permissionmanager;1"] .getservice(components.interfaces.nsipermissionmanager) .add(uri, 'allowxulxbl', components.interfaces.nsipermissionmanager.allow_action); see using remote xul.
Frequently Asked Questions - Archive of obsolete content
when servers send user agents an svg file they must tell the user agent that the file has the mime type "image/svg+xml", and if the svg file is stored gzipped they must tell the browser that too.
...this is either because your browser doesn't support svg (you must have mozilla firefox 1.5 or newer), or because the webpage/server isn't correctly telling mozilla that the file contains svg.
The life of an HTML HTTP request - Archive of obsolete content
the webshell then tells its documentloader to load (command "view") the specified url.
...the content sink tells the document about content model changes (notifybody()) in places like nshtmlcontentsink::willinterrupt() and nshtmlcontentsink::didbuildmodel().
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
0 : 1; } this is a completely correct (albeit trivial) program that will run predictably on all nspr platforms other than win-16.
...it's difficult to tell exaclty where the updated <tt>counter</tt> is being stored.
Using gdb on wimpy computers - Archive of obsolete content
however, you need to make sure that the base libraries like libc and pthreads are loaded before you tell gdb to stop loading shared libraries.
...there is absolutely no warranty for gdb.
Anonymous Content - Archive of obsolete content
dom methods that can be invoked on elements (e.g., getelementsbytagname) will only see nodes that are in the same scope.
... methods invoked on the document (e.g., getelementbyid) only see nodes that are at the document-level scope.
Binding Attachment and Detachment - Archive of obsolete content
var checkbox = document.getelementbyid("mycheckbox"); checkbox.style.mozbinding = "url(http://www.mozilla.org/xbl/htmlbindings.xml#checkbox)"; this attachment is not necessarily synchronous.
... scripts that invoke this method should not assume that the binding is installed immediately after this method returns.
Creating XPI Installer Modules - Archive of obsolete content
since we are not updating the mozilla ui to provide special access to this window (e.g., an item in the tasks menu or elsewhere), the measure of the success of the installation of the barley package is that the user can, as before, invoke our software by using a special startup option: mozilla -chrome chrome://barley/content this option tells mozilla to load a chrome other than the default, which is the main browser window.
...for a xpi file to be valid and installable, it must contain an installation script like the one above that tells mozilla xpinstall where to put the new resources and how to register them.
A XUL Bestiary - Archive of obsolete content
there are, unfortunately, different document object models corresponding to different types of documents and also to different proprietary notions about what in a document should be exposed programmatically.
...in fact, i'm not sure i understand them adequately myself, but here goes a simple explanation of events and of how they are used, basically, in a event-based interface like those created in xul.
id - Archive of obsolete content
ArchiveMozillaXULAttributeid
you can use this as a parameter to getelementbyid() and other dom functions and to reference the element in style sheets.
... example <button id="foo" label="click me" oncommand="dosomething()"/> <script> function dosomething(){ var mybutton = document.getelementbyid('foo'); mybutton.setattribute('label','the button was pressed'); } </script> a more abstract version of the above would be a <button id="foo" label="click me" oncommand="setwidgetlabel(this, 'i was pressed')"/> <script> function setwidgetlabel(idname, newcaption){ document.getelementbyid( idname.id ).setattribute('label',newcaption) } </script> not specifying the id attribute for a window or a prefwindow fills the console with the following warning message: warning: empty string passed to getelementbyid() see also name ...
label - Archive of obsolete content
see also treeitem.label, <label> element examples in javascript <label value="whaw" id="the-big-label" command="the-big-button"/> <button id="the-big-button" label="click me" oncommand="alert(document.getelementbyid('the-big-label').value)"/> <label id="mylabel" value="my label"/> <button label="click me" oncommand="document.getelementbyid('mylabel').setattribute('value','value changed');" /> <checkbox label="my checkbox" id="mycheckbox"/> <button label="another click" oncommand="document.getelementbyid('mycheckbox').setattribute('label','still not checked');"/> <button label="show label of chec...
...kbox" oncommand="alert( document.getelementbyid('mycheckbox').getattribute('label') )"/> ...
substate - Archive of obsolete content
before the element immediately before the splitter is collapsed.
... after the element immediately after the splitter is collapsed.
Methods - Archive of obsolete content
« xul reference home acceptdialog additemtoselection addpane addprogresslistener addsession addtab addtabsprogresslistener advance advanceselectedtab appendcustomtoolbar appendgroup appenditem appendnotification blur cancel canceldialog centerwindowonscreen checkadjacentelement clearresults clearselection click close collapsetoolbar contains decrease decreasepage docommand ensureelementisvisible ensureindexisvisible ensureselectedelementisvisible expandtoolbar extra1 extra2 focus getbrowseratindex getbrowserfordocument getbrowserfortab getbrowserindexfordocument getbutton getdefaultsession geteditor getelementsbyattribute getelementsbyattributens getformattedstring gethtmleditor getindexoffir...
... sizeto startediting stop stopediting swapdocshells syncsessions timedselect toggleitemselection related dom element methods dom:element.addeventlistener dom:element.appendchild dom:element.comparedocumentposition dom:element.dispatchevent dom:element.getattribute dom:element.getattributenode dom:element.getattributenodens dom:element.getattributens dom:element.getelementsbytagname dom:element.getelementsbytagnamens dom:element.getfeature fixme: brokenlink dom:element.getuserdata dom:element.hasattribute dom:element.hasattributens dom:element.hasattributes dom:element.haschildnodes dom:element.insertbefore dom:element.isequalnode dom:element.issamenode dom:element.issupported dom:element.lookupnamespaceuri dom:element.lookupprefix ...
Extensions - Archive of obsolete content
function init() { var contextmenu = document.getelementbyid("contentareacontextmenu"); if (contextmenu) contextmenu.addeventlistener("popupshowing", thumbnailsshowhideitems, false); } function thumbnailsshowhideitems(event) { var show = document.getelementbyid("thumbnail-show"); show.hidden = (document.popupnode.localname != "img"); } the init function should be called within the handler for the load event so that the popupshowing ev...
... function thumbnailsshowhideitems(event) { var show = document.getelementbyid("thumbnail-show"); show.hidden = !(gcontextmenu.onimage || gcontextmenu.onlink); } ...
Panels - Archive of obsolete content
for instance, using the search panel example above, we could add a button which closes the panel when pressed: <script> function dosearch() { document.getelementbyid("search-panel").hidepopup(); } </script> <toolbarbutton label="search" type="panel"> <panel id="search-panel" position="after_start"> <textbox id="search"/> <button label="search" oncommand="dosearch();"/> </panel> </toolbarbutton> in this example, the dosearch() function is called when the "search" button is pressed.
...for instance, to have the textbox initially focused in the example above: <panel id="search-panel" onpopupshown="document.getelementbyid('search').focus()"> to disable the adjusting of focus when a panel is opened, set the noautofocus attribute to true: <panel noautofocus="true"> this will cause the focus to remain on the element within the main window that has focus when the panel is opened.
Filtering - Archive of obsolete content
function applyfilter(country) { var cond = document.getelementbyid("cond"); var triple = document.getelementbyid("filtertriple"); if (country) { if (!triple) { triple = document.createelement("triple"); triple.id = "filtertriple"; triple.setattribute("subject", "?photo"); triple.setattribute("predicate", "http://www.xulplanet.com/rdf/country"); } triple.setattribute("object", country); cond.appendchild(triple)...
...; } else if (triple) { cond.removechild(triple); } document.getelementbyid("photoslist").builder.rebuild(); } the 'country' argument to the applyfilter function holds the value to filter by.
RDF Modifications - Archive of obsolete content
actually, internally, this isn't any different than the other notifications, but it is worth discussing separately.
...the template builder then rebuilds the template completely when done.
SQLite Templates - Archive of obsolete content
you would likely want to add an id to the param element so that the getelementbyid method may be used to refer to it.
...we could later change the age to use in the query with a short script: function adjustage(min, max) { document.getelementbyid("minage").textcontent = min; document.getelementbyid("maxage").textcontent = max; document.getelementbyid("friends").builder.rebuild(); } this function takes two arguments, the minimum and maximum values to use.
textbox (Toolkit autocomplete) - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
... related interfaces nsiaccessibleprovider, nsiautocompleteinput, nsidomxulmenulistelement articles how to implement custom autocomplete search component ...
The Joy of XUL - Archive of obsolete content
in practical terms, this enables developers to maintain one code stream for a given application, then apply custom branding or include special features for customers with a completely independent code base.
... fortunately, an implementation of the libical library was already available for macintosh so, with the cross platform nature of xpcom, a macintosh calendar implementation was working within a few days.
Things I've tried to do with XUL - Archive of obsolete content
this means that creating any sort of visual display (not necessarily "ui"; my use case is for creating a calendar time display) that sizes sanely when the user resizes the window is unfortunately very difficult.
...var available_width = document.getelementbyid("invisible_element").clientwidth; ...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
a simple document.getelementbyid('browsertoolbarpalette') will not work.
... the advantage to adding the toolbar button to the palette rather than creating an element and then appendchild to the toolbar (document.getelementbyid('nav-bar')) or appendchild to the addon bar (document.getelementbyid('addon-bar')) is that once in the toolbar palette, users can configure it through the customize menu.
Adding Labels and Images - Archive of obsolete content
</description> you can set the text via script using the textcontent property, as in the following example: <description id="text" width="200"/> document.getelementbyid('text').textcontent = "some lengthy word wrapped text goes here."; internally, both the label element and the description elements are the same.
...this element is appropriately named image.
Adding Properties to XBL-defined Elements - Archive of obsolete content
that way, all you need is to get a reference to the element (using document.getelementbyid or a similar function) and then get or set the additional properties and call the methods on it.
...xul: <box id="random-box" class="randomizer"/> <button label="generate" oncommand="document.getelementbyid('random-box').number=math.random();"/> <button label="show" oncommand="alert(document.getelementbyid('random-box').number)"/> xbl: <binding id="randomizer"> <implementation> <field name="number"/> </implementation> </binding> a number field has been defined in the binding, which stores the random number.
Custom Tree Views - Archive of obsolete content
function setview(){ document.getelementbyid('my-tree').view = treeview; } the following presents the example together.
...ion(row){ return false; }, isseparator: function(row){ return false; }, issorted: function(){ return false; }, getlevel: function(row){ return 0; }, getimagesrc: function(row,col){ return null; }, getrowproperties: function(row,props){}, getcellproperties: function(row,col,props){}, getcolumnproperties: function(colid,col,props){} }; function setview(){ document.getelementbyid('my-tree').view = treeview; } </script> <tree id="my-tree" flex="1"> <treecols> <treecol id="namecol" label="name" flex="1"/> <treecol id="datecol" label="date" flex="1"/> </treecols> <treechildren/> </tree> </window> in the image, you can see two columns, each with data taken from the getcelltext() function.
More Event Handlers - Archive of obsolete content
example 2 : source view <hbox id="outerbox"> <button id="okbutton" label="ok"/> </hbox> <script> function buttonpressed(event){ alert('button was pressed!'); } function boxpressed(event){ alert('box was pressed!'); event.stoppropagation(); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command',buttonpressed,true); var outerbox = document.getelementbyid("outerbox"); outerbox.addeventlistener('command',boxpressed,true); </script> here, an event listener has been added to the button and another event listener has been added to the box.
...here is an example which displays the current mouse coordinates: example 4 : source view <script> function updatemousecoordinates(e){ var text = "x:" + e.clientx + " y:" + e.clienty; document.getelementbyid("xy").value = text; } </script> <label id="xy"/> <hbox width="400" height="400" onmousemove="updatemousecoordinates(event);"/> in this example, the size of the box has been set explicitly so the effect is easier to see.
Property Files - Archive of obsolete content
var strbundle = document.getelementbyid("strings"); var nofilesfound=strbundle.getstring("notfoundalert"); alert(nofilesfound); this example first gets a reference to the bundle using its id then, it looks up the string 'notfoundalert' in the property file.
...var dir = "/usr/local/document"; var count = 10; var strbundle = document.getelementbyid("strings"); var result = strbundle.getformattedstring("resultmessage", [ dir, count ]); alert(result); this example will display following message in an alert box.
Splitters - Archive of obsolete content
set this to closest to have the element immediately to the left of the splitter resize.
...set this to closest to have the element immediately to the right of the splitter resize.
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
fortunately, xul provides a couple of built-in view implementations which do most of the hard work for you.
...in this example, the second column will be approximately twice as wide as the first column.
XPCOM Interfaces - Archive of obsolete content
an example is shown below: var bmarks = components.classes["@mozilla.org/browser/bookmarks-service;1"].getservice(); bmarks.queryinterface(components.interfaces.nsibookmarksservice); bmarks.addbookmarkimmediately("http://www.mozilla.org","mozilla",0,null); first, the component "@mozilla.org/browser/bookmarks-service;1" is retrieved and its service is placed in the variable bmarks.
...the function addbookmarkimmediately() provided by this interface can be used to add bookmarks.
Using Visual Studio as your XUL IDE - Archive of obsolete content
compared to a simple text-editor, visual studio gives you some special features when writing xul: intellisense / autocompletion for elements and attributes validation syntax coloring (okay, more sophisticated editors like notepad++ provide this as well) before you can use all of this, you have to adjust visual studio a little.
...using xml schemas for validation and intellisense visual studio needs the xml schema for xul files.
XULBrowserWindow - Archive of obsolete content
method overview boolean hidechromeforlocation(in string alocation); attributes attribute type description incontentwhitelist string[] an array of url strings for which chrome is automatically hidden.
...by default, chrome is hidden for about:addons and any other pages in the in content whitelist.
description - Archive of obsolete content
</description> this is a long section of text that will not word wrap <description value="this is a long section of text that will not word wrap"> </description> this is a long section of dynamically controlled text that will word wrap <description id="desc" style="width: 300px"></description> document.getelementbyid('desc').textcontent = "this is a long section of dynamic message text that will word wrap"; attributes crop type: one of the values below if the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
dialog - Archive of obsolete content
if it is set to true any changes to settings are supposed to be applied immediately.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
editor - Archive of obsolete content
ument, contentwindow, docshell, editingsession, editortype, webbrowserfind, webnavigation methods geteditor, gethtmleditor, makeeditable examples this example shows how to made the editor editable by setting the designmode property of the loaded html document: <script language="javascript"> function initeditor(){ // this function is called to set up the editor var editor = document.getelementbyid("myeditor"); editor.contentdocument.designmode = 'on'; } </script> <editor id="myeditor" editortype="html" src="about:blank" flex="1" type="content-primary"/> once editable, the document can have special formatting and other html pieces added to it using the document.execcommand method: var editor = document.getelementbyid("myeditor"); // toggle bold for the current selection ...
... inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
iframe - Archive of obsolete content
="http://mozilla.org" /> <menuitem label="slashdot" value="http://slashdot.org"/> <menuitem label="sourceforge" value="http://sf.net" /> <menuitem label="freshmeat" value="http://freshmeat.net"/> </menupopup> </menulist> <iframe id="myframe" flex="1"/> <script> function donav(obj) { var url = obj.selecteditem.value; // note the firstchild is the menupopup element document.getelementbyid('myframe').setattribute('src', url); } </script> attributes showcaret type: boolean whether or not to cause a typing caret to be visible in the content area.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
image - Archive of obsolete content
ArchiveMozillaXULimage
this would be useful if the images are stored remotely or you plan on swapping the image frequently.
..., ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
key - Archive of obsolete content
ArchiveMozillaXULkey
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
...for example: // modify some attributes let key = document.getelementbyid(key_id); key.setattribute("modifiers", "alt shift"); // apply the changes let keyset = document.getelementbyid(keyset_id); keyset.parentnode.appendchild(keyset); ...
listbox - Archive of obsolete content
el="ruby"/> <listitem label="emerald"/> <listitem label="sapphire" selected="true"/> <listitem label="diamond"/> </listbox> <listbox id="thelist" rows="10" width="400"> <listhead> <listheader label="1ct gem" width="240"/> <listheader label="price" width="150"/> </listhead> <listcols> <listcol/> <listcol flex="1"/> </listcols> </listbox> var thelist = document.getelementbyid('thelist'); gems = [ {gem: "ruby", price: "$3,500 - $4,600"}, {gem: "emerald", price: "$700 - 4,250"}, {gem: "blue sapphire", price: "$3,400 - $4,500"}, {gem: "diamond", price: "$5,600 - $16,000"} ]; for (var i = 0; i < gems.length; i++) { var row = document.createelement('listitem'); var cell = document.createelement('listcell'); cell.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
menuitem - Archive of obsolete content
this would be useful if the images are stored remotely or you plan on swapping the image frequently.
..., ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
menulist - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
... related elements menu, menubar, menuitem, menupopup, menuseparator interfaces nsiaccessibleprovider, nsidomxulmenulistelement ...
menupopup - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
...de(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() return type: no return value closes the popup immediately.
notificationbox - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
...if immediate is true, the messages are removed immediately.
panel - Archive of obsolete content
ArchiveMozillaXULpanel
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
...de(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() return type: no return value closes the popup immediately.
prefpane - Archive of obsolete content
methods domelement getpreferenceelement(in domelement startelement) preferenceforelement( uielement ) return type: preference element returns the preference element to which a user interface element is attached.
... inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
progressmeter - Archive of obsolete content
ties accessibletype, max, mode, value examples <progressmeter mode="determined" value="82"/> <progressmeter mode="undetermined"/> <!-- switching modes while the mouse is over a button --> <progressmeter mode="determined" id="myprogress"/> <button label="example" onmouseover="setloading(true)" onmouseout="setloading(false)"/> function setloading(state){ document.getelementbyid('myprogress').mode = (state) ?
..., ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbarbutton - Archive of obsolete content
this would be useful if the images are stored remotely or you plan on swapping the image frequently.
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
tooltip - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
...de(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() return type: no return value closes the popup immediately.
window - Archive of obsolete content
you can use this as a parameter to getelementbyid() and other dom functions and to reference the element in style sheets.
..., ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
wizard - Archive of obsolete content
nt, pageindex, pagestep, title, wizardpages methods advance, cancel, extra1, extra2, getbutton, getpagebyid, goto, rewind examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="thewizard" title="secret code wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkcode(){ document.getelementbyid('thewizard').canadvance = (document.getelementbyid('secretcode').value == "cabbage"); } </script> <wizardpage onpageshow="checkcode();"> <label value="enter the secret code:"/> <textbox id="secretcode" onkeyup="checkcode();"/> </wizardpage> <wizardpage> <label value="that is the correct secret code."/> </wizardpage> </wizard> attributes activetitlebarco...
... methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
Debugging a XULRunner Application - Archive of obsolete content
the easiest way to debug a xulrunner application is to get the system to tell you what's wrong!
...tors("myxulrunnerappwindowtype"); } debuggerserver.openlistener(6000); for xulrunner version 37+ the code to enable the debugger has changed: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); debuggerserver.addbrowseractors(); debuggerserver.allowchromeprocess = true; } let dbglistener=debuggerserver.createlistener(); dbglistener.portorpath=6000; dbglistener.open(); add the following to your prefs.js: (in recent ffox, edit about:config instead) pref("devtools.debugger.remote-enabled", true); in firefox, go to tools > web developer > connect...
Mozilla release FAQ - Archive of obsolete content
this list will be updated with time, but (according to netscape.public.mozilla.general) the following platforms have been built successfully: solaris 2.4, 2.5, 2.6 freebsd 2.2, 3.0 linux/intel and alpha 2.0, 2.1 macos winnt 4.0 irix 5.3, 6.2, 6.3, 6.4 win95, win98 digital unix 4.0 netbsd openbsd bsdi hp/ux 9.05, 10.20, 11.0 (see 2.7) hurd .03 dg/ux mac os x i'm *still* having problems getting mozilla to build on my platform!
...also, progressive display of the webpage would be completely gone with this idea.
2006-10-27 - Archive of obsolete content
on the same day cédric replied to axel's posting stating that he was going to forward a note to tristan separately.
... on the same day paul reed replied to cédric's posting by stating that they would like to close the directory before major releases but that unfortunately it wasn't that easy to do because the files must be readable, so mirrors can get the bits to serve them on the release day.
2006-10-20 - Archive of obsolete content
posted by jay patel on october 18th, 2006.
...posted by jay patel on october 18th, 2006.
NPN_GetURLNotify - Archive of obsolete content
it returns immediately and only later handles the request and calls npp_urlnotify().
... this notification is the only way the plug-in can tell whether a request with a null target failed, or that a request with a non-null target completed.
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
telling mozilla you support xembed as mentioned above, you will need to tell mozilla that you support the xembed protocol for hosting plugins.
... for backwards compatibility reasons if you don't tell mozilla that you support it it will try to hand you an xt widget as a parent.
SAX - Archive of obsolete content
an example implementation of the most commonly used content handler: function print(s) { dump(s + "\n"); } xmlreader.contenthandler = { // nsisaxcontenthandler startdocument: function() { print("startdocument"); }, enddocument: function() { print("enddocument"); }, startelement: function(uri, localname, qname, /*nsisaxattributes*/ attributes) { var attrs = []; for(var i=0; i<attributes.length; i++) { attrs.push(attributes.getqname(i) + "='" + attributes.getvalue(i) + "'"); } print("startelement: namespace='" + uri + "', localname='" + localname + "', qname='" + qname + "', attributes={" + attrs.join(",") +...
...below is an example of parsing from a string: xmlreader.parsefromstring("<f:a xmlns:f='g' d='1'><bbq/></f:a>", "text/xml"); this call results in the following output (assuming the content handler from the example above is used): startdocument startelement: namespace='g', localname='a', qname='f:a', attributes={d='1'} startelement: namespace='', localname='bbq', qname='bbq', attributes={} endelement: namespace='', localname='bbq', qname='bbq' endelement: namespace='g', localname='a', qname='f:a' enddocument ...
Security - Archive of obsolete content
but encryption and decryption, by themselves, do not address another problem: tampering.encryption and decryptionencryption is the process of transforming information so it is unintelligible to anyone but the intended recipient.
... decryption is the process of transforming encrypted information so that it is intelligible again.introduction to public-key cryptographypublic-key cryptography and related standards and techniques underlie the security features of many products such as signed and encrypted email, single sign-on, and secure sockets layer (ssl) communications.
Solaris 10 Build Prerequisites - Archive of obsolete content
fortunately, it also isn't necessary, so you can fix this problem by simply removing the reference to that package from the installer script (cbe-install).
... the installer may tell you your c compiler is not the recommended compiler, but the compiler you installed will work fine, so you should tell the installer to use the compiler anyway.
Table Reflow Internals - Archive of obsolete content
absolutely positioned elements) reflows reflowee and passes a reflow state (in) and a reflow metrics (in/out) review of reflow the reflow state: is a node in a tree structurally equivalent to the frame tree of reflow participants contains: reflow type, avail size, various computed values, resolved style structs possible request for preferred size and more.
...when a target is the cell or below and the cell changes size, the row tells the table so it can decide if it needs to rebalance when a target is inside the cell's block, the cell requests max element, preferred sizes of its block in case they change after the table reflows the row group(s) containing the targets, if it rebalances, it then does a pass 2 reflow.
Common Firefox theme issues and solutions - Archive of obsolete content
this document was started on july 27, 2012 so it will take some time to completely fill in and some issues still need to have solutions written for them.
... */ #inspector-treepanel-toolbutton { list-style-image: url("chrome://browser/skin/devtools/treepanel-button.png"); -moz-margin-end: 0; -moz-image-region: rect(0px 18px 16px 0px); } /* highlighter toolbar */ #inspector-inspect-toolbutton { list-style-image: url("chrome://browser/skin/devtools/inspect-button.png"); -moz-image-region: rect(0px 16px 16px 0px); } style inspector is completely unstyled the style inspector that is part of firefox 10 and later needs to be styled.
Theme changes in Firefox 2 - Archive of obsolete content
the ends of the bar are now skinned separately.
... #sitelabel style information for the site label.
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
that's because there's nothing telling those two applications what to do with the chrome provided by the extension.
...as you may (or may not) recall, that file tells the application what xul code your extension's interface needs to overlay onto.
CSS - Archive of obsolete content
ArchiveWebCSS
normally, a <xul:stack> will change its size so that all of its child elements are completely visible.
...this is important in that it provides a natural way to tell several voices apart, as each can be positioned to originate at a different location on the sound stage.
The global XML object - Archive of obsolete content
this property tells e4x to ignore comment nodes when serializing and filtering.
...this property tells e4x to ignore processing instructions in xml when serializing and filtering.
Debug.write - Archive of obsolete content
the debug.write function is almost identical to the debug.writeln function.
... the only difference is that the debug.writeln function sends a newline character after the strings are sent.
Debug - Archive of obsolete content
in windows 8.x store apps, the write and writeln functions of the debug object display strings in the visual studio output window at run time.
... debug.writeln sends strings to the script debugger, followed by a newline character.
Archived JavaScript Reference - Archive of obsolete content
you can use the more general proxy object instead.arraybuffer.transfer()the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
... if newbytelength is undefined, the bytelength of the oldbuffer is used.
Sharp variables in JavaScript - Archive of obsolete content
form sharp variables have the form of a sharp sign (#) immediately followed by one or more digits.
... #1 = {}; // this doesn't do much since the sharp variable is out of scope immediately after a = #2 = {}; // slightly more useful since we retain a reference to the new object to reference the sharp variable, simply append another sharp (#) to the end of the variable name.
Mozilla XForms Specials - Archive of obsolete content
information about how to whitelist domain can be found in the release notes the cross domain check also includes forms loaded from file://.
...so there is not automatic "whitelisting" of local files.
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
for example, if an organization is developing a web-based client, they may have to adhere to standards imposed by these organizations: ansi (american national standards institute ) atsc (advanced television systems committee ) ieee (institute of electrical and electronics engineers ) ietf (internet engineering task force ) irtf (internet research task force ) iso (international standards organization ) itu (international telecommunication union ) oasis (organization for the advancement of structured information standards ) oma (open mobile alliance ), uni (unicode consortium ) w3c (w...
...however, when mac os x was released, apple completely revamped the interface and desktop metaphor.
Displaying a graphic with audio samples - Archive of obsolete content
html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <img id="mozlogo" style="display:none" src="mozilla2.png"></img> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); ...
....fillrect (0,0, canvas.width, canvas.height); ctx.fillstyle = "rgb(255,255,255)"; for (var i = 0; i < signal.length; i++ ) { // multiply spectrum by a zoom value magnitude = signal[i] * 1000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } ctx.drawimage(document.getelementbyid('mozlogo'),0,0, canvas.width, canvas.height); } var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); </script> </body> </html> ...
Fixing Incorrectly Sized List Item Markers - Archive of obsolete content
the solution fortunately, there are mozilla-specific css-like rules that can be used to correct both problems.
... the following rule is derived from mozilla's html.css file: *|*:-moz-list-bullet, *|*:-moz-list-number {font-size: 1em;} this rule tells gecko-based browsers to use the computed value of font-size for the marker's parent, which is the list item itself.
The Business Benefits of Web Standards - Archive of obsolete content
while some browsers have quirks that cause different behavior by platform, mozilla-based browsers are designed to behave identically on all supported platforms (mac, linux, unix, windows...) web content is increasingly being accessed by a growing number of user agents other than browsers, or by browsers on different platforms - for example mobile telephones.
...ultimately that better user experience delivers the business or operational objectives of the site.
Windows Media in Netscape - Archive of obsolete content
fortunately, windows media player also fires a scriptcommand() event for closed captioning, which means content may update the caption manually with a small piece of javascript.
...instead of doing that, this is the recommendation and workaround for netscape 7.1: <script for="player" event="scriptcommand(type, param)"> if (type == "text") { var cap = document.getelementbyid("captext"); cap.innerhtml = param; } </script> more detailed examples are available in the final section on examples and sample code.
Common causes of memory leaks in extensions - Extensions
all zombie compartments in extensions are caused by a failure to release resources appropriately in certain circumstances, such as when a window is closed, a page unloads, or an extension is disabled or removed.
... consider the following example: var myobserver = { observe: function(subject, topic, data) { window.document.documentelement.setattribute( "pbm", (data == "enter") ?
Index - Game development
fortunately, i do not have any experience with this, but i have heard it is an excruciating game of whack-a-mole.
... 68 paddle and keyboard controls beginner, canvas, controls, games, graphics, javascript, tutorial, keyboard the ball is bouncing off the walls freely and you can watch it indefinitely, but currently there's no interactivity.
Bounding volume collision detection with THREE.js - Game development
var knot = new three.mesh( new three.torusknotgeometry(0.5, 0.1), new meshnormalmaterial({})); var knotbsphere = new sphere( knot.position, knot.geometry.boundingsphere.radius); unfortunately, there is no equivalent of box3.setfromobject for sphere instances.
...box3 unfortunately this test is not implemented in three.js, but we can patch sphere to implement a sphere vs.
Building up a basic demo with Babylon.js - Game development
ml structure here's the html structure we will use: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: babylon.js demo</title> <style> html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <body> <script src="babylon.js"></script> <canvas id="render-canvas"></canvas> <script> var canvas = document.getelementbyid("render-canvas"); /* all our javascript code goes here */ </script> </body> </html> it contains some basic information like the document <title>, and some css to set the width and height of the <canvas> element (which babylon.js will use to render the content on) to fill the entire available viewport space.
... var renderloop = function () { scene.render(); }; engine.runrenderloop(renderloop); we're using the engine's runrenderloop() method to execute the renderloop() function repeatedly on every frame — the loop will continue to render indefinitely until told to stop.
Building up a basic demo with the PlayCanvas engine - Game development
<!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: playcanvas demo</title> <style> body { margin: 0; padding: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <script src="playcanvas-latest.js"></script> <canvas id="application-canvas"></canvas> <script> var canvas = document.getelementbyid("application-canvas"); /* all our javascript code goes here */ </script> </body> </html> it contains some basic information like the document <title>, and some css to set the width and height of the <canvas> element that playcanvas will use to 100% so that it will fill the entire available viewport space.
... the cube is visible, but it is completely.
GLSL Shaders - Game development
applying the shaders to actually apply the newly created shaders to the cube, comment out the basicmaterial definition first: // var basicmaterial = new three.meshbasicmaterial({color: 0x0095dd}); then, create the shadermaterial: var shadermaterial = new three.shadermaterial( { vertexshader: document.getelementbyid( 'vertexshader' ).textcontent, fragmentshader: document.getelementbyid( 'fragmentshader' ).textcontent }); this shader material takes the code from the scripts and applies it to the object the material is assigned to.
... height); renderer.setclearcolor(0xdddddd, 1); document.body.appendchild(renderer.domelement); var scene = new three.scene(); var camera = new three.perspectivecamera(70, width/height); camera.position.z = 50; scene.add(camera); var boxgeometry = new three.boxgeometry(10, 10, 10); var shadermaterial = new three.shadermaterial( { vertexshader: document.getelementbyid( 'vertexshader' ).textcontent, fragmentshader: document.getelementbyid( 'fragmentshader' ).textcontent }); var cube = new three.mesh(boxgeometry, shadermaterial); scene.add(cube); cube.rotation.set(0.4, 0.2, 0); function render() { requestanimationframe(render); renderer.render(scene, camera); } render(); css body { margin: 0; paddi...
Unconventional controls - Game development
this approach won't give us the full flexibility of using a gamepad, or even leap motion, but it's definitely an interesting, unconventional alternative.
... makey makey if you want to go completely bananas you can use makey makey, a board that can turn anything into a controller — it's all about connecting real-world, conductive objects to a computer and using them as touch interfaces.
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
networking and communications asynchronous communication is a method of exchanging messages between two or more parties in which each party receives and processes messages whenever it's convenient or possible to do so, rather than doing so immediately upon receipt.
...for example, the ajax (asynchronous javascript and xml) programming technique—now usually simply "ajax", even though json is usually used rather than xml in modern applications—is a mechanism that requests relatively small amounts of data from the server using http, with the result being returned when available rather than immediately.
DTMF (Dual-Tone Multi-Frequency signaling) - MDN Web Docs Glossary: Definitions of Web-related terms
few telephone keypads include the letters, which are typically used for control signaling by the telephone network.
... computers may make use of dtmf when dialing a modem, or when sending commands to a menu system for teleconferencing or other purposes.
Function - MDN Web Docs Glossary: Definitions of Web-related terms
function loop(x) { if (x >= 10) return; loop(x + 1); }; //using ecmascript 2015 arrow notation const loop = x => { if (x >= 10) return; loop(x + 1); }; an immediately invoked function expressions (iife) is a function that is called directly after the function is loaded into the browser’s compiler.
... // declared functions can't be called immediately this way // error (https://en.wikipedia.org/wiki/immediately-invoked_function_expression) /* ​function foo() { console.log('hello foo'); }(); */ // function expressions, named or anonymous, can be called immediately (function foo() { console.log("hello foo"); }()); (function food() { console.log("hello food"); })(); (() => console.log('hello world'))(); if you'd like to know more about iifes, check out the following page on wikipedia : immediately invoked function expression learn more technical reference functions arrow functions ...
ITU - MDN Web Docs Glossary: Definitions of Web-related terms
the international telecommunication union (itu) is the organization authorized by the united nations to establish standards and rules for telecommunication, including telegraph, radio, telephony and the internet.
... in the internet age, the itu's role of establishing standards for video and audio data formats used for streaming, teleconferencing, and other purposes.
Request header - MDN Web Docs Glossary: Definitions of Web-related terms
a few request headers after a get request: get /home.html http/1.1 host: developer.mozilla.org user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language: en-us,en;q=0.5 accept-encoding: gzip, deflate, br referer: https://developer.mozilla.org/testpage.html connection: keep-alive upgrade-insecure-requests: 1 if-modified-since: mon, 18 jul 2016 02:36:04 gmt if-none-match: "c561c68d0ba92bbeb8b0fff2a9199f722e3a62...
...1a" cache-control: max-age=0 strictly speaking, the content-length header in this example is not a request header like the others, but an entity header: post /myform.html http/1.1 host: developer.mozilla.org user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 content-length: 128 learn more technical knowledge list of all http headers ...
VoIP - MDN Web Docs Glossary: Definitions of Web-related terms
it is also known as ip telephony, or broadband telephony.
...usually, telephone calls over the internet do not incur further charges beyond what the user is paying for internet access, much in the same way that the user doesn't pay for sending individual emails over the internet.
Application Context - MDN Web Docs Glossary: Definitions of Web-related terms
if an application context is created as a result of the user agent being asked to navigate to a deep link, the user agent must immediately navigate to the deep link with replacement enabled.
... otherwise, when the application context is created, the user agent must immediately navigate to the start url with replacement enabled.
MDN Web Docs Glossary: Definitions of Web-related terms
server timing session hijacking sgml shadow tree shim signature signature (functions) signature (security) simd simple header simple response header sisd site site map sld sloppy mode slug smoke test smpte (society of motion picture and television engineers) smtp snap positions soap spa (single-page application) specification speculative parsing speed index sql sql injection sri stacking context state machine statement static method static typing strict mode string stun ...
... style origin stylesheet svg svn symbol symmetric-key cryptography synchronous syntax syntax error synthetic monitoring t tag tcp tcp handshake tcp slow start telnet texel thread three js time to first byte time to interactive tld tofu transmission control protocol (tcp) transport layer security (tls) tree shaking trident truthy ttl turn type type coercion type conversion u udp (user datagram protocol) ui undefined unicode uri ur...
Test your skills: CSS and JavaScript accessibility - Learn web development
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.
Accessible multimedia - Learn web development
for example, some users may not be able to hear the audio because they are in noisy environments (like a crowded bar when a sports game is being shown) or might not want to disturb others if they are in a quiet place (like a library.) this is not a new concept — television services have had closed captioning available for quite a long time: whereas many countries offer english films with subtitles written in their own native languages, and different language subtitles are often available on dvds, for example there are different types of text track with different purposes.
...furthermore, use srclang to tell the browser what language you have written the subtitles in.
Backgrounds and borders - Learn web development
you can also use keywords: cover — the browser will make the image just large enough so that it completely covers the box area while still retaining its aspect ratio.
... the value of background-size may only be included immediately after background-position, separated with the '/' character, like this: center/80%.
Attribute selectors - Learn web development
[attr|=value] div[lang|="zh"] matches elements with an attr attribute whose value is exactly value or begins with value immediately followed by a hyphen.
...this flag tells the browser to match ascii characters case-insensitively.
Sizing items in CSS - Learn web development
this technique is used to make images responsive, so that when viewed on a smaller device they scale down appropriately.
...images should be appropriately sized to be no larger than they need to be for the largest size they are displayed in the design.
Styling tables - Learn web development
unfortunately, it doesn't look good when rendered on the screen (see it live at punk-bands-unstyled.html): with only the default browser styling it looks cramped, hard to read, and boring.
...yes, we could have put both the background image and the linear gradient on the <thead> and <tfoot> elements using multiple background images, but we decided to do it separately for the benefit of older browsers that don't support multiple background images or linear gradients.
The box model - Learn web development
by doing this you are telling the browser to take the border box as the area defined by any size you set.
...try changing this to display: block or removing the line completely to see the difference in display models.
Beginner's guide to media queries - Learn web development
media query basics the simplest media query syntax looks like this: @media media-type and (media-feature-rule) { /* css rules go here */ } it consists of: a media type, which tells the browser what kind of media this code is for (e.g.
... to remedy this, including a viewport meta tag like the one above on your page tells the browser "don't render the content with a 960 pixel viewport — render it using the real device width instead, and set a default initial scale level for better consistency." the media queries will then kick in as expected.
Supporting older browsers - Learn web development
this is straightforward if you have an existing website which you are adding to or replacing, as you probably have analytics available which can tell you the technology people are using.
...browsers that do not support grid, and do not support the feature query will use that layout information they can understand and completely ignore everything else.
Getting started with CSS - Learn web development
adding css to our document the very first thing we need to do is to tell the html document that we have some css rules we want it to use.
... to link styles.css to index.html add the following line somewhere inside the <head> of the html document: <link rel="stylesheet" href="styles.css"> this <link> element tells the browser that we have a stylesheet, using the rel attribute, and the location of that stylesheet as the value of the href attribute.
How CSS is structured - Learn web development
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.
...it is completely ignored by the browser's css engine.
CSS FAQ - Learn web development
LearnCSSHowtoCSS FAQ
it is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for 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.
...for example, many developers only using the -webkit- prefixed version of a property when the non-prefixed version is supported across all browsers meant that a feature relying on that property would break in non-webkit-based browsers, completely needlessly.
Learn to style HTML using CSS - Learn web development
however, doing so isn't absolutely necessary as much of what is covered in the css basics article is also covered in our css first steps module, albeit in a lot more detail.
...you should definitely start with the first one.
What do common web layouts contain? - Learn web development
in fact, everything not absolutely required by the page's main content.
...the way the curve of the header's menu ties in with the curve at the bottom of the image, the header and main content look like one thing even though they're technically completely different.
How can we design for all types of users? - Learn web development
for instance, if in your css you declare this: body { font-size:16px; } … you are telling the browser that whatever happens, the font size must be 16 pixels.
... relative units are expressed in em, % and rem: percent-based sizes: % this unit tells your browser that an element's font size must be n% of the previous element whose font size was expressed.
How do I use GitHub Pages? - Learn web development
here's what you'd type if you've put your website in a directory called test-site on your desktop: cd desktop/test-site when the command line is pointing inside your website directory, type the following command, which tells the git tool to turn the directory into a git repository: git init an aside on command line interfaces the best way to upload your code to github is via the command line — this is a window where you type in commands to do things like create files and run programs, rather than clicking inside a user interface.
...you tell the computer to do something in the terminal by typing in a command and hitting enter, as seen above.
What is a URL? - Learn web development
deeper dive basics: anatomy of a url here are some examples of urls: https://developer.mozilla.org https://developer.mozilla.org/docs/learn/ https://developer.mozilla.org/search?q=url any of those urls can be typed into your browser's address bar to tell it to load the associated page (resource).
...so in this example, we really want to reach this url: https://developer.mozilla.org/docs/learn/skills/infrastructure/understanding_urls going back in the directory tree ../css/display in this case, we use the ../ writing convention — inherited from the unix file system world — to tell the browser we want to go up from one directory.
What is a web server? - Learn web development
http is a textual, stateless protocol.
... stateless neither the server nor the client remember previous communications.
Basic native form controls - Learn web development
other text input types, like search, url, and tel, were added with html5.
...the associated <label> is generally placed immediately after the radio button or checkbox, with the instructions for the group of radio button or checkboxes generally being the content of the <legend>.
Sending form data - Learn web development
this header is very important because it tells the server what kind of data is being sent.
...store them on a different server and allow access to the file only through a different subdomain or even better through a completely different domain.
Dealing with files - Learn web development
an aside on casing and spacing you'll notice that throughout this article, we ask you to name folders and files completely in lowercase with no spaces.
...we need to tell the html where the image is.
JavaScript basics - Learn web development
for example, the alert() function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what message to display.
...for example: multiply(4, 7); multiply(20, 20); multiply(0.5, 3); note: the return statement tells the browser to return the result variable out of the function so it is available to use.
Marking up a letter - Learn web development
inline semantics the names of the sender and receiver (and tel and email) should be marked up with strong importance.
... the six sub/superscripts should be marked up appropriately — in the chemical formulae, and the numbers 103 and 104 (they should be 10 to the power of 3 and 4, respectively).
Adding vector graphics to the Web - Learn web development
here's a quick review: <iframe src="triangle.svg" width="500" height="500" sandbox> <img src="triangle.png" alt="triangle with three unequal sides" /> </iframe> this is definitely not the best method to choose: cons iframes do have a fallback mechanism, as you can see, but browsers only display the fallback if they lack support for iframes altogether.
...g> </textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="show solution" 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.queryselector('.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; sol...
Structuring the web with HTML - Learn web development
it is recommended that you work through getting started with the web before attempting this topic, however, it isn't absolutely necessary; much of what is covered in the html basics article is also covered in our introduction to html module, albeit in a lot more detail.
...you should definitely start with the first one.
Choosing the right approach - Learn web development
we then run it once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date = new date(); let time = date.tolocaletimestring(); document.getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); pitfalls the frame rate isn't optimized for the system the animation is running on, and can be somewhat inefficient.
... further information cooperative asynchronous javascript: timeouts and intervals, in particular requestanimationframe() requestanimationframe() reference promises promises are a javascript feature that allows you to run asynchronous operations and wait until it is definitely complete before running another operation based on its result.
Introduction to events - Learn web development
previous overview: building blocks next events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired.
...if they are, we call the preventdefault() function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong: const form = document.queryselector('form'); const fname = document.getelementbyid('fname'); const lname = document.getelementbyid('lname'); const para = document.queryselector('p'); form.onsubmit = function(e) { if (fname.value === '' || lname.value === '') { e.preventdefault(); para.textcontent = 'you need to fill in both names!'; } } obviously, this is pr...
Introduction to web APIs - Learn web development
examples include telling the user that a useful update is available on a web app via system notifications (see the notifications api) or vibration hardware (see the vibration api).
... the telegram apis allows you to embed content from telegram channels on your website, in addition to providing support for bots.
Third-party APIs - Learn web development
they are found on third-party servers browser apis are built into the browser — you can access them from javascript immediately.
...try this, for example: map.addcontrol(l.mapquest.control({ position: 'bottomright' })); there are other types of control available, for example mapquest.searchcontrol() and mapquest.satellitecontrol(), and some are quite complex and powerful.
Adding features to our bouncing balls demo - Learn web development
remember to set the ball() constructor's prototype and constructor appropriately.
... for a bonus point, can you tell us why we've had to set let _this = this; in the position it is in?
Inheritance in JavaScript - Learn web development
to create a subclass we use the extends keyword to tell javascript the class we want to base our class on, class teacher extends person { constructor(subject, grade) { this.subject = subject; this.grade = grade; } } but there's a little catch.
... ultimately, objects are just another form of code reuse, like functions or loops, with their own specific roles and advantages.
Working with JSON - Learn web development
"name": "madame uppercut", "age": 39, "secretidentity": "jane wilson", "powers": [ "million tonne punch", "damage resistance", "superhuman reflexes" ] }, { "name": "eternal flame", "age": 1000000, "secretidentity": "unknown", "powers": [ "immortality", "heat immunity", "inferno", "teleportation", "interdimensional travel" ] } ] } if we loaded this object into a javascript program, parsed in a variable called superheroes for example, we could then access the data inside it using the same dot/bracket notation we looked at in the javascript object basics article.
... we have wrapped the code in an event handler that runs when the load event fires on the request object (see onload) — this is because the load event fires when the response has successfully returned; doing it this way guarantees that request.response will definitely be available when we come to try to do something with it.
Object building practice - Learn web development
drawing the ball first add the following draw() method to the ball()'s prototype: ball.prototype.draw = function() { ctx.beginpath(); ctx.fillstyle = this.color; ctx.arc(this.x, this.y, this.size, 0, 2 * math.pi); ctx.fill(); } using this function, we can tell the ball to draw itself onto the screen, by calling a series of members of the 2d canvas context we defined earlier (ctx).
... immediately inside the for loop, we use an if statement to check whether the current ball being looped through is the same ball as the one we are currently checking.
What is web performance? - Learn web development
the download of additional assets linked to from the index file is generally sequential, based on source order, but this can be manipulated and should definitely be optimized, realizing that some resources block additional downloads until their content is parsed and executed.
...next up we'll look at perceived performance, and how you can use some clever techniques to make some unavoidable performance hits appear less severe to the user, or disguise them completely.
Multimedia: video - Learn web development
this is a useful option for some small or moderately sized files.
... changing the setting to auto tells the browser to automatically download the entire video.
The "why" of web performance - Learn web development
at its worst, bad performance causes content to be completely inaccessible.
...good performance may not be obvious to most site visitors, but most will immediately recognize a sluggish site.
Getting started with Ember - Learn web development
developers are then more easily able to switch between projects and applications without having to completely relearn the architecture, patterns, conventions, etc.
... finally, find app.css, located at app/styles/app.css, and paste in the following: :focus, .view label:focus, .todo-list li .toggle:focus + label, .toggle-all:focus + label { /* !important needed because todomvc styles deliberately disable the outline */ outline: #d86f95 solid !important; } this css overrides some of the styles provided by the todomvc-app-css npm package, therefore allowing keyboard focus to be visible.
Componentizing our React app - Learn web development
the final line of src/index.js should read like this: reactdom.render(<app tasks={data} />, document.getelementbyid("root")); this array is now available to the app component as props.tasks.
... note: all_caps constant names have no special meaning in javascript; they’re a convention that tells other developers "this data will never change after being defined here”.
Working with Svelte stores - Learn web development
with $: onmessagechange($alert, ms) we tell svelte to run this function whenever the $alert store or the ms prop changes.
...app.svelte is completely transparent in terms of what kind of store we are using.
Rendering a list of Vue components - Learn web development
to make sure it is re-using list elements appropriately, it needs a unique "key" on the same element that you attach v-for to.
... to make sure that vue can accurately compare the key attributes, they need to be string or numeric values.
Implementing feature detection - Learn web development
give it the following contents: const conditional = document.queryselector('.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.
...cript inside the tags: if (modernizr.geolocation) { navigator.geolocation.getcurrentposition(function(position) { let latlng = new google.maps.latlng(position.coords.latitude,position.coords.longitude); let myoptions = { zoom: 8, center: latlng, maptypeid: google.maps.maptypeid.terrain, disabledefaultui: true } let map = new google.maps.map(document.getelementbyid("map_canvas"), myoptions); }); } else { const para = document.createelement('p'); para.textcontent = 'argh, no geolocation!'; document.body.appendchild(para); } try your example out!
Client-side tooling overview - Learn web development
linters linters are tools that check through your code and tell you about any errors that are present, what error types they are, and what code lines they are present on.
... there's definitely no silver bullet that will guarantee success with tools, but as your experience increases you'll find workflows that work for you or for your team and their projects.
Package management basics - Learn web development
sure there's some calculation, but we definitely don’t need 195k worth of javascript to do this!.
... dist/my-project.86f8a5fc.js 10.34 kb 7.17s dist/index.html 288 b 753ms now the bundle is approximately 10k.
Accessibility API cross-reference
n/a accessible_active_descendant_property aria-activedescendant critical info to convey immediately alert_high n/a n/a aria-live=assertive info that's important, but does not require immediacy alert_medium n/a n/a aria-live=polite low-priority info such as a tip or hint alert_low n/a n/a n/a this object is changing or moving rapidly animated n/a n/a n/a ...
...e care of text-to-speech on its own selfvoicing n/a n/a object can be resized n/a resizable resizable this object and all of its ancestors are visible n/a showing showing this text object can only contain 1 line of text n/a single_line single_line tells accessibility aid "don't add event listener - this object doesn't generate any".
Accessible Toolkit Checklist
since the individual widgets predominately come from the operating system, they already implement standard keyboard commands and follow the operating system's visual theme.
...this is one reason why a label must be created together with each widget, rather than separately.
A bird's-eye view of the Mozilla framework
the client is completely unaware of which c++ class (or other language) actually implements nsirdfnode; it only interacts with the idl interface.
... var toctree = document.getelementbyid("help-toc-panel"); the document object is a xuldocument, and toctree is thecontents panel xulelement.
Testopia
despite bugzilla 5.0 has already been released a few months ago, we don't plan to release a fix for testopia immediately, because it's currently under heavy work to make testopia a fully self-contained extension, which means that all tr_*.cgi scripts which are currently in the bugzilla/ root directory are being moved into extensions/testopia/lib/.
...also, future versions may remove this support completely.
What to do and what not to do in Bugzilla
when marking it wfm you should tell the bug reporter that they should reopen the bug if they can still see it with a recent build.
... note: because of how duplicate detection works in bugzilla, you should try not to verify bugs immediately after they're marked fixed; instead, let a little time pass first.
HTTP logging
if you've put it elsewhere, change the path used on the third line appropriately.) reproduce whatever problem you're trying to debug.
... this will cause each log message to be immediately written (and fflush()'d), which is likely to give us more information about your crash.
Configuring Build Options
parallel compilation note: the build system automatically makes an intelligent guess for how many cpu cores to use when building.
...you will see (diminishing) returns up to a value approximately 1.5× to 2.0× the number of cores on your system.
Reviewer Checklist
[fennec: if your custom view does animations, it's better to clean up runnables in ondetachfromwindow().] ensure all file handles and other closeable resources are closed appropriately.
... adequately document any potentially confusing pieces of code.
Multiple Firefox profiles
it takes little time to set up a new profile, and once it is complete, all of your firefox versions will update separately and can be run simultaneously.
... this will launch firefox immediately.
Limitations of frame scripts
for example: nsifileinputstream nsifileoutputstream constructing a file from a string or nsifile (but file objects can be sent via message manager) htmlinputelement.mozsetfilenamearray (alternative: mozsetfilearray) file: uris, see bug 1187099 <...> xul and browser ui anything that tries to touch the browser ui or anything to do with xul is likely not to work in the content process.
...by default, about: pages (except for a small whitelist) are loaded in the chrome process when browsed to from the awesomebar.
Message manager overview
if you load a frame script using the global frame message manager, the script gets loaded separately into every open tab: three times, in the diagram above.
...if you load a frame script using the window message manager it gets loaded separately into each tab open in that particular window.
Security best practices for Firefox front-end engineers
the canonical truth for the list of whitelisted elements is the source code.
... appendix list of disallowed dom apis innerhtml outerhtml insertadjacenthtml() createcontextualfragment() document.write() document.writeln() please take a look at the repository for an updated list ...
Hacking with Bonsai
use the bonsai query tool to see what's been checked in to the tree lately and to look at differences between versions.
...you are either at your desk, or pageable, checking e-mail constantly, or on irc so that you can be found immediately and can respond to any problems in your code.
Integrated Authentication
on older versions of windows this hash is computed using a relatively weak algorithm (see hertel for more info on ntlm authentication).
... mozilla currently supports a whitelist of sites that are permitted to engage in spnego authentication with the browser.
JavaScript Tips
similarly prefer document.getelementsbytagname(atag).item(0) != null to document.getelementsbytagname(atag).length > 0.
... xul also maps the class attribute, but unfortunately class is a reserved identifier, so the property is named classname.
Add-on Manager
the callbacks may be called immediately while the initial function is still executing or shortly after, depending on when the requested data becomes available.
...it must be passed an updatelistener to receive information about compatibility information and new update information.
Download
you can use the downloadtarget.size property to get the actual size of the completely-downloaded file once the download has succeeded.
... if the cancel() method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then restarts the download immediately.
Promise
for example, the os.file.exists function returns a promise that will eventually fulfill with a boolean: promise<boolean> exists(string path); the rejection reason may be specified separately in the function's documentation, and is considered to be an error object unless otherwise specified.
... new promise(executor); parameters executor this function is invoked immediately with the resolving functions as its two arguments: executor(resolve, reject); the constructor will not return until the executor has completed.
Application Translation with Mercurial
start tracking changes you make against the localization repository by telling it that with the qnew subcommand to save these changes as patch in a mercurial queue.
... tell mercurial to store the changes in the mercurial queue with the qref command.
Index
with that document, users can see immediately two localized files in their user interface by following closely and carefully the steps to create a language pack or a binary file that is ready for installation.
... apache, infrastructure, localization, php, svn, unix first, make your project's file type decision (see localization formats for details): 40 what every mozilla translator should know internationalization, localization l10n stands for localization = l + another 10 letters + n 41 writing localizable code internationalization, localization this page tells you about best practices and guidelines when dealing with ui code with respect to localization.
Localization technical reviews
this is something to look for, but can be difficult to diagnose immediately.
...in order to ultimately have your revision included as an official build, your dashboards must be at 100% green.
Localization formats
can be hard to tell what has changed .lang files historically, mozilla has used a gettext-like file to present content for localization.
...rs to edit the l10n file where they shouldn't separates localizable strings available for localizers for the rest of the code, protecting it from unintended changes disadvantage of gettext .po file needs to be compiled into a .mo file for localizer to see changes using regular diff to see changes to a file is sometimes impossible because the editing tool can save the .po file using a completely different structure or order of entities.
Basics
<msup> <mi>y</mi> <mn>4</mn> </msup> </mrow> <mo>+</mo> <msup> <mi>y</mi> <mn>5</mn> </msup> </mrow> </maction> </mtd> </mtr> </mtable> </mtd> </mtr> </mtable> </math> </div> css content .control { text-decoration: none; font-weight: bold; font-size: 200%; } input { color: red; } [class="inputmath"] { border: 1px dotted; } javascript content function setselection(id,value) { document.getelementbyid(id).setattribute("selection",value); } function expand() { setselection("a11","2"); setselection("a12","2"); setselection("a13","2"); setselection("a21","2"); setselection("a22","2"); setselection("a23","2"); setselection("a31","2"); setselection("a32","2"); setselection("a33","2"); setselection("a41","2"); setselection("a42","2"); setselection("a43","2"); } function unex...
...pand() { setselection("a11","1"); setselection("a12","1"); setselection("a13","1"); setselection("a21","1"); setselection("a22","1"); setselection("a23","1"); setselection("a31","1"); setselection("a32","1"); setselection("a33","1"); setselection("a41","1"); setselection("a42","1"); setselection("a43","1"); } function incrementinput(inputid, increment) { var inputelement = document.getelementbyid(inputid); var size = parseint(inputelement.size) + increment; if (size <= 0) size = 1 inputelement.size = size; } and there could be more...
MathML Demo: <mspace> - space
"javascript:downdepth();" title="decrease depth">-</a> <math display="block"> <mstyle displaystyle="true"> <msqrt> <mrow> <mn>3</mn> <mspace style="background-color: yellow" id="thespace" height="0.1ex" depth="0.1ex" width="0.1em" /> <mi>x</mi> </mrow> </msqrt> </mstyle> </math> </p> javascript content var height=0; var width=0; var depth=0; function upheight() { height++; document.getelementbyid("thespace").setattribute("height",height+".1ex"); } function downheight() { height--; document.getelementbyid("thespace").setattribute("height",height+".1ex"); } function upwidth() { width++; document.getelementbyid("thespace").setattribute("width",width+".1em"); } function downwidth() { width--; document.getelementbyid("thespace").setattribute("width",width+".1em"); } functi...
...on updepth() { depth++; document.getelementbyid("thespace").setattribute("depth",depth+".1ex"); } function downdepth() { depth--; document.getelementbyid("thespace").setattribute("depth",depth+".1ex"); } ...
Mozilla Development Strategies
this puts the bug on the radar of our documentation team to ensure that once the bug is resolved, the documentation will be updated appropriately.
...it's easier to tell someone set a pref, or apply a small patch, or set a #define than to apply a monster patch.
Activity Monitor, Battery Status Menu and top
(apple support documentation specifically recommends it for troubleshooting battery life problems.) unfortunately "energy impact" is not a good measure for either users or software developers and it should be avoided.
...the exception is when the application is closed, in which case it disappears immediately.
GPU performance
intel graphics performance analyzers - haven't tried.
...guides accurately profiling direct3d api calls (direct3d 9)- suggests avoiding normal profilers like xperf and instead measuring the time to flush the command buffer.
tools/power/rapl
tools/power/rapl (or rapl for short) is a command-line utility in the mozilla tree that periodically reads and prints all available intel rapl power estimates.
... windows unfortunately, rapl does not work on windows, and porting it would be difficult because windows does not have apis that allow easy access to the relevant model-specific registers.
Phishing: a short definition
the ss7 telephony system is vulnerable, making eavesdropping, or rerouting text messages quite trivial.
...unfortunately, some users still feel it's too tedious unlocking a phone, opening the otp app, and manually typing a few digits each time a provider requests a new token.
A guide to searching crash reports
this immediately shows which moz_crash calls are being hit frequently by users.
...these results would be improved by using numeric ranges instead of individual values, but unfortunately that isn't supported.
L20n HTML Bindings
in addition to the pre-defined whitelists, any element found in the original source html is allowed in the translation as well.
...</p> the input element is not on the default whitelist but since it's present in the source html, it is also allowed in the translation.
NSPR Poll Method
the prototype of the poll method is print16 poll_method(prfiledesc *fd, print16 in_flags, print16 *out_flags); the purpose of the poll method is to allow a layer to modify that flags that will ultimately be used in the call to the underlying network transport's select (or equivalent) function, and to indicate that a layer is already able to make progress in the manner suggested by the polling flags.
...on return, if (new_flags & out_flags) is nonzero, you can try pr_recv or pr_send immediately.
Floating Point Number to String Conversion
clinger, "how to read floating point numbers accurately," proc.
...white, "how to print floating-point numbers accurately," proc.
Introduction to NSPR
nspr threads are scheduled in two separate domains: local threads are scheduled within a process only and are handled entirely by nspr, either by completely emulating threads on each host operating system (os) that doesn't support threads, or by using the threading facilities of each host os that does support threads to emulate a relatively large number of local threads by using a relatively small number of native threads.
...writing the code as follows could potentially return a null reference, violating the invariant of the function: void *dequeue() { void *db; enter(monitor); if ((db = delink()) == null) { wait(condition); db = delink(); } exit(monitor); return db; } the same function would be more appropriately written as follows: void *dequeue() { void *db; enter(monitor); while ((db = delink()) == null) wait(condition); exit(monitor); return db; } caution: the semantics of pr_waitcondvar assume that the monitor is about to be exited.
PRLinger
description by default, pr_close returns immediately, but if there are any data remaining in the socket send buffer, the system attempts to deliver the data to the peer.
... the pr_sockopt_linger socket option, with a value represented by a structure of type prlinger, makes it possible to change this default as follows: if polarity is set to pr_false, pr_close returns immediately, but if there are any data remaining in the socket send buffer, the runtime attempts to deliver the data to the peer.
JSS FAQ
MozillaProjectsNSSJSSJSS FAQ
how can i tell which ssl/tls ciphers jss supports?
...you can find more information in bugzilla bug 102251 ssl session cache locking issue with nt fibers how can i tell which ssl/tls ciphers jss supports?
NSS 3.14.2 release notes
the release is available for download from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_2_rtm/src/ for the primary nss documentation pages please visit /docs/nss new in nss 3.14.2 nss will now make use of the intel aes-ni and avx instruction sets for hardware-accelerated aes-gcm on 64-bit linux systems.
... new types: in certt.h cert_pi_useonlytrustanchors in secoidt.h sec_oid_ms_ext_key_usage_ctl_signing notable changes in nss 3.14.2 bug 805604 - support for aes-ni and avx accelerated aes-gcm was contributed by shay gueron of intel.
NSS 3.16.2.1 release notes
users are encouraged to upgrade immediately.
... bugs fixed in nss 3.16.2.1 bug 1064636 - (cve-2014-1568) rsa signature forgery in nss acknowledgements the nss development team would like to thank antoine delignat-lavaud, security researcher at inria paris in team prosecco, and the advanced threat research team at intel security, who both independently discovered and reported this issue, for responsibly disclosing the issue by providing advance copies of their research.
NSS 3.16.5 release notes
users are encouraged to upgrade immediately.
... bugs fixed in nss 3.16.5 bug 1064636 - (cve-2014-1568) rsa signature forgery in nss acknowledgements the nss development team would like to thank antoine delignat-lavaud, security researcher at inria paris in team prosecco, and the advanced threat research team at intel security, who both independently discovered and reported this issue, for responsibly disclosing the issue by providing advance copies of their research.
NSS 3.17.1 release notes
users are encouraged to upgrade immediately.
...s 3.17.1 this bugzilla query returns all the bugs fixed in nss 3.17.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17.1 acknowledgements the nss development team would like to thank antoine delignat-lavaud, security researcher at inria paris in team prosecco, and the advanced threat research team at intel security, who both independently discovered and reported this issue, for responsibly disclosing the issue by providing advance copies of their research.
NSS 3.35 release notes
tls servers are able to handle a clienthello statelessly, if the client supports tls 1.3.
... this better enables stateless server operation.
NSS Developer Tutorial
unfortunately, this can be a source of integer overflow bugs on 64-bit systems.
...unfortunately, public headers may declare private functions, for historical reasons.
NSS Tools sslstrength
policy=export or policy=domestic will set your policies appropriately.
...you can tell if you stepped-up, because the output will says 'using export policy', and you'll find the secret key size was 128-bits.
PKCS #11 Module Specs
parameter passing if the parameter is specified, the application/library will strip the value out, processing any outter quotes and escapes appropriately, and pass the parameter to the pkcs #11 library when it calls c_initialize().
... critical - if this library cannot be loaded, completely fail initialization.
FC_GetOperationState
syntax ck_rv fc_getoperationstate( ck_session_handle hsession, ck_byte_ptr poperationstate, ck_ulong_ptr puloperationstatelen ); parameters hsession [in] handle of the open session.
...puloperationstatelen [out] pointer to ck_ulong which receives the total length (in bytes) of the operation state.
FC_SetOperationState
syntax ck_rv fc_setoperationstate( ck_session_handle hsession, ck_byte_ptr poperationstate, ck_ulong uloperationstatelen, ck_object_handle hencryptionkey, ck_object_handle hauthenticationkey ); parameters hsession [in] handle of the open session.
...uloperationstatelen [in] contains the total length (in bytes) of the operation state.
sslintro.html
these functions tell the library which cipher suites are permitted by policy (for example, to comply with export restrictions).
... use ssl_forcehandshake when the socket has been prepared for a handshake but neither end has anything to say immediately.
NSS Tools sslstrength
policy=export or policy=domestic will set your policies appropriately.
...you can tell if you stepped-up, because the output will says 'using export policy', and you'll find the secret key size was 128-bits.
NSS tools : signtool
-e extension tells signtool to sign only files with the given extension; for example, use -e".class" to sign only java class files.
... -z tells signtool not to store the signing time in the digital signature.
Necko walkthrough
nshttpconnection::activate this connection is passed the transaction nshttpconnection::onoutputstreamready nshttpconnection::onsocketwritable tries to write the request data from the current transaction (mtransaction) tells the transaction to now wait (`resumerecv) nshttpconnection::resumerecv nshttptransaction::readsegments readrequestsegment is passed to mrequeststream->readsegments - this function pointer is called and used to read the request bytes, which in turn calls ...
...note: from what i can tell, there are some cases where the transaction is queued up to be written to the socket later if it's not writable now, or in the case of pipelining or spdy where it's done in batches.
Installing Pork
to tell mcpp which gcc installation to integrate itself with, place the selected gcc bin dir as the first element of your path: path=/bindir/of/my/gcc:$path if you want to use a gcc that has binaries named something other than "gcc" and "g++", or you use "ccache" for you main gcc installation and want mcpp to override a separate installation, you need to pass the options "cc=gccxxx cxx=g++xxx" to "./c...
...in particular, -k tells mcpp to add the macro annotations we use to get exact source positions.
SpiderMonkey Build Documentation
if --enable-nspr-build does not work, explicitly tell configure where to find nspr using the --with-nspr-cflags and --with-nspr-libs configure options.
... building your application while "how to build your complete application" is clearly out of scope for this document, here are some tips that will help get you on your way: the spidermonkey developers frequently and deliberately change the jsapi abi.
Creating JavaScript jstest reftests
a different approach is to use the expectexitcode(exitcode) function which outputs a string: --- note: in this testcase, we expect exit code <exitcode> --- that tells the post-processing scripts jsdriver.pl or post-process-logs.pl that the test passes if the shell or browser terminates with that exit code.
... multiple calls to expectexitcode will tell the post-processing scripts that the test actually passed if any of the exit codes are found when the test terminates.
Functions
if a name definitely refers to an argument or local variable of the immediately enclosing function, it can be accessed using jsop_{get,set,call}{arg,local} instructions.
...outside all functions, if a name definitely refers to a global for which we have seen a var, const, or function declaration, then we emit a js_defvar instruction in the script prelude and access the global using jsop_{get,set,call}gvar.
JSAPI Cookbook
ion(cx); /* do error-handling stuff here */ return true; finally // javascript try { foo(); bar(); } finally { cleanup(); } if your c/c++ cleanup code doesn't call back into the jsapi, this is straightforward: /* jsapi */ bool success = false; if (!js_callfunctionname(cx, global, "foo", 0, null, &r)) goto finally_block; /* instead of returning false immediately */ if (!js_callfunctionname(cx, global, "bar", 0, null, &r)) goto finally_block; success = true; /* intentionally fall through to the finally block.
... /* jsapi */ bool success = false; if (!js_callfunctionname(cx, global, "foo", 0, null, &r)) goto finally_block; /* instead of returning false immediately */ if (!js_callfunctionname(cx, global, "bar", 0, null, &r)) goto finally_block; success = true; /* intentionally fall through to the finally block.
JS_AddArgumentFormatter
the js_true passed for fromjs tells the formatter to convert zero or more jsvals at sp to zero or more c values accessed via pointers-to-values at ap, updating both sp (via *vpp) and ap (via *app) to point past the converted arguments and their result pointers on the c stack.
... when called from js_pushargumentsva, the formatter is invoked thus: formatter(cx, "aa...", js_false, &sp, &ap); where js_false for fromjs means to wrap the c values at ap according to the format specifier and store them at sp, updating ap and sp appropriately.
JS_DumpHeap
the "trace kind" is a static map which tells which layout a gc thing has.
... although this map is public, the details are completely hidden.
JS_NewGlobalObject
this api provides a way for consumers to set slots atomically (immediately after the global is created), before any debugger hooks are fired.
... it's unfortunately on the clunky side, but that's the way the cookie crumbles.
JS_SetBranchCallback
if the callback returns js_false without raising an exception, then the javascript engine immediately stops running the script with an uncatchable error.
...the callback simply increments the counter and does nothing further (returning js_true immediately) unless the counter has reached the threshold value.
JS_YieldRequest
a program can call this function periodically to ensure that a long-running request does not block garbage collection indefinitely.
... the effect is the same as a call to js_suspendrequest immediately followed by a call to js_resumerequest.
Secure Development Guidelines
: dynamically allocate fd_set structs int main(void) { int i, fd; fd_set fdset; for( i = 0; i < 2000; i++) { fd = open("/dev/null", o_rdwr); } fd_set(fd, &fdset); } file i/o: race conditions operating on files can often lead to race conditions since the file system is shared with other processes you check the state of a file at one point in time and immediately after the state might have changed most file name operations suffer from these race conditions, but not when performed on file descriptors file i/o: race conditions consider the following example int main(int argc, char **argv) { char *file = argv[1]; int fd; struct stat statbuf; stat(file, &statbuf); if (s_islink(statbuf.st_mode)) { bailout(“symbolic link�...
... unlock(locka); unlock(lockb); } writing secure code: good coding practices banned api list badly designed apis can often lead to vulnerabilities it’s too easy to use the api inappropriately for example, consider the libc string handling apis strcpy() performs no bounds checking strncpy() doesn’t always 0-terminate strncat() length parameter is very confusing banned api list examples of incorrect strncat usage buffer overflow strncat(buffer, string, sizeof(buffer)); off-by-one strncat(buffer, string, sizeof(buffer) – strlen(string)); ...
Generating GUIDs
warning: if you just want an id for your add-on, generating a guid is almost definitely not what you want to do.
... using the extensionname@organization.tld form is approximately one thousand times easier for everyone involved.
Creating the Component Code
the registerself call allows your component to tell xpcom exactly what it supports.
... nsicomponentregistrar methods to tell xpcom what implementation is in the component library, call this method from registerself: ns_imethod registerfactorylocation(const nscid & aclass, const char *aclassname, const char *acontractid, nsifile *afile, const char *aloaderstr, ...
Preface
it is badly out of date, and much of what it says is either no longer remotely accurate, or is severely deprecated.
...those terms are either explained immediately after they are cited, or else the reader is referred to a section in the book where they are described in detail.
Starting WebLock
for example, the user interface needs to be able to enable and disable the web locking functionality, see what sites are in the whitelist, and add or remove sites from that list.
...on the macintosh platform, for example, files are represented as a triplet - two numbers and one string - so using a string on the macintosh does not adequately identify files on that operating system.
Components.utils.cloneInto
same mechanism as that used in components.utils.exportfunction: // add-on script var addonscriptobject = { greetme: function() { alert("hello from add-on"); } }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, {clonefunctions: true}); // page script var test = document.getelementbyid("test"); test.addeventlistener("click", function() { window.addonscriptobject.greetme(); }, false); cloning objects that contain dom elements by default, if the object you clone contains objects that are reflected from c++, such as dom elements, the cloning operation will fail with an error.
...rapreflectors:true} flag, then the object you clone is allowed to contain these objects: // add-on script var addonscriptobject = { body: contentwindow.document.body }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, {wrapreflectors: true}); // page script var test = document.getelementbyid("test"); test.addeventlistener("click", function() { console.log(window.addonscriptobject.body.innerhtml); }, false); access to these objects in the target scope is subject to the normal security checks.
Components.utils.schedulePreciseGC
note: garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary.
...egc(), you specify a callback that is executed in once the scheduled garbage collection has been completed: components.utils.scheduleprecisegc( function() { // this code is executed when the garbage collection has completed } ); since the garbage collection doesn't occur until some time in the future (unlike, for example, components.utils.forcegc(), which causes garbage collection immediately but isn't able to collect all javascript-related memory), the callback lets you know when that's been finished.
imgIDecoderObserver
however, with decode-on-draw, the set of decode notifications can come completely after the load notifications, and can come multiple times if the image is discardable.
...unfortunately, this is currently the only way to signal decoding errors to consumers, and the only decoding errors that consumers care about (indeed, the only ones that they're prepared to hear about) are failures to instantiate the decoder (<img src="foo.html"> for example).
imgIRequest
status_frame_complete 0x10 the first frame has been completely decoded.
...imgirequest clone( in imgidecoderobserver aobserver ); parameters aobserver return value decrementanimationconsumers() tell the image it can forget about a request that the image animate.
mozIRegistry
introduction the title of this document is completely misleading.
...the information below is intended to tell you everything you need to know about how to do that.
mozIStorageConnection
note: the statements may be reused immediately, and the statements do not need to be reset individually.
...this helps avoid disk fragmentation by letting you help sqlite make intelligent decisions about resizing of the file.
nsICRLInfo
lastupdatelocale astring lastupdate formatted as a human readable string formatted according to the environment locale.
... nextupdatelocale astring nextupdate formatted as a human readable string formatted according to the environment locale.
nsIDOMChromeWindow
this method tells the window manager to start dragging the window.
...if set to -1, cycles indefinitely until window is brought into the foreground.
nsIDragService
enddragsession() tells the drag service to end a drag session.
... startdragsession() tells the drag service to start a drag session.
nsIEditorSpellCheck
ignorewordalloccurrences() tells the spell checker to ignore all occurrences of the specified word when spell checking the document.
...this function allows the caller to force the default immediately.
nsIFile
unfortunately, an actual "move" is impossible between different volumes (disks or partitions).
... unfortunately, an actual "move" is impossible between different volumes (disks or partitions).
nsILocalFile
delete_on_close may be implemented by removing the file (by path name) immediately after opening it, so beware of possible races; the file should be exclusively owned by this process.
...therefore, never use these functions unless you are absolutely sure that the path passed to them is always ascii-only.
nsILoginManager
to create an instance, use: var loginmanager = components.classes["@mozilla.org/login-manager;1"] .getservice(components.interfaces.nsiloginmanager); method overview void addlogin(in nsilogininfo alogin); nsiautocompleteresult autocompletesearch(in astring asearchstring, in nsiautocompleteresult apreviousresult, in nsidomhtmlinputelement aelement); unsigned long countlogins(in astring ahostname, in astring aactionurl, in astring ahttprealm); boolean fillform(in nsidomhtmlformelement aform); void findlogins(out unsigned long count, in astring ahostname, in astring aactionurl, in astring ahttprealm, [retval, array, size_is(count)] out nsilogininfo logins); void getalldisabledhosts([optional...
... nsiautocompleteresult autocompletesearch( in astring asearchstring, in nsiautocompleteresult apreviousresult, in nsidomhtmlinputelement aelement ); parameters asearchstring missing description apreviousresult missing description aelement missing description return value missing description countlogins() returns the number of logins matching the specified criteria.
nsIMacDockSupport
bute('label', 'show most recent window'); macmenuitem.setattribute('id', 'mymacmenuitem'); macmenuitem.addeventlistener('command', function(){ var docksupport = cc['@mozilla.org/widget/macdocksupport;1'].getservice(ci.nsimacdocksupport); docksupport.activateapplication(true); services.wm.getmostrecentwindow(null).focus() }) macmenu.appendchild(macmenuitem); var mainpopupset = win.document.getelementbyid('mainpopupset'); mainpopupset.appendchild(macmenu); let dockmenuelement = macmenu; //document.getelementbyid("menu_mac_dockmenu");66 let nativemenu = cc["@mozilla.org/widget/standalonenativemenu;1"].createinstance(ci.nsistandalonenativemenu); console.log('dockmenuelement:', dockmenuelement); nativemenu.init(dockmenuelement); docksupport.dockmenu = nativemenu; this replaces the default...
...); macmenuitem.setattribute('label', 'show most recent window'); macmenuitem.setattribute('id', 'mymacmenuitem'); macmenuitem.addeventlistener('command', function(){ var docksupport = cc['@mozilla.org/widget/macdocksupport;1'].getservice(ci.nsimacdocksupport); docksupport.activateapplication(true); services.wm.getmostrecentwindow(null).focus() }) services.appshell.hiddendomwindow.document.getelementbyid('menu_mac_dockmenu').appendchild(macmenuitem) this adds the "show most recent window" menuitem from the previous example as a third item.
nsIMessenger
as far as i can tell this isn't used or checked.
...unfortunately, you must call this before navigating to a position, because calling this has the side effect of making us adjust our current history position, and not adding the loaded message to the history queue.
nsIMsgSearchSession
; boolean isstringattribute(in nsmsgsearchattribvalue attrib); void addallscopes(in nsmsgsearchscopevalue attrib); void search(in nsimsgwindow awindow); void interruptsearch(); void pausesearch(); void resumesearch(); [noscript] nsmsgsearchtype setsearchparam(in nsmsgsearchtype type, in voidptr param); [noscript] void addresultelement(in nsmsgresultelement element); boolean matchhdr(in nsimsgdbhdr amsghdr, in nsimsgdatabase adatabase); void addsearchhit(in nsimsgdbhdr header, in nsimsgfolder folder); attributes attribute type description searchterms nsisupportsarray readonly: numsearchterms unsigned long readonly: runningadapter nsimsgsea...
... void pausesearch(); resumesearch() void resumesearch(); setsearchparam() [noscript] nsmsgsearchtype setsearchparam(in nsmsgsearchtype type, in voidptr param); parameters type param addresultelement() [noscript] void addresultelement(in nsmsgresultelement element); parameters element matchhdr() boolean matchhdr(in nsimsgdbhdr amsghdr, in nsimsgdatabase adatabase); parameters amsghdr adatabase addsearchhit() void addsearchhit(in nsimsgdbhdr header, in nsimsgfolder folder); parameters header folder ...
Component; nsIPrefBranch
if you find yourself wondering what is the maximum amount of data you can store in a string preference, consider storing data separately, for example in a flat file or an sqlite database.
...if you find yourself wondering what is the maximum amount of data you can store in a string preference, consider storing data separately, for example in a flat file or an sqlite database.
nsIProtocolProxyService
proxy auto config (pac) may perform a synchronous dns query, which may not return immediately.
...this method is intended as a substitute for resolve when the result is not needed immediately.
nsISessionStore
this method affects all tabs indiscriminately.
... note: calling setbrowserstate immediately replaces the current session, restoring the state of the entire application to the state passed in the astate parameter.
nsIStyleSheetService
sheets added via this api take effect on all documents, including already-loaded ones, immediately.
...the removal takes effect immediately, even for already-loaded documents.
nsITextInputProcessor
if you call this when there is no composition, this starts composition automatically and commits the composition with specified string immediately.
...but the computation doesn't emulate the mapping of native key event handling completely because it has some special cases depending on platform or selected keyboard layout.
nsITreeBoxObject
void invalidate(); void invalidatecolumn(in nsitreecolumn col); void invalidaterow(in long index); void invalidatecell(in long row, in nsitreecolumn col); void invalidaterange(in long startindex, in long endindex); void invalidatecolumnrange(in long startindex, in long endindex, in nsitreecolumn col); getrowat() a hit test that can tell you what row the mouse is over.
... long getrowat(in long x, in long y); parameters x the x coordinate y the y coordinate getcellat() a hit test that can tell you what cell the mouse is over.
nsIWebBrowserChrome
the implementation should reflect the value of this attribute by hiding or showing its chrome appropriately.
...sizebrowserto() tells the chrome to size itself such that the browser will be the specified size.
nsIWebBrowserChromeFocus
inherits from: nsisupports last changed in gecko 1.7 method overview void focusnextelement(); void focusprevelement(); methods focusnextelement() set the focus at the next focusable element in the chrome.
... void focusnextelement(); parameters none.
nsIXPConnect
deferreleasesuntilaftergarbagecollection prbool obsolete since gecko 1.9 pendingexception nsiexception constants constant value description init_js_standard_classes 1 << 0 flag_system_global_object 1 << 1 omit_components_object 1 << 2 xpc_xow_clearscope 1 tells updatexows() to clear the scope of all of the xows it finds.
... return value missing description exceptions thrown missing exception missing description native code only!evalinsandboxobject evaluate script in a sandbox, completely isolated from all other running scripts.
nsIXULBrowserWindow
xpfe/appshell/public/nsixulbrowserwindow.idlscriptable provides methods that may be called from the internals of the browser area to tell the containing xul window to update its user interface.
... setoverlink() tells the object implementing this function what link we are currently over.
nsIXULWindow
highestz 9 methods addchildwindow() tell this window that it has picked up a child xul window.note that xul windows do not currently track child xul windows.
... removechildwindow() tell this window that it has lost a child xul window.
XPCOM Interface Reference
iapplicationcachenamespacensiapplicationcacheservicensiapplicationupdateservicensiarraynsiasyncinputstreamnsiasyncoutputstreamnsiasyncstreamcopiernsiasyncverifyredirectcallbacknsiauthinformationnsiauthmodulensiauthpromptnsiauthprompt2nsiauthpromptadapterfactorynsiauthpromptcallbacknsiauthpromptprovidernsiauthpromptwrappernsiautocompletecontrollernsiautocompleteinputnsiautocompleteitemnsiautocompletelistenernsiautocompleteobservernsiautocompleteresultnsiautocompletesearchnsibadcertlistener2nsibidikeyboardnsibinaryinputstreamnsibinaryoutputstreamnsiblocklistpromptnsiblocklistservicensiboxobjectnsibrowserboxobjectnsibrowserhistorynsibrowsersearchservicensicrlinfonsicrlmanagernsicachensicachedeviceinfonsicacheentrydescriptornsicacheentryinfonsicachelistenernsicachemetadatavisitornsicacheservicens...
...sisupportsprint64nsisupportsprtimensisupportspruint8nsisupportspruint16nsisupportspruint32nsisupportspruint64nsisupportsprimitivensisupportsprioritynsisupportsstringnsisupportsvoidnsisupportsweakreferencensisyncjpakensisyncmessagesendernsitxttohtmlconvnsitaggingservicensitaskbarpreviewnsitaskbarpreviewbuttonnsitaskbarpreviewcontrollernsitaskbarprogressnsitaskbartabpreviewnsitaskbarwindowpreviewnsitelemetrynsitextinputprocessornsitextinputprocessorcallbacknsitextinputprocessornotificationnsithreadnsithreadeventfilternsithreadinternalnsithreadmanagernsithreadobservernsithreadpoolnsithreadpoollistenernsitimernsitimercallbacknsitoolkitnsitoolkitprofilensitoolkitprofileservicensitraceablechannelnsitransactionnsitransactionlistnsitransactionlistenernsitransactionmanagernsitransferablensitransportns...
Performance
for example sqlite> explain query plan select * from moz_historyvisit v join moz_history h on v.page_id = h.id where v.visit_date > 1000000000; 0|0|table moz_historyvisit as v with index moz_historyvisit_dateindex 1|1|table moz_history as h using primary key this tells us that it will first look up in moz_historyvisit using an index, and will then look up in moz_history using the primary key.
...unfortunately, this operation cannot be controlled on a per-transaction or per-connection basis.
Reference Manual
nscomptr<t> = do_queryinterface( nsisupports* ), nscomptr<t> = do_queryinterface( nsisupports*, nsresult* ) if you can't satisfy the above promise, you can `annotate' the assignment to tell the nscomptr it needs to call queryinterface, e.g., nscomptr<nsifoo> foo( do_queryinterface(abarptr) ); // or foo = do_queryinterface(abarptr); // ..._will_ call |queryinterface| (and therefore, |addref|) // of course, since you're calling |queryinterface|, you might need the // error result...
... } unfortunately, not.
Index
77 building a thunderbird extension 4: chrome manifest extensions, thunderbird the file called chrome.manifest tells thunderbird what packages and overlays are provided by the extension.
...you can either put the folder with the extension files directly into thunderbird's extensions folder, or you can put a file there that tells thunderbird where your extension is located.
Adding items to the Folder Pane
the following code snippet listens for that event: let gnumbersext = { load: function gne_load() { window.removeeventlistener("load", gnumbersext.load, false); let tree = document.getelementbyid("foldertree"); tree.addeventlistener("maprebuild", gnumbersext._insert, false); }, _insert: function gne__insert() { // this function is called when a rebuild occurs } }; window.addeventlistener("load", gnumbersext.load, true); the structure of folder-tree-items the folder pane stores its current display data in a property called _rowmap.
...unfortunately, this rebuild will occur before an extension's "load" event fires.
Access StringBundle from Overlay
unfortunately adding the bundles into thunderbird isn't as easy as adding them to your xul overlay.
... the most efficient way to append these strings is by attaching them to an existing stringbundleset as such: <stringbundleset id="stringbundleset"> <stringbundle src="chrome://your_extension/locale/overlay.properties" id="your-extension-strings" /> </stringbundleset> now that your stringbundle is attached you can access it from javascript as follows: var str = document.getelementbyid("your-extension-strings"); //get the stringbundle object itself str.getstring("propertyname"); //get a string (and do something with it) alternative way let stringbundleservice = cc["@mozilla.org/intl/stringbundle;1"].getservice(ci.nsistringbundleservice); let bundle = stringbundleservice.createbundle("chrome://your_extension/locale/overlay.properties"); let str = bundle...
customDBHeaders Preference
ents.interfaces.nsiobserver observe: function(amsgfolder, atopic, adata) { dump("here here!"); addcustomcolumnhandler(); } } function doonceloaded(){ var observerservice = components.classes["@mozilla.org/observer-service;1"].getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(createdbobserver, "msgcreatedbview", false); window.document.getelementbyid('foldertree').addeventlistener("select",addcustomcolumnhandler,false); } window.addeventlistener("load",doonceloaded,false); dump(" ~ ~ ~ ~ end superfluous ~ ~ ~ ~ \n"); important be aware that only messages that are added to the .msf database after the customdbheaders pref is set will have the corresponding string property set on the msghdr.
.../ chrome.manifest chrome/content/ chrome/content/superfluous.js chrome/content/superfluous_overlay.xul install.rdf adding: chrome/ (stored 0%) adding: chrome.manifest (deflated 44%) adding: chrome/content/ (stored 0%) adding: chrome/content/superfluous.js (deflated 57%) adding: chrome/content/superfluous_overlay.xul (deflated 44%) adding: install.rdf (deflated 50%) end result ultimately, you want to be able to compose a message like this: and see the superfluous column displayed in your inbox like this: thanks many thanks go out to the thunderbird developers for the fine product that it is.
Using the Multiple Accounts API
relevant api calls: nsimsgaccount nsimsgaccountmanager.createaccount() nsimsgaccount nsimsgaccountmanager.getaccount(in string key) nsimsgincomingserver nsimsgaccountmanager.createincomingserver(in string type) nsimsgincomingserver nsimsgaccountmanager.getincomingserver(in string key) smtp servers smtp servers are kept separately from all the other account management stuff.
... preference: mail.server.server.max_cached_connections - integer, max number of connections left open to the server preference: mail.server.server.empty_trash_threshhold integer, (should not be imap-specific) max k of wasted diskspace before we purge a folder preference: mail.server.server.delete_model - integer, delete model (move to trash, imap delete, purge immediately, not sure of values) preference: mail.server.server.timeout - integer, number of minutes a connection is idle before we drop it preference: mail.server.server.capability - list of capabilities of this server preference: mail.server.server.namespace.public - the server's namespace for public folders preference: mail.server.server.namespace.personal - the server's namespace for per...
Working with data
creating uninitialized cdata objects there are three forms of the syntax for creating cdata objects without immediately assigning them a value: var mycdataobj = new type; var mycdataobj = new type(); var mycdataobj = type(); these all do the same thing: they return a new cdata object of the specified type, whose data buffer has been populated entirely with zeroes.
... 64-bit integers while most numeric types in js-ctypes are represented by standard javascript number objects, 64-bit integers cannot all be represented accurately by this type.
Drawing and Event Handling - Plugins
« previousnext » this chapter tells how to determine whether a plug-in instance is windowed or windowless, how to draw and redraw plug-ins, and how to handle plug-in events.
... typically, the browser calls npp_setwindow after creating the instance so that the plug-in can begin drawing immediately.
Plug-in Side Plug-in API - Plugins
npp_destroystream tells the plug-in that a stream is about to be closed or destroyed.
... npp_setwindow tells the plug-in when a window is created, moved, sized, or destroyed.
Accessibility Inspector - Firefox Developer Tools
assistive technologies like screenreaders use this information to find out what's on a web page, tell their users what's there, and enable them to interact with the page.
...ch are detailed below: context menu options an extra context menu option is added, both for the general context menu on the web page when right/ctrl + clicking a ui feature, and the html pane of the page inspector when right/ctrl + clicking a dom element: when you choose the inspect accessibility properties/show accessibility properties context menu options, the accessibility tab is immediately opened to show the corresponding accessibility tree item and its properties.
Source map errors - Firefox Developer Tools
this message will show an error message, the resource url, and the source map url: here, the resource url tells us that bundle.js mentions a source map, and the source map url tells us where to find the source map data (in this case, relative to the resource).
... the error tells us that the source map is not json data — so we're serving the wrong file.
Debugger.Object - Firefox Developer Tools
for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
...ifvalue is a primitive, we return it unchanged; ifvalue is an object, we return the debugger.object instance representing that object, wrapped appropriately for use in this debugger.object’s referent’s compartment.
Debugger.Object - Firefox Developer Tools
for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
...ifvalue is a primitive, we return it unchanged; ifvalue is an object, we return the debugger.object instance representing that object, wrapped appropriately for use in this debugger.object's referent's compartment.
The Firefox JavaScript Debugger - Firefox Developer Tools
you can use it to debug code running locally in firefox or running remotely, for example on an android device running firefox for android.
...there are multiple ways to tell the debugger how and when to pause: set a breakpoint set a conditional breakpoint set an xhr breakpoint set event listener breakpoints break on exceptions use watchpoints for property reads and writes break on dom mutation disable breakpoints control execution what can you do after execution pauses?
Index - Firefox Developer Tools
65 inspect and select colors guide, inspector, tools in the css pane's rules view, if a rule contains a color value, you'll see a sample of the color next to the value: 66 open the inspector guide, inspector, tools there are two main ways to open the inspector: 67 reposition elements in the page starting in firefox 48 you can move absolutely positioned elements by dragging them around the page.
...however, you can tell the debugger to ignore the details of selected sources.
Migrating from Firebug - Firefox Developer Tools
unfortunately, the devtools do not have this feature yet (see bug 1004678).
... this is the part where firebug and the devtools differ the most, because the outputs are completely different.
Reposition elements in the page - Firefox Developer Tools
new in firefox 48 starting in firefox 48 you can move absolutely positioned elements by dragging them around the page.
... if the element is absolutely positioned, dashed lines are shown representing the offset parent.
Allocations - Firefox Developer Tools
this is telling us that, of the 8904 allocations seen in signallater(), all but three came through the removeinner() branch.
...while gc events like this are executing, the javascript engine must be paused, so your program is suspended and will be completely unresponsive.
Animating CSS properties - Firefox Developer Tools
the predominance of green is telling us that we're spending a lot of time painting.
...in the screenshot above we've highlighted a paint operation, and the box on the right tells us it took 13.11ms.
Waterfall - Firefox Developer Tools
gc is relevant to performance because while it's running the javascript engine must be paused, so your program is suspended and will be completely unresponsive.
... for example, consider code like this: var timerbutton = document.getelementbyid("timer"); timerbutton.addeventlistener("click", handleclick, false); function handleclick() { console.time("timer"); runtimer(1000).then(timerfinished); } function timerfinished() { console.timeend("timer"); console.log("ready!"); } function runtimer(t) { return new promise(function(resolve) { settimeout(resolve, t); }); } the waterfall will display a marker for the p...
Responsive Design Mode - Firefox Developer Tools
now when you change such settings for the first time, you are given a warning message that tells you these reloads are no longer automatic, and informed about how you can make them automatic.
...in responsive design mode, you can instruct the browser to emulate, very approximately, the characteristics of various different types of networks.
Style Editor - Firefox Developer Tools
any changes you make are immediately applied to the page.
... editing original sources you can also edit the original sources in the style editor and see the results applied to the page immediately.
The JavaScript input interpreter - Firefox Developer Tools
for example, if you type: function foo() { and then enter, the console does not immediately execute the input, but behaves as if you had pressed shift+enter , so you can finish entering the function definition.
...there are three ways to select an iframe using cd(): you can pass the iframe dom element: var frame = document.getelementbyid("frame1"); cd(frame); you can pass a css selector that matches the iframe: cd("#frame1"); you can pass the iframe's global window object: var frame = document.getelementbyid("frame1"); cd(frame.contentwindow); to switch the context back to the top-level window, call cd() with no arguments: cd(); for example, suppose we have a document that embeds an iframe: <!doctype html> <html...
Animation.onfinish - Web APIs
the finish event occurs when the animation completes naturally, as well as when the animation.finish() method is called to immediately cause the animation to finish up.
...here is one instance where we add pointer events back to an element after its opacity animation has faded it in: // add an animation to the game's ending credits var endingui = document.getelementbyid("ending-ui"); var bringui = endingui.animate(keysfade, timingfade); // pause said animation's credits bringui.pause(); // this function removes pointer events on the credits.
AudioBufferSourceNode - Web APIs
fortunately, these nodes are very inexpensive to create, and the actual audiobuffers can be reused for multiple plays of the sound.
... audiobuffersourcenode.start() used to schedule playback of the audio data contained in the buffer, or to begin playback immediately.
AudioContext.createMediaElementSource() - Web APIs
e.pagey : event.clienty + (document.documentelement.scrolltop ?
... document.documentelement.scrolltop : document.body.scrolltop); gainnode.gain.value = cury/height; } // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(gainnode); gainnode.connect(audioctx.destination); note: as a consequence of calling createmediaelementsource(), audio playback from the htmlmediaelement will be re-routed into the processing graph of the audiocontext.
AudioScheduledSourceNode.start() - Web APIs
if no time is specified, then the sound begins playing immediately.
...a value of 0 (or omitting the when parameter entirely) causes the sound to start playback immediately.
AudioScheduledSourceNode.stop() - Web APIs
if no time is specified, then the sound stops playing immediately.
...omitting this parameter, specifying a value of 0, or passing a negative value causes the sound to stop playback immediately.
BaseAudioContext.createChannelSplitter() - Web APIs
the createchannelsplitter() method of the baseaudiocontext interface is used to create a channelsplitternode, which is used to access the individual channels of an audio stream and process them separately.
... syntax baseaudiocontext.createchannelsplitter(numberofoutputs); parameters numberofoutputs the number of channels in the input audio stream that you want to output separately; the default is 6 if this parameter is not specified.
Battery Status API - Web APIs
navigator.getbattery().then(function(battery) { function updateallbatteryinfo(){ updatechargeinfo(); updatelevelinfo(); updatecharginginfo(); updatedischarginginfo(); } updateallbatteryinfo(); battery.addeventlistener('chargingchange', function(){ updatechargeinfo(); }); function updatechargeinfo(){ console.log("battery charging?
..."yes" : "no")); } battery.addeventlistener('levelchange', function(){ updatelevelinfo(); }); function updatelevelinfo(){ console.log("battery level: " + battery.level * 100 + "%"); } battery.addeventlistener('chargingtimechange', function(){ updatecharginginfo(); }); function updatecharginginfo(){ console.log("battery charging time: " + battery.chargingtime + " seconds"); } battery.addeventlistener('dischargingtimechange', function(){ updatedischarginginfo(); }); function updatedischarginginfo(){ console.log("battery discharging time: " + battery.dischargingtime + " seconds"); } }); see also the example in the specification.
CanvasPattern.setTransform() - Web APIs
html <canvas id="canvas"></canvas> <svg id="svg1"></svg> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var svg1 = document.getelementbyid('svg1'); var matrix = svg1.createsvgmatrix(); var img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ...
.../div> <textarea id="code" class="playable-code" style="height:120px"> var img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); };</textarea> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var edit = document.getelementbyid('edit'); var code = textarea.value; var svg1 = document.getelementbyid('svg1'); var matrix = svg1.createsvgmatrix(); function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.valu...
CanvasRenderingContext2D.addHitRegion() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); canvas.addeventlistener('mousemove', function(event) { if(event.region) { alert('ouch, my eye :('); } }); ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi); ctx.linewidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi); ctx.arc(130, 80, 10, 0, 2 * math.pi); ctx.fill(); ctx.addhitregion({id: "e...
...e" style="height:250px"> ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi, false); ctx.linewidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.arc(130, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi, false); ctx.stroke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; dra...
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
html <canvas id="canvas"></canvas> javascript // define canvas and context const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // define the points as {x, y} let start = { x: 50, y: 20 }; let cp1 = { x: 230, y: 30 }; let cp2 = { x: 150, y: 80 }; let end = { x: 250, y: 100 }; // cubic bézier curve ctx.beginpath(); ctx.moveto(start.x, start.y); ctx.beziercurveto(cp1.x, cp1.y, cp2.x, cp2.y, end.x, end.y); ctx.stroke(); // start and end points ctx...
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(30, 30); ctx.beziercurveto(120,160, 180,10, 220,140); ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.beziercurveto' in that specification.
CanvasRenderingContext2D.clearRect() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.clearrect(0, 0, canvas.width, canvas.height); erasing part of a canvas this example draws a blue triangle on top of a yellowish background.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw yellow background ctx.beginpath(); ctx.fillstyle = '#ff6'; ctx.fillrect(0, 0, canvas.width, canvas.height); // draw blue triangle ctx.beginpath(); ctx.fillstyle = 'blue'; ctx.moveto(20, 20); ctx.lineto(180, 20); ctx.lineto(130, 130); ctx.closepath(); ctx.fill(); // clear part of the canvas ctx.clearrect(10, 10, 120, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingc...
CanvasRenderingContext2D.clip() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create circular clipping region ctx.beginpath(); ctx.arc(100, 75, 50, 0, math.pi * 2); ctx.clip(); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = 'orange'; ctx.fillrect(0, 0, 100, 100); result specifying a path and a fillrule this example saves two rectangl...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create clipping path let region = new path2d(); region.rect(80, 10, 20, 130); region.rect(40, 50, 100, 50); ctx.clip(region, "evenodd"); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.clip' in that specification.
CanvasRenderingContext2D.closePath() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(20, 140); // move pen to bottom-left corner ctx.lineto(120, 10); // line to top corner ctx.lineto(220, 140); // line to bottom-right corner ctx.closepath(); // line to bottom-left corner ctx.stroke(); result closing just one sub-path this example draws a smiley face consisting of three disconnec...
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(240, 20, 40, 0, math.pi); ctx.moveto(100, 20); ctx.arc(60, 20, 40, 0, math.pi); ctx.moveto(215, 80); ctx.arc(150, 80, 65, 0, math.pi); ctx.closepath(); ctx.linewidth = 6; ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.closepath' in that specification.
CanvasRenderingContext2D.createImageData() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 50); console.log(imagedata); // imagedata { width: 100, height: 50, data: uint8clampedarray[20000] } filling a blank imagedata object this example creates and fills a new imagedata object with purple pixels.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 100); // iterate through every pixel for (let i = 0; i < imagedata.data.length; i += 4) { // modify pixel data imagedata.data[i + 0] = 190; // r value imagedata.data[i + 1] = 0; // g value imagedata.data[i + 2] = 210; // b value imagedata.data[i + 3] = 255; // a value } // draw image data to the canvas ctx.putimagedata(imagedata, 20, 20); result more examples for more examples using createimagedata()...
CanvasRenderingContext2D.drawImage() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const image = document.getelementbyid('source'); image.addeventlistener('load', e => { ctx.drawimage(image, 33, 71, 104, 124, 21, 20, 87, 104); }); result understanding source element size the drawimage() method uses the source element's intrinsic size in css pixels when drawing.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const image = new image(60, 45); // using optional size for image image.onload = drawimageactualsize; // draw when image has loaded // load an image of intrinsic size 300x227 in css pixels image.src = 'https://udn.realityripple.com/samples/db/f374e9c6fc.jpg'; function drawimageactualsize() { // use the intrinsic size of image in css pi...
CanvasRenderingContext2D.ellipse() - Web APIs
html <canvas id="canvas" width="200" height="200"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw the ellipse ctx.beginpath(); ctx.ellipse(100, 100, 50, 75, math.pi / 4, 0, 2 * math.pi); ctx.stroke(); // draw the ellipse's line of reflection ctx.beginpath(); ctx.setlinedash([5, 5]); ctx.moveto(0, 200); ctx.lineto(200, 0); ctx.stroke(); result various elliptical arcs this example creates three elliptical paths with varyin...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'red'; ctx.beginpath(); ctx.ellipse(60, 75, 50, 30, math.pi * .25, 0, math.pi * 1.5); ctx.fill(); ctx.fillstyle = 'blue'; ctx.beginpath(); ctx.ellipse(150, 75, 50, 30, math.pi * .25, 0, math.pi); ctx.fill(); ctx.fillstyle = 'green'; ctx.beginpath(); ctx.ellipse(240, 75, 50, 30, math.pi * .25, 0, math.pi, true); ctx.fill(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.ellipse' in that specification.
CanvasRenderingContext2D.fill() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill(); result specifying a path and a fillrule this example saves some intersecting lines to a path2d object.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create path let region = new path2d(); region.moveto(30, 90); region.lineto(110, 20); region.lineto(240, 130); region.lineto(60, 130); region.lineto(190, 20); region.lineto(270, 90); region.closepath(); // fill path ctx.fillstyle = 'green'; ctx.fill(region, 'evenodd'); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.fill' in that specification.
CanvasRenderingContext2D.fillRect() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(20, 10, 150, 100); result filling the whole canvas this code snippet fills the entire canvas with a rectangle.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillrect(0, 0, canvas.width, canvas.height); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.fillrect' in that specification.
CanvasRenderingContext2D.fillStyle - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); result creating multiple fill colors using loops in this example, we use two for loops to draw a grid of rectangles, each having a different fill color.
... <canvas id="canvas" width="150" height="150"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); for (let i = 0; i < 6; i++) { for (let j = 0; j < 6; j++) { ctx.fillstyle = `rgb( ${math.floor(255 - 42.5 * i)}, ${math.floor(255 - 42.5 * j)}, 0)`; ctx.fillrect(j * 25, i * 25, 25, 25); } } the result looks like this: screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontex...
CanvasRenderingContext2D.fillText() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.filltext('hello world', 50, 90); this code obtains a reference to the <canvas>, then gets a reference to its 2d graphics context.
... html <canvas id="canvas" width="400" height="150"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.filltext('hello world', 50, 90, 140); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.filltext' in that specification.
CanvasRenderingContext2D.getLineDash() - Web APIs
syntax ctx.getlinedash(); return value an array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units).
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.setlinedash([10, 20]); console.log(ctx.getlinedash()); // [10, 20] // draw a dashed line ctx.beginpath(); ctx.moveto(0, 50); ctx.lineto(300, 50); ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.getlinedash' in that specifica...
CanvasRenderingContext2D.isPointInPath() - Web APIs
html <canvas id="canvas"></canvas> <p>in path: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innertext = ctx.ispointinpath(30, 70); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in a circular path2d path.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create circle const circle = new path2d(); circle.arc(150, 75, 50, 0, 2 * math.pi); ctx.fillstyle = 'red'; ctx.fill(circle); // listen for mouse moves canvas.addeventlistener('mousemove', function(event) { // check whether point is inside circle if (ctx.ispointinpath(circle, event.offsetx, event.offsety)) { ctx.fillstyle = 'green'; } else { ctx.fillstyle = 'red'; } // draw circle ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.fill(circle); }); result specifications specification status comment html living standardthe definition of 'canv...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
html <canvas id="canvas"></canvas> <p>in stroke: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innertext = ctx.ispointinstroke(50, 10); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical path2d path.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create ellipse const ellipse = new path2d(); ellipse.ellipse(150, 75, 40, 60, math.pi * .25, 0, 2 * math.pi); ctx.linewidth = 25; ctx.strokestyle = 'red'; ctx.fill(ellipse); ctx.stroke(ellipse); // listen for mouse moves canvas.addeventlistener('mousemove', function(event) { // check whether point is inside ellipse's stroke if (ctx.ispointinstroke(ellipse, event.offsetx, event.offsety)) { ctx.strokestyle = 'green'; } else { ctx.strokestyle = 'red'; } // draw ellipse ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.fill(ellipse); ctx.stroke(ellipse); }); ...
CanvasRenderingContext2D.lineDashOffset - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.setlinedash([4, 16]); // dashed line with no offset ctx.beginpath(); ctx.moveto(0, 50); ctx.lineto(300, 50); ctx.stroke(); // dashed line with offset of 4 ctx.beginpath(); ctx.strokestyle = 'red'; ctx.linedashoffset = 4; ctx.moveto(0, 100); ctx.lineto(300, 100); ctx.stroke(); result the line with a dash offset is drawn in red.
... html <canvas id="canvas"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let offset = 0; function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.setlinedash([4, 2]); ctx.linedashoffset = -offset; ctx.strokerect(10, 10, 100, 100); } function march() { offset++; if (offset > 16) { offset = 0; } draw(); settimeout(march, 20); } march(); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d...
CanvasRenderingContext2D.lineJoin - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 20; ctx.linejoin = 'round'; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(190, 100); ctx.lineto(280, 20); ctx.lineto(280, 150); ctx.stroke(); result comparison of line joins the example below draws three different paths, demonstrating each of the three linejoin options.
... <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getelementbyid('canvas').getcontext('2d'); var linejoin = ['round', 'bevel', 'miter']; ctx.linewidth = 10; for (let i = 0; i < linejoin.length; i++) { ctx.linejoin = linejoin[i]; ctx.beginpath(); ctx.moveto(-5, 5 + i * 40); ctx.lineto(35, 45 + i * 40); ctx.lineto(75, 5 + i * 40); ctx.lineto(115, 45 + i * 40); ctx.lineto(155, 5 + i * 40); ctx.stroke(); } screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.linejoin' in that specification.
CanvasRenderingContext2D.lineTo() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); // start a new path ctx.moveto(30, 50); // move the pen to (30, 50) ctx.lineto(150, 100); // draw a line to (150, 100) ctx.stroke(); // render the path result drawing connected lines each call of lineto() (and similar methods) automatically adds to the current sub-path, which means that all the line...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.moveto(90, 130); ctx.lineto(95, 25); ctx.lineto(150, 80); ctx.lineto(205, 25); ctx.lineto(210, 130); ctx.linewidth = 15; ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.lineto' in that specification.
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // quadratic bézier curve ctx.beginpath(); ctx.moveto(50, 20); ctx.quadraticcurveto(230, 30, 50, 100); ctx.stroke(); // start and end points ctx.fillstyle = 'blue'; ctx.beginpath(); ctx.arc(50, 20, 5, 0, 2 * math.pi); // start point ctx.arc(50, 100, 5, 0, 2 * math.pi); // end point ctx.fill(); // control point ctx.fillstyle = 'red'; ...
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(20, 110); ctx.quadraticcurveto(230, 150, 250, 20); ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.quadraticcurveto' in that specification.
CanvasRenderingContext2D.resetTransform() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw a rotated rectangle ctx.rotate(45 * math.pi / 180); ctx.fillrect(60, 0, 100, 30); // reset transformation matrix to the identity matrix ctx.resettransform(); result continuing with a regular matrix whenever you're done drawing transformed shapes, you should call resettransform() before rendering anything else.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // skewed rectangles ctx.transform(1, 0, 1.7, 1, 0, 0); ctx.fillstyle = 'gray'; ctx.fillrect(40, 40, 50, 20); ctx.fillrect(40, 90, 50, 20); // non-skewed rectangles ctx.resettransform(); ctx.fillstyle = 'red'; ctx.fillrect(40, 40, 50, 20); ctx.fillrect(40, 90, 50, 20); result the skewed rectangles are gray, and the non-skewed rectangles are red.
CanvasRenderingContext2D.rotate() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // point of transform origin ctx.arc(0, 0, 5, 0, 2 * math.pi); ctx.fillstyle = 'blue'; ctx.fill(); // non-rotated rectangle ctx.fillstyle = 'gray'; ctx.fillrect(100, 0, 80, 20); // rotated rectangle ctx.rotate(45 * math.pi / 180); ctx.fillstyle = 'red'; ctx.fillrect(100, 0, 80, 20); // reset transformation matrix to the identity matrix ...
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // non-rotated rectangle ctx.fillstyle = 'gray'; ctx.fillrect(80, 60, 140, 30); // matrix transformation ctx.translate(150, 75); ctx.rotate(math.pi / 2); ctx.translate(-150, -75); // rotated rectangle ctx.fillstyle = 'red'; ctx.fillrect(80, 60, 140, 30); result the non-rotated rectangle is gray, and the rotated rectangle is red.
CanvasRenderingContext2D.scale() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // scaled rectangle ctx.scale(9, 3); ctx.fillstyle = 'red'; ctx.fillrect(10, 10, 8, 20); // reset current transformation matrix to the identity matrix ctx.settransform(1, 0, 0, 1, 0, 0); // non-scaled rectangle ctx.fillstyle = 'gray'; ctx.fillrect(10, 10, 8, 20); result the scaled rectangle is red, and the non-scaled rectangle is gray...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.scale(-1, 1); ctx.font = '48px serif'; ctx.filltext('hello world!', -280, 90); ctx.settransform(1, 0, 0, 1, 0, 0); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.scale' in that specification.
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.fillrect(10, 10, 30, 30); ctx.scrollpathintoview(); edit the code below to see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"> <input id="button" type="range" min="1" max="12"> </canvas> <div class="playable-buttons"> <input id="edit" ty...
...pe="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginpath(); ctx.rect(10, 10, 30, 30); ctx.scrollpathintoview();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener("click", function() { textarea.focus(); }) textarea.addeventlistener("input", drawcanvas); window.addeventlistener("load", d...
CanvasRenderingContext2D.strokeRect() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.strokestyle = 'green'; ctx.strokerect(20, 10, 160, 100); result applying various context settings this example draws a rectangle with a drop shadow and thick, beveled outlines.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.shadowcolor = '#d53'; ctx.shadowblur = 20; ctx.linejoin = 'bevel'; ctx.linewidth = 15; ctx.strokestyle = '#38f'; ctx.strokerect(30, 30, 160, 90); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.strokerect' in that specification.
CanvasRenderingContext2D.strokeStyle - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.strokestyle = 'blue'; ctx.strokerect(10, 10, 100, 100); result creating multiple stroke colors using loops in this example, we use two for loops and the arc() method to draw a grid of circles, each having a different stroke color.
...(the red channel has a fixed value.) <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getelementbyid('canvas').getcontext('2d'); for (let i = 0; i < 6; i++) { for (let j = 0; j < 6; j++) { ctx.strokestyle = `rgb( 0, ${math.floor(255 - 42.5 * i)}, ${math.floor(255 - 42.5 * j)})`; ctx.beginpath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, math.pi * 2, true); ctx.stroke(); } } the result looks like this: screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.strokestyle' in that...
CanvasRenderingContext2D.strokeText() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.stroketext('hello world', 50, 90); this code obtains a reference to the <canvas>, then gets a reference to its 2d graphics context.
... html <canvas id="canvas" width="400" height="150"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.stroketext('hello world', 50, 90, 140); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.stroketext' in that specification.
CanvasRenderingContext2D.textAlign - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); canvas.width = 350; const ctx = canvas.getcontext('2d'); const x = canvas.width / 2; ctx.beginpath(); ctx.moveto(x, 0); ctx.lineto(x, canvas.height); ctx.stroke(); ctx.font = '30px serif'; ctx.textalign = 'left'; ctx.filltext('left-aligned', x, 40); ctx.textalign = 'center'; ctx.filltext('center-aligned', x, 85); ctx.textalign = 'right'; ctx.filltext('right-aligned', x, 1...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '30px serif'; ctx.direction = 'ltr'; ctx.textalign = 'start'; ctx.filltext('start-aligned', 0, 50); ctx.textalign = 'end'; ctx.filltext('end-aligned', canvas.width, 120); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.textalign' in that specification.
A basic ray-caster - Web APIs
so every update, the raycaster looks to see if you've pressed any keys lately, to conserve calculations by not casting if you're idle.
... also, it leaves a lot to be desired in terms of trying to be any sort of game engine—there are no wall textures, no sprites, no doors, not even any teleporters to get to another level.
Manipulating video using canvas - Web APIs
var processor; processor.doload = function doload() { this.video = document.getelementbyid('video'); this.c1 = document.getelementbyid('c1'); this.ctx1 = this.c1.getcontext('2d'); this.c2 = document.getelementbyid('c2'); this.ctx2 = this.c2.getcontext('2d'); let self = this; this.video.addeventlistener('play', function() { self.width = self.video.videowidth / 2; self.height = self.video.videoheight / 2; self.timercallback(); ...
... processor.timercallback = function timercallback() { if (this.video.paused || this.video.ended) { return; } this.computeframe(); let self = this; settimeout(function() { self.timercallback(); }, 0); }, the first thing the callback does is check to see if the video is even playing; if it's not, the callback returns immediately without doing anything.
Canvas API - Web APIs
html <canvas id="canvas"></canvas> javascript the document.getelementbyid() method gets a reference to the html <canvas> element.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 150, 100); result reference htmlcanvaselement canvasrenderingcontext2d canvasgradient canvasimagesource canvaspattern imagebitmap imagedata renderingcontext textmetrics offscreencanvas path2d imagebitmaprenderingcontext note: the interfaces related to the webglrenderingc...
ChannelMergerNode - Web APIs
this is useful for accessing each channels separately, e.g.
... for performing channel mixing where gain must be separately controlled on each channel.
ChannelSplitterNode - Web APIs
this is useful for accessing each channel separately, e.g.
... for performing channel mixing where gain must be separately controlled on each channel.
CharacterData - Web APIs
nondocumenttypechildnode.nextelementsibling read only returns the element immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.
... nondocumenttypechildnode.previouselementsibling read only returns the element immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list.
ContentIndex.getAll() - Web APIs
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const ...
...listelem = document.createelement('ul'); for (const entry of entries) { const listitem = document.createelement('li'); const anchorelem = document.createelement('a'); anchorelem.innertext = entry.title; anchorelem.setattribute('href', entry.url); listelem.append(listitem); } readinglistelem.append(listelem); } } specifications specification status comment unknownthe definition of 'getall' in that specification.
ContentIndex - Web APIs
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const ...
...listelem = document.createelement('ul'); for (const entry of entries) { const listitem = document.createelement('li'); const anchorelem = document.createelement('a'); anchorelem.innertext = entry.title; anchorelem.setattribute('href', entry.url); listelem.append(listitem); } readinglistelem.append(listelem); } } unregistering indexed content below is an asynchronous function, that removes an item from the content index.
CustomElementRegistry.whenDefined() - Web APIs
if the custom element is already defined, the promise is resolved immediately.
... <menu-item>item n</menu-item> </nav-menu> </nav> const container = document.getelementbyid('menu-container'); const placeholder = container.queryselector('.menu-placeholder'); // fetch all the children of menu that are not yet defined.
DOMImplementation.createHTMLDocument() - Web APIs
here's the html for this example: <body> <p>click <a href="javascript:makedocument()">here</a> to create a new document and insert it below.</p> <iframe id="theframe" src="about:blank" /> </body> the javascript implementation of makedocument() follows: function makedocument() { let frame = document.getelementbyid("theframe"); let doc = document.implementation.createhtmldocument("new document"); let p = doc.createelement("p"); p.innerhtml = "this is a new paragraph."; try { doc.body.appendchild(p); } catch(e) { console.log(e); } // copy the new html document into the frame let destdocument = frame.contentdocument; let srcnode = doc.documentelement; let newnode = des...
...tdocument.importnode(srcnode, true); destdocument.replacechild(newnode, destdocument.documentelement); } the code in lines 4–12 handle creating the new html document and inserting some content into it.
DOMMatrixReadOnly - Web APIs
if no matrix is specified as the multiplier, the matrix is multiplied by a matrix in which every element is 0 except the bottom-right corner and the element immediately above and to its left: m33 and m34.
...if no matrix is specified, the matrix is initialized with every element set to 0 except the bottom-right corner and the element immediately above and to its left: m33 and m34.
DataTransfer.clearData() - Web APIs
status">drag to start</span></div> <div>data is: <span id="data">uninitialized</span></div> css span.tweaked { display: inline-block; margin: 1em 0; padding: 1em 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript window.addeventlistener('domcontentloaded', function () { // select html elements var draggable = document.getelementbyid('source'); var dropable = document.getelementbyid('target'); var status = document.getelementbyid('status'); var data = document.getelementbyid('data'); var dropped = false; // register event handlers draggable.addeventlistener('dragstart', dragstarthandler); draggable.addeventlistener('dragend', dragendhandler); dropable.addeventlistener('dragover', dragoverhandler); ...
...); } function dragleavehandler (event) { status.innerhtml = 'drag in process (drop was available)'; event.preventdefault(); } function drophandler (event) { dropped = true; status.innerhtml = 'drop done'; event.preventdefault(); // get data linked to event format « text » var _data = event.datatransfer.getdata('text/plain'); var element = document.getelementbyid(_data); // append drag source element to event's target element event.target.appendchild(element); // change css styles and displayed text element.style.csstext = 'border: 1px solid black;display: block; color: red'; element.innerhtml = "i'm in the drop zone!"; } }) specifications specification status comment html living standardthe de...
DeprecationReportBody - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside 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.
... the report details are displayed via the displayreports() fuction, which takes the observer callback's reports parameter as its parameter: function displayreports(reports) { const outputelem = document.queryselector('.output'); const list = document.createelement('ul'); outputelem.appendchild(list); for(let i = 0; i < reports.length; i++) { let listitem = document.createelement('li'); let textnode = document.createtextnode('report ' + (i + 1) + ', type: ' + reports[i].type); listitem.appendchild(textnode); let innerlist = document.createelement('ul'); listitem.appendchild(innerlist); list.appendchild(listitem); for (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; i...
Document.onfullscreenchange - Web APIs
the document interface's onfullscreenchange property is an event handler for the fullscreenchange event that is fired immediately before a document transitions into or out of full-screen mode.
... example document.onfullscreenchange = function ( event ) { console.log("full screen change") }; document.documentelement.onclick = function () { // requestfullscreen() must be in an event handler or it will fail document.documentelement.requestfullscreen(); } specifications specification status comment fullscreen apithe definition of 'onfullscreenchange' in that specification.
Document.write() - Web APIs
WebAPIDocumentwrite
after writing, call document.close() to tell the browser to finish loading the page.
...for example: <script> document.write("<h1>main title</h1>") </script> note: document.write() and document.writeln do not work in xhtml documents (you'll get an "operation is not supported" [ns_error_dom_not_supported_err] error in the error console).
DocumentOrShadowRoot.activeElement - Web APIs
often activeelement will return a htmlinputelement or htmltextareaelement object if it has the text selection at the time.
...morbi sed euismod diam.</textarea> </form> <p>active element id: <b id="output-element"></b></p> <p>selected text: <b id="output-text"></b></p> javascript function onmouseup(e) { const activetextarea = document.activeelement; const selection = activetextarea.value.substring( activetextarea.selectionstart, activetextarea.selectionend ); const outputelement = document.getelementbyid('output-element'); const outputtext = document.getelementbyid('output-text'); outputelement.innerhtml = activetextarea.id; outputtext.innerhtml = selection; } const textarea1 = document.getelementbyid('ta-example-one'); const textarea2 = document.getelementbyid('ta-example-two'); textarea1.addeventlistener('mouseup', onmouseup, false); textarea2.addeventliste...
Example - Web APIs
<html> <head> <title>my document</title> <script type="text/javascript"> function change() { // document.getelementsbytagname("h1") returns a nodelist of the h1 // elements in the document, and the first is number 0: var header = document.getelementsbytagname("h1").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document".
... var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the first paragraph."; // create a new text node for the second paragraph var newtext = document.createtextnode("this is the second paragraph."); // create a new element to be the second paragraph var newelement = document.createelement("p"); // put the text in the paragraph newelement.appendchild(newtext); // and put the paragraph on the end of the document by appending it to // the body (which is the parent of para) para.parentnode.appendchild(newelement); } </script> </head> <body> <input type="button" value="change this document." onclick="change()"> <h1>header</h1> <p>paragraph</p> </body> </head> ...
Using the W3C DOM Level 1 Core - Web APIs
the following script would do the job: html content <body> <input type="button" value="change this document." onclick="change()"> <h2>header</h2> <p>paragraph</p> </body> javascript content function change() { // document.getelementsbytagname("h2") returns a nodelist of the <h2> // elements in the document, and the first is number 0: var header = document.getelementsbytagname("h2").item(0); // the firstchild of the header is a text node: header.firstchild.data = "a dynamic document"; // now the header is "a dynamic document".
... var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the first paragraph."; // create a new text node for the second paragraph var newtext = document.createtextnode("this is the second paragraph."); // create a new element to be the second paragraph var newelement = document.createelement("p"); // put the text in the paragraph newelement.appendchild(newtext); // and put the paragraph on the end of the document by appending it to // the body (which is the parent of para) para.parentnode.appendchild(newelement); } you can see this script as a complete example.
Element.animate() - Web APIs
WebAPIElementanimate
examples in the demo down the rabbit hole (with the web animation api), we use the convenient animate() method to immediately create and play an animation on the #tunnel element to make it flow upwards, infinitely.
... document.getelementbyid("tunnel").animate([ // keyframes { transform: 'translatey(0px)' }, { transform: 'translatey(-300px)' } ], { // timing options duration: 1000, iterations: infinity }); implicit to/from keyframes in newer browser versions, you are able to set a beginning or end state for an animation only (i.e.
Element.attributes - Web APIs
syntax var attr = element.attributes; example basic examples // get the first <p> element in the document var para = document.getelementsbytagname("p")[0]; var atts = para.attributes; enumerating elements attributes numerical indexing is useful for going through all of an element's attributes.
... <!doctype html> <html> <head> <title>attributes example</title> <script type="text/javascript"> function listattributes() { var paragraph = document.getelementbyid("paragraph"); var result = document.getelementbyid("result"); // first, let's verify that the paragraph has some attributes if (paragraph.hasattributes()) { var attrs = paragraph.attributes; var output = ""; for(var i = attrs.length - 1; i >= 0; i--) { output += attrs[i].name + "->" + attrs[i].value; } result.value = output; } else { result.value = "no attributes to show"; } } </script> </hea...
Element.classList - Web APIs
WebAPIElementclassList
document.documentelement.firstchild.appendchild(document.createelement('style')).stylesheet.csstext=( '_*{x-uclp:expression(!this.hasownproperty("classlist")&&window[" ucl"](this))}' + // ie6 '[class]{x-uclp/**/:expression(!this.hasownproperty("classlist")&&window[" ucl"](this))}' //ie7-8 ); } })(window); // 3.
...however, such actions would not work in ie6-ie8 and, in ie9, slow the performance of the entire webpage to a snail's crawl, making these modifications completely impractical for this polyfill.
Element.getAttributeNS() - Web APIs
<svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="hello namespaced attribute!"/> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getelementbyid( 'target' ); console.log( 'attribute test:foo: "' + circle.getattributens( ns, 'foo' ) + '"' ); </script> </svg> in an html5 document the attribute has to be accessed with test:foo since namespaces are not supported.
... <!doctype html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="foo value"/> </svg> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getelementbyid( 'target' ); console.log('attribute value: ' + circle.getattribute('test:foo')); </script> </body> </html> notes namespaces are only supported in xml documents.
Element.releasePointerCapture() - Web APIs
syntax targetelement.releasepointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object.
...lign-items: center; justify-content: center; background: #fbe; } javascript function beginsliding(e) { slider.onpointermove = slide; slider.setpointercapture(e.pointerid); } function stopsliding(e) { slider.onpointermove = null; slider.releasepointercapture(e.pointerid); } function slide(e) { slider.style.transform = `translate(${e.clientx - 70}px)`; } const slider = document.getelementbyid('slider'); slider.onpointerdown = beginsliding; slider.onpointerup = stopsliding; result specifications specification status comment pointer events – level 2the definition of 'releasepointercapture' in that specification.
Element.setCapture() - Web APIs
<html> <head> <title>mouse capture example</title> <style type="text/css"> #mybutton { border: solid black 1px; color: black; padding: 2px; box-shadow: black 2px 2px; } </style> <script type="text/javascript"> function init() { var btn = document.getelementbyid("mybutton"); if (btn.setcapture) { btn.addeventlistener("mousedown", mousedown, false); btn.addeventlistener("mouseup", mouseup, false); } else { document.getelementbyid("output").innerhtml = "sorry, there appears to be no setcapture support on this browser"; } } function mousedown(e) { e.target.setcapture(); e.targ...
...et.addeventlistener("mousemove", mousemoved, false); } function mouseup(e) { e.target.removeeventlistener("mousemove", mousemoved, false); } function mousemoved(e) { var output = document.getelementbyid("output"); output.innerhtml = "position: " + e.clientx + ", " + e.clienty; } </script> </head> <body onload="init()"> <p>this is an example of how to use mouse capture on elements in gecko 2.0.</p> <p><a id="mybutton" href="#">test me</a></p> <div id="output">no events yet</div> </body> </html> view live examples notes the element may not be scrolled completely to the top or bottom, depending on the layout of other elements.
Element.setPointerCapture() - Web APIs
syntax targetelement.setpointercapture(pointerid); parameters pointerid the pointerid of a pointerevent object.
...lign-items: center; justify-content: center; background: #fbe; } javascript function beginsliding(e) { slider.onpointermove = slide; slider.setpointercapture(e.pointerid); } function stopsliding(e) { slider.onpointermove = null; slider.releasepointercapture(e.pointerid); } function slide(e) { slider.style.transform = `translate(${e.clientx - 70}px)`; } const slider = document.getelementbyid('slider'); slider.onpointerdown = beginsliding; slider.onpointerup = stopsliding; result specifications specification status comment pointer events – level 2the definition of 'setpointercapture' in that specification.
ElementCSSInlineStyle.style - Web APIs
examples // set multiple styles in a single statement elt.style.csstext = "color: blue; border: 1px solid black"; // or elt.setattribute("style", "color:red; border: 1px solid blue;"); // set specific style while leaving other inline style values untouched elt.style.color = "blue"; getting style information the style property is not useful for completely learning about the styles applied on the element, since it represents only the css declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets.
... the following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the getcomputedstyle() method: <!doctype html> <html> <body style="font-weight:bold;"> <div style="color:red" id="myelement">..</div> </body> </html> var element = document.getelementbyid("myelement"); var out = ""; var elementstyle = element.style; var computedstyle = window.getcomputedstyle(element, null); for (prop in elementstyle) { if (elementstyle.hasownproperty(prop)) { out += " " + prop + " = '" + elementstyle[prop] + "' > '" + computedstyle[prop] + "'\n"; } } console.log(out) the output would be something like: ...
Comparison of Event Targets - Web APIs
</thead> <tr> <td id="target"></td> <td id="currenttarget"></td> <td id="relatedtarget"></td> <td id="explicitoriginaltarget"></td> <td id="originaltarget"></td> </tr> </table> <p>clicking on the text will show the difference between explicitoriginaltarget, originaltarget, and target</p> <script> function handleclicks(e) { document.getelementbyid('target').innerhtml = e.target; document.getelementbyid('currenttarget').innerhtml = e.currenttarget; document.getelementbyid('relatedtarget').innerhtml = e.relatedtarget; document.getelementbyid('explicitoriginaltarget').innerhtml = e.explicitoriginaltarget; document.getelementbyid('originaltarget').innerhtml = e.originaltarget; } function handle...
...mouseover(e) { document.getelementbyid('target').innerhtml = e.target; document.getelementbyid('relatedtarget').innerhtml = e.relatedtarget; } document.addeventlistener('click', handleclicks, false); document.addeventlistener('mouseover', handlemouseover, false); </script> </body> </html> use of target and relatedtarget the relatedtarget property for the mouseover event holds the node that the mouse was previously over.
EventTarget.removeEventListener() - Web APIs
if a listener is registered twice, one with capture and one without, remove each one separately.
... const body = document.queryselector('body') const clicktarget = document.getelementbyid('click-target') const mouseovertarget = document.getelementbyid('mouse-over-target') let toggle = false; function makebackgroundyellow() { if (toggle) { body.style.backgroundcolor = 'white'; } else { body.style.backgroundcolor = 'yellow'; } toggle = !toggle; } clicktarget.addeventlistener('click', makebackgroundyellow, false ); mouseovertarget.
FileList - Web APIs
WebAPIFileList
for example, if the html includes the following file input: <input id="fileitem" type="file"> the following line of code fetches the first file in the node's file list as a file object: var file = document.getelementbyid('fileitem').files[0]; method overview file item(index); properties attribute type description length integer a read-only value indicating the number of files in the list.
... example this example iterates over all the files selected by the user using an input element: // fileinput is an html input element: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; var file; // loop through 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.
FileSystemDirectoryEntry.removeRecursively() - Web APIs
androidopera for androidsafari on iossamsung internetremoverecursively deprecatednon-standardchrome full support 8edge full support 79firefox no support 50 — 52notes no support 50 — 52notes notes while the removerecursively() method existed, it immediately called the error callback with ns_error_dom_security_err.ie no support noopera no support nosafari no support nowebview android full support ≤37chrome android full support ...
... 18firefox android no support 50 — 52notes no support 50 — 52notes notes while the removerecursively() method existed, it immediately called the error callback with ns_error_dom_security_err.opera android no support nosafari ios no support nosamsung internet android full support yeslegend full support full support no support no supportnon-standard.
FileSystemDirectoryEntry - Web APIs
full support yesremoverecursively deprecatednon-standardchrome full support 8edge full support 79firefox no support 50 — 52notes no support 50 — 52notes notes while the removerecursively() method existed, it immediately called the error callback with ns_error_dom_security_err.ie no support noopera no support nosafari no support nowebview android full support ≤37chrome android full support ...
... 18firefox android no support 50 — 52notes no support 50 — 52notes notes while the removerecursively() method existed, it immediately called the error callback with ns_error_dom_security_err.opera android no support nosafari ios no support nosamsung internet android full support yeslegend full support full support no support no supportexperimental.
FileSystemFileEntry.createWriter() - Web APIs
irefox for androidopera for androidsafari on iossamsung internetcreatewriter deprecatednon-standardchrome full support 8edge full support 79firefox no support 50 — 52notes no support 50 — 52notes notes while the createwriter() method existed, it immediately called errorcallback with the ns_error_dom_security_err error.ie no support noopera no support nosafari no support nowebview android full support ≤37chrome android full support ...
... 18firefox android no support 50 — 52notes no support 50 — 52notes notes while the createwriter() method existed, it immediately called errorcallback with the ns_error_dom_security_err error.opera android no support nosafari ios no support nosamsung internet android full support yeslegend full support full support no support no supportnon-standard.
FileSystemFileEntry - Web APIs
yesprefixed prefixed implemented with the vendor prefix: webkitcreatewriter deprecatednon-standardchrome full support 8edge full support 79firefox no support 50 — 52notes no support 50 — 52notes notes while the createwriter() method existed, it immediately called errorcallback with the ns_error_dom_security_err error.ie no support noopera no support nosafari no support nowebview android full support ≤37chrome android full support ...
... 18firefox android no support 50 — 52notes no support 50 — 52notes notes while the createwriter() method existed, it immediately called errorcallback with the ns_error_dom_security_err error.opera android no support nosafari ios no support nosamsung internet android full support yesfilechrome full support 8edge full support 79firefox full support 50ie no support noopera no support ...
Using FormData Objects - Web APIs
creating a formdata object from scratch you can build a formdata object yourself, instantiating it then appending fields to it by calling its append() method, like this: var formdata = new formdata(); formdata.append("username", "groucho"); formdata.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // html file input, chosen by user formdata.append("userfile", fileinputelement.files[0]); // javascript file-like object var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
...the number assigned to the field "accountnum" is immediately converted into a string by the formdata.append() method (the field's value can be a blob, file, or a string: if the value is neither a blob nor a file, the value is converted to a string).
FullscreenOptions.navigationUI - Web APIs
example in this example, the entire document is placed into full-screen mode by calling requestfullscreen() on the document's document.documentelement, which is the document's root <html> element.
... let elem = document.documentelement; elem.requestfullscreen({ navigationui: "show" }).then({}).catch(err => { alert(`an error occurred while trying to switch into full-screen mode: ${err.message} (${err.name})`); }); the promise's resolve handler does nothing, but if the promise is rejected, an error message is displayed by calling alert().
GlobalEventHandlers.onanimationcancel - Web APIs
function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.innerhtml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the handlecancelevent() function, which is called in response to the animationcancel event, as set up in the html above.
... function handlecancelevent(event) { log("animation canceled", event); }; then we add a method to handle toggle display between "flex" and "none" and establish it as the handler for a click event on the "hide/show" the box button: document.getelementbyid('togglebox').addeventlistener('click', function() { if (box.style.display == "none") { box.style.display = "flex"; document.getelementbyid("togglebox").innerhtml = "hide the box"; } else { box.style.display = "none"; document.getelementbyid("togglebox").innerhtml = "show the box"; } }); toggling the box to display: none has the effect of aborting its animation.
GlobalEventHandlers.onanimationend - Web APIs
function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.innerhtml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the event handlers for the animationstart and animationend events: let box = document.getelementbyid("box"); box.onanimationstart = function(even...
...t) { log("animation started", event); } box.onanimationend = function(event) { log("animation stopped", event); }; finally, we set up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeventlistener("click", function(event) { document.getelementbyid("box").classname = "slideanimation"; event.target.style.display = "none"; }, false); this sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once.
GlobalEventHandlers.onanimationiteration - Web APIs
var box = document.getelementbyid("box"); var iterationcounter = 0; box.onanimationiteration = function(event) { box.style.animationplaystate = "paused"; document.getelementbyid("play").innerhtml = "start iteration #" + (iterationcounter+1); }; this sets up two global variables: box, which references the "box" element that we're animating, and iterationcounter, which is initially zero, which indicates how many ite...
... finally, we set up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeventlistener("click", function(event) { box.style.animationplaystate = "running"; iterationcounter++; }, false); this sets the box element's animation-play-state to "running" and increments the iteration counter.
GlobalEventHandlers.onanimationstart - Web APIs
function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.innerhtml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the event handlers for the animationstart and animationend events: let box = document.getelementbyid("box"); box.onanimationstart = function(even...
...t) { log("animation started", event); } box.onanimationend = function(event) { log("animation stopped", event); }; finally, we set up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeventlistener("click", function(event) { document.getelementbyid("box").classname = "slideanimation"; event.target.style.display = "none"; }, false); this sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once.
GlobalEventHandlers.onclick - Web APIs
html <div id="demo">click here</div> javascript document.getelementbyid('demo').onclick = function changecontent() { document.getelementbyid('demo').innerhtml = "help me"; document.getelementbyid('demo').style = "color: red"; } result getting the coordinates of clicks this example displays the coordinates at which the most recent mouse button click occurred.
... html <p>click anywhere in this example.</p> <p id="log"></p> javascript let log = document.getelementbyid('log'); document.onclick = inputchange; function inputchange(e) { log.textcontent = `position: (${e.clientx}, ${e.clienty})`; } result specification specification status comment html living standardthe definition of 'onclick' in that specification.
GlobalEventHandlers.ondrag - Web APIs
syntax var draghandler = targetelement.ondrag; return value draghandler the drag event handler for element targetelement.
...; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <!-- <div class="source"> --> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element...
GlobalEventHandlers.ondragover - Web APIs
syntax var dragoverhandler = targetelement.ondragover; return value dragoverhandler the dragover event handler for element targetelement.
...; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and...
GlobalEventHandlers.ondragstart - Web APIs
syntax var dragstarthandler = targetelement.ondragstart; return value dragstarthandler the dragstart event handler for element targetelement.
...; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and...
GlobalEventHandlers.ondrop - Web APIs
syntax var drophandler = targetelement.ondrop; return value drophandler the drop event handler for element targetelement.
...; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } function drop_handler(ev) { console.log("drop"); ev.currenttarget.style.background = "lightyellow"; ev.preventdefault(); var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div class="source"> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to th...
GlobalEventHandlers.onpointercancel - Web APIs
syntax targetelement.onpointercancel = cancelhandler; var cancelhandler = targetelement.onpointercancel; value cancelhandler the pointercancel event handler for element targetelement.
... <html> <script> function cancelhandler(ev) { // process the pointercancel event } function init() { var el = document.getelementbyid('target1'); el.onpointercancel = cancelhandler; } </script> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.onpointerenter - Web APIs
syntax targetelement.onpointerenter = enterhandler; var enterhandler = targetelement.onpointerenter; value enterhandler the pointerenter event handler for element targetelement.
... <html> <script> function enterhandler(ev) { // process the pointerenter event } function init() { let el = document.getelementbyid('target1'); el.onpointerenter = enterhandler; } </script> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.onpointermove - Web APIs
syntax targetelement.onpointermove = movehandler; var movehandler = targetelement.onpointermove; value movehandler the pointermove event handler for element targetelement.
... <html> <script> function movehandler(ev) { // process the pointermove event } function init() { let el=document.getelementbyid('target1'); el.onpointermove = movehandler; } </script> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.onpointerout - Web APIs
syntax targetelement.onpointerout = outhandler; var outhandler = targetelement.onpointerout; value outhandler the pointerout event handler for element targetelement.
... <html> <script> function outhandler(ev) { // process the pointerout event } function init() { let el=document.getelementbyid('target1'); el.onpointerout = outhandler; } </script> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.onpointerover - Web APIs
syntax targetelement.onpointerover = overhandler; var overhandler = targetelement.onpointerover; value overhandler the pointerover event handler for element targetelement.
... <html> <script> function overhandler(ev) { // process the pointerover event } function init() { let el = document.getelementbyid('target1'); el.onpointerover = overhandler; } </script> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.onpointerup - Web APIs
syntax targetelement.onpointerup = uphandler; var uphandler = targetelement.onpointerup; value uphandler the pointerup event handler for element targetelement.
... <html> <script> function uphandler(ev) { // process the pointerup event } function init() { let el = document.getelementbyid('target1'); el.onpointerup = uphandler; } </script> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.ontouchend - Web APIs
syntax var endhandler = targetelement.ontouchend; return value endhandler the touchend event handler for element targetelement.
... <html> <script> function endtouch(ev) { // process the event } function init() { var el=document.getelementbyid("target1"); el.ontouchend = endtouch; } </script> <body onload="init();"> <div id="target1"> touch me ...
HTMLCanvasElement.toDataURL() - Web APIs
examples given this <canvas> element: <canvas id="canvas" width="5" height="5"></canvas> you can get a data-url of the canvas with the following lines: var canvas = document.getelementbyid('canvas'); var dataurl = canvas.todataurl(); console.log(dataurl); // "data:image/png;base64,ivborw0kggoaaaansuheugaaaauaaaafcayaaacnby // blaaaadeleqvqimwngobmaaabpaafei8araaaaaelftksuqmcc" setting image quality with jpegs var fullquality = canvas.todataurl('image/jpeg', 1.0); // data:image/jpeg;base64,/9j/4aaqskzjrgabaq...9oadambaairaxeapwd/ad/6ap/z" var mediumquality = canvas.todat...
...class="grayscale" src="mypicture.png" alt="description of my picture" /> javascript window.addeventlistener('load', removecolors); function showcolorimg() { this.style.display = 'none'; this.nextsibling.style.display = 'inline'; } function showgrayimg() { this.previoussibling.style.display = 'inline'; this.style.display = 'none'; } function removecolors() { var aimages = document.getelementsbyclassname('grayscale'), nimgslen = aimages.length, ocanvas = document.createelement('canvas'), octx = ocanvas.getcontext('2d'); for (var nwidth, nheight, oimgdata, ograyimg, npixel, apix, npixlen, nimgid = 0; nimgid < nimgslen; nimgid++) { ocolorimg = aimages[nimgid]; nwidth = ocolorimg.offsetwidth; nheight = ocolorimg.offsetheight; ocanvas.width = nwidt...
HTMLElement: beforeinput event - Web APIs
bubbles yes cancelable yes interface inputevent event handler 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.queryselector('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.
HTMLElement: change event - Web APIs
eam"> <option value="">select one …</option> <option value="chocolate">chocolate</option> <option value="sardine">sardine</option> <option value="vanilla">vanilla</option> </select> </label> <div class="result"></div> body { display: grid; grid-template-areas: "select result"; } select { grid-area: select; } .result { grid-area: result; } javascript const selectelement = document.queryselector('.ice-cream'); selectelement.addeventlistener('change', (event) => { const result = document.queryselector('.result'); result.textcontent = `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.
... html <input placeholder="enter some text" name="name"/> <p id="log"></p> javascript const input = document.queryselector('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.
HTMLElement.hidden - Web APIs
javascript document.getelementbyid("okbutton") .addeventlistener("click", function() { document.getelementbyid("welcome").hidden = true; document.getelementbyid("awesome").hidden = false; }, false); this code sets up a handler for the welcome panel's "ok" button that hides the welcome panel and makes the follow-up panel—with the curious name "awesome"—visible in its place.
... the welcome panel <div id="welcome" class="panel"> <h1>welcome to foobar.com!</h1> <p>by clicking "ok" you agree to be awesome every day!</p> <button class="button" id="okbutton">ok</button> </div> this html creates a panel (in a <div> block) that welcomes the user to a site and tells them what they're agreeing to by clicking the ok button.
HTMLElement.offsetHeight - Web APIs
syntax var intelemoffsetheight = element.offsetheight; intelemoffsetheight is a variable storing an integer corresponding to the offsetheight pixel value of the element.
...these elements are typically contained within scrollable elements; consequently, these non-scrollable elements may be completely or partly invisible, depending on the scrolltop setting of the scrollable container.
HTMLElement.offsetLeft - Web APIs
example var colortable = document.getelementbyid("t1"); var toleft = colortable.offsetleft; if (toleft > 5) { // large left offset: do something here } this example shows a 'long' sentence that wraps within a div with a blue border, and a red box that one might think should describe the boundaries of the span.
...</span> <span id="longspan">long span that wraps within this div.</span> </div> <div id="box" style="position: absolute; border-color: red; border-width: 1; border-style: solid; z-index: 10"> </div> <script type="text/javascript"> var box = document.getelementbyid("box"); var longspan = document.getelementbyid("longspan"); box.style.left = longspan.offsetleft + document.body.scrollleft + "px"; box.style.top = longspan.offsettop + document.body.scrolltop + "px"; box.style.width = longspan.offsetwidth + "px"; box.style.height = longspan.offsetheight + "px"; </script> specification specification status comment css object model (cssom) view modu...
HTMLFormElement.elements - Web APIs
<form id="my-form"> <input type="text" name="username"> <input type="text" name="full-name"> <input type="password" name="password"> </form> var inputs = document.getelementbyid("my-form").elements; var inputbyindex = inputs[0]; var inputbyname = inputs["username"]; accessing form controls this example gets the form's element list, then iterates over the list, looking for <input> elements of type "text" so that some form of processing can be performed on them.
... var inputs = document.getelementbyid("my-form").elements; // iterate over the form controls for (i = 0; i < inputs.length; i++) { if (inputs[i].nodename === "input" && inputs[i].type === "text") { // update text input inputs[i].value.tolocaleuppercase(); } } disabling form controls var inputs = document.getelementbyid("my-form").elements; // iterate over the form controls for (i = 0; i < inputs.length; i++) { // disable all form controls inputs[i].setattribute("disabled", ""); } specifications specification status comment html living standardthe definition of 'htmlformelement.elements' in that specification.
HTMLImageElement - Web APIs
htmlimageelement.loading a domstring providing a hint to the browser used to optimize loading the document by determining whether to load the image immediately (eager) or on an as-needed basis (lazy).
... htmlimageelement.referrerpolicy a domstring that reflects the referrerpolicy html attribute, which tells the user agent how to decide which referrer to use in order to fetch the image.
HTMLMediaElement.seekToNextFrame() - Web APIs
this method returns immediately, returning a promise, whose fulfillment handler is called when the seek operation is complete.
...if the seek fails because the media is already at the last frame, a seeked event occurs, followed immediately by an ended event.
HTMLElement.focus() - Web APIs
examples focus on a text field javascript focusmethod = function getfocus() { document.getelementbyid("mytextfield").focus(); } html <input type="text" id="mytextfield" value="text field."> <p></p> <button type="button" onclick="focusmethod()">click me to focus on the text field!</button> result focus on a button javascript focusmethod = function getfocus() { document.getelementbyid("mybutton").focus(); } html <button type="button" id="mybutton">click me!</button>...
... <p></p> <button type="button" onclick="focusmethod()">click me to focus on the button!</button> result focus with focusoption javascript focusscrollmethod = function getfocus() { document.getelementbyid("mybutton").focus({preventscroll:false}); } focusnoscrollmethod = function getfocuswithoutscrolling() { document.getelementbyid("mybutton").focus({preventscroll:true}); } html <button type="button" onclick="focusscrollmethod()">click me to focus on the button!</button> <button type="button" onclick="focusnoscrollmethod()">click me to focus on the button without scrolling!</button> <div id="container" style="height: 1000px; width: 1000px;"> <button type="button" id="mybutton" style="margin-top: 500px;">click me!</button> </div> result specification ...
HTMLTableRowElement.insertCell() - Web APIs
the cell does not need to be appended separately with node.appendchild() as would be the case if document.createelement() had been used to create the new <td> element.
... html <table id="my-table"> <tr><td>row 1</td></tr> <tr><td>row 2</td></tr> <tr><td>row 3</td></tr> </table> javascript function addrow(tableid) { // get a reference to the table let tableref = document.getelementbyid(tableid); // insert a row at the end of the table let newrow = tableref.insertrow(-1); // insert a cell in the row at index 0 let newcell = newrow.insertcell(0); // append a text node to the cell let newtext = document.createtextnode('new bottom row'); newcell.appendchild(newtext); } // call addrow() with the table's id addrow('my-table'); result specifications ...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
consider the javascript program below: let outputelem = document.getelementbyid("output"); let userlanguages = { "mike": "en", "teresa": "es" }; function greetuser(user) { function localgreeting(user) { let greeting; let language = userlanguages[user]; switch(language) { case "es": greeting = `¡hola, ${user}!`; break; case "en": default: greeting = `hello, ${user}!`; break; ...
... } return greeting; } outputelem.innerhtml += localgreeting(user) + "<br>\r"; } greetuser("mike"); greetuser("teresa"); greetuser("veronica"); this short program contains three execution contexts, some of which are created and destroyed several times over the course of the program's execution.
Dragging and Dropping Multiple Items - Web APIs
// [item1] data=url1, index=0 // [item2] data=url3, index=1 fortunately, you don't normally need to clear items often; it's more common to just add the items only when you know they are needed.
... output(" item " + i + ":\n"); var types = dt.moztypesat(i); for (var t = 0; t < types.length; t++) { output(" " + types[t] + ": "); try { var data = dt.mozgetdataat(types[t], i); output("(" + (typeof data) + ") : <" + data + " >\n"); } catch (ex) { output("<<error>>\n"); dump(ex); } } } } function output(text) { document.getelementbyid("output").textcontent += text; dump(text); } </script> </head> <body> <div id="output" style="min-height: 100px; white-space: pre; border: 1px solid black;" ondragenter="document.getelementbyid('output').textcontent = ''; event.stoppropagation(); event.preventdefault();" ondragover="event.stoppropagation(); event.preventdefault();" ondrop="event.stoppropagation(); even...
IDBDatabase - Web APIs
methods inherits from: eventtarget idbdatabase.close() returns immediately and closes the connection to a database in a separate thread.
... idbdatabase.transaction() immediately returns a transaction object (idbtransaction) containing the idbtransaction.objectstore method, which you can use to access your object store.
Basic concepts - Web APIs
they also have readystate, result, and errorcode properties that tell you the status of the request.
... out-of-line key a key that is stored separately from the value being stored.
Checking when a deadline is due - Web APIs
if not, we drop a message into our developer notifications pane (see the bottom left of the app ui) to tell the user what is going on, and exit out of the function.
...we want all the values to match before we show the user some kind of notification to tell them their deadline is up.
IntersectionObserver.unobserve() - Web APIs
var observer = new intersectionobserver(callback); observer.observe(document.getelementbyid("elementtoobserve")); /* ...
... */ observer.unobserve(document.getelementbyid("elementtoobserve")); specifications specification status comment intersection observerthe definition of 'intersectionobserver.unobserve()' in that specification.
IntersectionObserver - Web APIs
intersectionobserver.observe() tells the intersectionobserver a target element to observe.
... intersectionobserver.unobserve() tells the intersectionobserver to stop observing a particular target element.
Timing element visibility with the Intersection Observer API - Web APIs
and the threshold is set to an array containing the values 0.0 and 0.75; this will cause our callback to execute whenever a targeted element becomes completely obscured or first starts to become unobscured (intersection ratio 0.0) or passes through 75% visible in either direction (intersection ratio 0.75).
...the ad's background color is set to the value specified in the new ad's record, and elements' classes and contents are set appropriately as well.
KeyboardEvent.code - Web APIs
de values are for each one.</p> <div id="output"> </div> css #output { font-family: arial, helvetica, sans-serif; border: 1px solid black; } javascript window.addeventlistener("keydown", function(event) { let str = "keyboardevent: key='" + event.key + "' | code='" + event.code + "'"; let el = document.createelement("span"); el.innerhtml = str + "<br/>"; document.getelementbyid("output").appendchild(el); }, true); try it out to ensure that keystrokes go to the sample, click in the output box below before pressing keys.
... let shipsize = { width: 30, height: 30 }; let position = { x: 200, y: 200 }; let moverate = 9; let turnrate = 5; let angle = 0; let spaceship = document.getelementbyid("spaceship"); next comes the function updateposition().
KeyboardEvent.key - Web APIs
WebAPIKeyboardEventkey
in sequence 1 & 3, the keyboardevent.key attribute is defined and is set appropriately to a value according to the rules defined ealier.
... id="console-log"></pre> </div> </div> css .fx { -webkit-display: flex; display: flex; margin-left: -20px; margin-right: -20px; } .fx > div { padding-left: 20px; padding-right: 20px; } .fx > div:first-child { width: 30%; } .flex { -webkit-flex: 1; flex: 1; } #test-target { display: block; width: 100%; margin-bottom: 10px; } javascript let textarea = document.getelementbyid('test-target'), consolelog = document.getelementbyid('console-log'), btnclearconsole = document.getelementbyid('btn-clear-console'); function logmessage(message) { document.getelementbyid("console-log").innerhtml += message + "<br>"; } textarea.addeventlistener('keydown', (e) => { if (!e.repeat) logmessage(`key "${e.key}" pressed [event: keydown]`); else logmessage(`key ...
KeyframeEffect.target - Web APIs
syntax var targetelement = document.getelementbyid("elementtoanimate"); var keyframes = new keyframeeffect( targetelement, keyframeblock, timingoptions ); // returns #elementtoanimate keyframes.target; // assigns keyframes a new target keyframes.target = newtargetelement; value an element, csspseudoelement, or null.
... examples in the follow the white rabbit example, whiterabbit sets the target element to be animated: var whiterabbit = document.getelementbyid("rabbit"); var rabbitdownkeyframes = new keyframeeffect( whiterabbit, [ { transform: 'translatey(0%)' }, { transform: 'translatey(100%)' } ], { duration: 3000, fill: 'forwards' } ); // returns <div id=​"rabbit">​click the rabbit's ears!​</div>​ rabbitdownkeyframes.target; specifications specification status comment web animationsthe definition of 'keyframeeffect' in that specification.
MSCandidateWindowShow - Web APIs
mscandidatewindowshow fires immediately after the input method editor (ime) candidate window is set to appear, but before it renders.
... example in ie11, developers can detect the opening of the ime candidate window by listening to mscandidatewindowshow event, then call getcandidatewindowclientrect() function to find out where the candidate window is and position the suggestion ui away from it: var context = document.getelementbyid("mysearchbox").msgetinputcontext(); context.addeventlistener("mscandidatewindowshow", candidatewindowshowhandler); function candidatewindowshowhandler(e) { var imerect = context.getcandidatewindowclientrect(); var suggestionrect = document.getelementbyid("mysuggestionlist").getboundingclientrect(); // check if the two rects intersect, and position them away from each other.
MediaDevices.ondevicechange - Web APIs
let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: { width: 160, height: 120, framerate: 30 }, audio: { samplerate: 44100, samplesize: 16, volume...
...: 0.25 } }).then(stream => { videoelement.srcobject = stream; updatedevicelist(); }) .catch(err => log(err.name + ": " + err.message)); }, false); we set up global variables that contain references to the <ul> elements that are used to list the audio and video devices: let audiolist = document.getelementbyid("audiolist"); let videolist = document.getelementbyid("videolist"); getting and drawing the device list now let's take a look at updatedevicelist() itself.
MediaElementAudioSourceNode - Web APIs
e.pagey : event.clienty + (document.documentelement.scrolltop ?
... document.documentelement.scrolltop : document.body.scrolltop); gainnode.gain.value = cury/height; } // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(gainnode); gainnode.connect(audioctx.destination); note: as a consequence of calling createmediaelementsource(), audio playback from the htmlmediaelement will be re-routed into the processing graph of the audiocontext.
MediaStreamTrack: mute event - Web APIs
musictrack.addeventlistener("mute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; }, false); musictrack.addeventlistener("unmute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; }, false); with these event handlers in place, when the track musictrack enters its muted state, the element with the id timeline-widget gets its background color changed to #aaa.
...the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; } musictrack.mute = event = > { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; } specifications specification status comment media capture and streamsthe definition of 'mute' in that specification.
MediaStreamTrack: unmute event - Web APIs
musictrack.addeventlistener("mute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; }, false); musictrack.addeventlistener("unmute", event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; }, false); with these event handlers in place, when the track musictrack enters its muted state, the element with the id timeline-widget gets its background color changed to #aaa.
...the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; } musictrack.mute = event = > { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; } specifications specification status comment media capture and streamsthe definition of 'unmute' in that specification.
Using the Media Capabilities API - Web APIs
on> <option>2500</option> <option>800</option> </select> </li> </ul> <p><input type="button" value="test this video configuration" id="tryit"></p> </form> <ul id="results"></ul> javascript let mc = { videoconfiguration : new object(), tryit: function () { mc.createconfiguration(); mc.testit(); }, createconfiguration: function () { var size = document.getelementbyid('size').value.split('x'); mc.videoconfiguration = { type: 'file', video: { contenttype: document.getelementbyid('codec').value, width: size[0], height: size[1], bitrate: document.getelementbyid('bitrate').value, framerate: document.getelementbyid('framerate').value, } } }, testit: function () { let content = ''; ...
...' is ' : ' is not ') + 'power efficient.'; var ul = document.getelementbyid("results") li.innerhtml = content; ul.appendchild(li); }).catch((error) => { var li = document.createelement('li'), ul = document.getelementbyid("results"); li.innertext = 'codec ' + mc.videoconfiguration.video.contenttype + ' threw an error: ' + error; ul.appendchild(li); }); } } document.getelementbyid('tryit').addeventlistener...
MutationObserver.takeRecords() - Web APIs
the most common use case for this is to immediately fetch all pending mutation records immediately prior to disconnecting the observer, so that any pending mutations can be processed when stopping down the observer.
...this is done immediately prior to calling disconnect() to stop observing the dom.
Navigator.registerProtocolHandler() - Web APIs
for example, this api lets webmail sites open mailto: urls, or voip sites open tel: urls.
... otherwise, the scheme must be one of the following: bitcoin geo im irc ircs magnet mailto mms news nntp openpgp4fpr sip sms smsto ssh tel urn webcal wtai xmpp example if your site is burgers.example.com, you can register a protocol handler for it to handle web+burger: links, like so: navigator.registerprotocolhandler("web+burger", "https://burgers.example.com/?burger=%s", "burger handler"); this creates a handler that lets web+burger: links send the user...
Online and offline events - Web APIs
this property existed in older versions of firefox and internet explorer (the specification based itself off of these prior implementations), so you can begin using it immediately.
... here's the javascript part: window.addeventlistener('load', function() { var status = document.getelementbyid("status"); var log = document.getelementbyid("log"); function updateonlinestatus(event) { var condition = navigator.online ?
Node.previousSibling - Web APIs
the node.previoussibling read-only property returns the node immediately preceding the specified one in its parent's childnodes list, or null if the specified node is the first in that list.
... syntax previousnode = node.previoussibling; example <img id="b0"> <img id="b1"> <img id="b2"> console.log(document.getelementbyid("b1").previoussibling); // <img id="b0"> console.log(document.getelementbyid("b2").previoussibling.id); // "b1" notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup.
Node - Web APIs
WebAPINode
node.parentelementread only returns an element that is the parent of this node.
... sample usage the following example prints the textcontent properties of each <span> tag in a <div> element named "box": <div id="box"> <span>foo</span> <span>bar</span> <span>baz</span> </div> const box = document.getelementbyid("box") eachnode(box, function(node) { if (null != node.textcontent) { console.log(node.textcontent) } }) the above will result in the following strings printing to the user's console: "\n\t", "foo", "\n\t", "bar", "\n\t", "baz" note: whitespace forms part of a text node, meaning indentation and newlines form separate text between the element nodes.
NodeFilter.acceptNode() - Web APIs
the nodefilter.acceptnode() method returns an unsigned short that will be used to tell if a given node must be accepted or not by the nodeiterator or treewalker iteration algorithm.
... example var nodeiterator = document.createnodeiterator( // node to use as root document.getelementbyid('someid'), // only consider nodes that are text nodes (nodetype 3) nodefilter.show_text, // object containing the function to use for the acceptnode method // of the nodefilter { acceptnode: function(node) { // logic to determine whether to accept, reject or skip node // in this case, only accept nodes that have content // other than whitespace if ( ...
NodeFilter - Web APIs
nodefilter.acceptnode() returns an unsigned short that will be used to tell if a given node must be accepted or not by the nodeiterator or treewalker iteration algorithm.
... example const nodeiterator = document.createnodeiterator( // node to use as root document.getelementbyid('someid'), // only consider nodes that are text nodes (nodetype 3) nodefilter.show_text, // object containing the function to use for the acceptnode method // of the nodefilter { acceptnode: function(node) { // logic to determine whether to accept, reject or skip node // in this case, only accept nodes that have content // other than whitespace if ( ...
OffscreenCanvas - Web APIs
var one = document.getelementbyid("one").getcontext("bitmaprenderer"); var two = document.getelementbyid("two").getcontext("bitmaprenderer"); var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); // ...
... main.js (main thread code): var htmlcanvas = document.getelementbyid("canvas"); var offscreen = htmlcanvas.transfercontroltooffscreen(); var worker = new worker("offscreencanvas.js"); worker.postmessage({canvas: offscreen}, [offscreen]); offscreencanvas.js (worker code): onmessage = function(evt) { var canvas = evt.data.canvas; var gl = canvas.getcontext("webgl"); // ...
Path2D() - Web APIs
WebAPIPath2DPath2D
<canvas id="canvas"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let path1 = new path2d(); path1.rect(10, 10, 100,100); let path2 = new path2d(path1); path2.moveto(220, 60); path2.arc(170, 60, 50, 0, 2 * math.pi); ctx.stroke(path2); using svg paths this example creates a path2d path using svg path data.
... <canvas id="canvas"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let p = new path2d('m10 10 h 80 v 80 h -80 z'); ctx.fill(p); specification specification status comment html living standardthe definition of 'path2d()' in that specification.
PaymentAddress.phone - Web APIs
the read-only phone property of the paymentaddress interface returns a string containing the telephone number of the recipient or contact person.
... syntax var paymentphone = paymentaddress.phone; value a domstring containing the telephone number for the recipient of the shipment or of the responsible party for payment.
PaymentRequest.show() - Web APIs
instead of immediately failing, you could choose to call retry() on the response object to ask the user agent to try to process the payment again; this should usually only be done after the user has made any needed corrections to the order.
...} document.getelementbyid("buybutton").onclick = requestpayment; specifications specification status comment payment request apithe definition of 'show(optional detailspromise)' in that specification.
PerformanceNavigationTiming.domComplete - Web APIs
the domcomplete read-only property returns a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to complete.
... syntax perfentry.domcomplete; return value a timestamp representing a time value equal to the time immediately before the user agent sets the current document readiness of the current document to complete.
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
the domcontentloadedeventend read-only property returns a timestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes.
... syntax perfentry.domcontentloadedeventend; return value a timestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes.
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
the domcontentloadedeventstart read-only property returns a timestamp representing the time value equal to the time immediately before the user agent fires the domcontentloaded event at the current document.
... syntax perfentry.domcontentloadedeventstart; return value a timestamp representing the time value equal to the time immediately before the user agent fires the domcontentloaded event at the current document.
PerformanceNavigationTiming.domInteractive - Web APIs
the dominteractive read-only property returns a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive.
... syntax perfentry.dominteractive; return value a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive.
PerformanceNavigationTiming.loadEventStart - Web APIs
the loadeventstart read-only property returns a timestamp representing the time value equal to the time immediately before the load event of the current document is fired.
... syntax perfentry.loadeventstart; return value a timestamp representing a time value equal to the time immediately before the load event of the current document is fired.
PerformanceNavigationTiming.unloadEventEnd - Web APIs
the unloadeventend read-only property returns a timestamp representing the time value equal to the time immediately after the user agent finishes the unload event of the previous document.
... syntax perfentry.unloadeventend; return value a timestamp representing a time value equal to the time immediately after the user agent finishes the unload event of the previous document.
PerformanceNavigationTiming.unloadEventStart - Web APIs
the unloadeventstart read-only property returns a timestamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document.
... syntax perfentry.unloadeventstart; return value a timestamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document.
PerformanceResourceTiming.connectStart - Web APIs
the connectstart read-only property returns the timestamp immediately before the user agent starts establishing the connection to the server to retrieve the resource.
... syntax resource.connectstart; return value a domhighrestimestamp immediately before the browser starts to establish the connection to the server to retrieve the resource.
PerformanceResourceTiming.domainLookupEnd - Web APIs
the domainlookupend read-only property returns the timestamp immediately after the browser finishes the domain name lookup for the resource.
... syntax resource.domainlookupend; return value a domhighrestimestamp representing the time immediately after the browser finishes the domain name lookup for the resource.
PerformanceResourceTiming.domainLookupStart - Web APIs
the domainlookupstart read-only property returns the timestamp immediately before the browser starts the domain name lookup for the resource.
... syntax resource.domainlookupstart; return value a domhighrestimestamp immediately before the browser starts the domain name lookup for the resource.
PerformanceResourceTiming.requestStart - Web APIs
the requeststart read-only property returns a timestamp of the time immediately before the browser starts requesting the resource from the server, cache, or local resource.
... syntax resource.requeststart; return value a domhighrestimestamp representing the time immediately before the browser starts requesting the resource from the server example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.responseEnd - Web APIs
the responseend read-only property returns a timestamp immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.
... syntax resource.responseend; return value a domhighrestimestamp immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.
PerformanceResourceTiming.responseStart - Web APIs
the responsestart read-only property returns a timestamp immediately after the browser receives the first byte of the response from the server, cache, or local resource.
... syntax resource.responsestart; return value a domhighrestimestamp immediately after the browser receives the first byte of the response from the server.
PerformanceResourceTiming.secureConnectionStart - Web APIs
the secureconnectionstart read-only property returns a timestamp immediately before the browser starts the handshake process to secure the current connection.
... syntax resource.secureconnectionstart; return value if the resource is fetched over a secure connection, a domhighrestimestamp immediately before the browser starts the handshake process to secure the current connection.
Pointer Lock API - Web APIs
other examples include apps for viewing maps or satellite imagery.
... var tracker = document.getelementbyid('tracker'); var animation; function updateposition(e) { x += e.movementx; y += e.movementy; if (x > canvas.width + radius) { x = -radius; } if (y > canvas.height + radius) { y = -radius; } if (x < -radius) { x = canvas.width + radius; } if (y < -radius) { y = canvas.height + radius; } tracker.textcontent = "x position: " + x + ", y position: " + y; ...
Multi-touch interaction - Web APIs
function set_handlers(name) { // install event handlers for the given element var el=document.getelementbyid(name); el.onpointerdown = pointerdown_handler; el.onpointermove = pointermove_handler; // use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same.
...false : true; } function log(name, ev) { var o = document.getelementsbytagname('output')[0]; var s = name + ": pointerid = " + ev.pointerid + " ; pointertype = " + ev.pointertype + " ; isprimary = " + ev.isprimary; o.innerhtml += s + " "; } function clearlog(event) { var o = document.getelementsbytagname('output')[0]; o.innerhtml = ""; } ...
Pinch zoom gestures - Web APIs
function init() { // install event handlers for the pointer target var el=document.getelementbyid("target"); el.onpointerdown = pointerdown_handler; el.onpointermove = pointermove_handler; // use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same.
...false : true; } function log(prefix, ev) { if (!logevents) return; var o = document.getelementsbytagname('output')[0]; var s = prefix + ": pointerid = " + ev.pointerid + " ; pointertype = " + ev.pointertype + " ; isprimary = " + ev.isprimary; o.innerhtml += s + " "; } function clearlog(event) { var o = document.getelementsbytagname('output')[0]; o.innerhtml = ""; } ...
ProgressEvent - Web APIs
in other words, it tells if the progress is measurable or not.
... var progressbar = document.getelementbyid("p"), client = new xmlhttprequest() client.open("get", "magical-unicorns") client.onprogress = function(pe) { if(pe.lengthcomputable) { progressbar.max = pe.total progressbar.value = pe.loaded } } client.onloadend = function(pe) { progressbar.value = pe.loaded } client.send() specifications specification status comment xmlhttprequestthe definit...
RTCConfiguration.certificates - Web APIs
syntax let rtcconfiguration = { certificates: certificatelist }; let rtcconfiguration.certificates = [ cert1...
...one obvious benefit to providing your own is identity key continuity—if you use the same certificate for subsequent calls, the remote peer can tell you're the same caller.
RTCIceTransport: selectedcandidatepairchange event - Web APIs
let icetransport = pc.getsenders[0].transport.icetransport; let localprotoelem = document.getelementbyid("local-protocol"); let remoteprotoelem = document.getelementbyid("remote-protocol"); icetransport.addeventlistener("selectedcandidatepairchange", ev => { let pair = icetransport.getselectedcandidatepair(); localprotoelem.innertext = pair.local.protocol.touppercase(); remoteprotoelem.innertext = pair.remote.protocol.touppercase(); }, false) this can also be done by setting the ons...
... let icetransport = pc.getsenders[0].transport.icetransport; let localprotoelem = document.getelementbyid("local-protocol"); let remoteprotoelem = document.getelementbyid("remote-protocol"); icetransport.onselectedcandidatepairchange = ev => { let pair = icetransport.getselectedcandidatepair(); localprotoelem.innertext = pair.local.protocol.touppercase(); remoteprotoelem.innertext = pair.remote.protocol.touppercase(); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'selectedcandidatepairchange' in that specification.
RTCPeerConnection.removeTrack() - Web APIs
the rtcpeerconnection.removetrack() method tells the local end of the connection to stop sending media from the specified track, without actually removing the corresponding rtcrtpsender from the list of senders as reported by rtcpeerconnection.getsenders().
... var pc, sender; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerconnection(); var track = stream.getvideotracks()[0]; sender = pc.addtrack(track, stream); }); document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removetrack(sender); pc.close(); }, false); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.removetrack()' in that specification.
RTCRtpSender - Web APIs
you can also obtain access to an rtcdtmfsender which can be used to send dtmf codes (to simulate the user pressing buttons on a telephone's dial pad) to the remote peer.
... properties rtcrtpsender.dtmf read only an rtcdtmfsender which can be used to send dtmf tones using telephone-event payloads on the rtp session represented by the rtcrtpsender object.
Range.compareNode() - Web APIs
WebAPIRangecompareNode
the node is completely selected by the range.
... example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); returnvalue = range.comparenode(document.getelementsbytagname("p").item(0)); notes this method is obsolete; you should use the w3c dom range.compareboundarypoints() method.
Range.extractContents() - Web APIs
syntax documentfragment = range.extractcontents(); example basic example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); var documentfragment = range.extractcontents(); document.body.appendchild(documentfragment); moving items between containers this example lets you move items between two containers.
... html <p id="list1">123456</p> <button id="swap">swap selected item(s)</button> <p id="list2">abcdef</p> css body { pointer-events: none; } p { border: 1px solid; font-size: 2em; padding: .3em; } button { font-size: 1.2em; padding: .5em; pointer-events: auto; } javascript const list1 = document.getelementbyid('list1'); const list2 = document.getelementbyid('list2'); const button = document.getelementbyid('swap'); button.addeventlistener('click', e => { selection = window.getselection(); for (let i = 0; i < selection.rangecount; i++) { const range = selection.getrangeat(i); if (range.commonancestorcontainer === list1 || range.commonancestorcontainer.parentnode === list1)...
Range.selectNodeContents() - Web APIs
example range = document.createrange(); referencenode = document.getelementsbytagname("div")[0]; range.selectnodecontents(referencenode); live sample this example lets the user select and deselect a paragraph with buttons.
... html <p id="p"><b>use the buttons below</b> to select or deselect the contents of this paragraph.</p> <button id="select-button">select paragraph</button> <button id="deselect-button">deselect paragraph</button> javascript const p = document.getelementbyid('p'); const selectbutton = document.getelementbyid('select-button'); const deselectbutton = document.getelementbyid('deselect-button'); selectbutton.addeventlistener('click', e => { // clear any current selection const selection = window.getselection(); selection.removeallranges(); // select paragraph const range = document.createrange(); range.selectnodecontents(p); sele...
Range.setStart() - Web APIs
WebAPIRangesetStart
main st.<br> dodge city, ks<br> 67801<br> usa</p> <hr> <p>nodes in the original address:</p> <ol id="log"></ol> javascript const address = document.getelementbyid('address'); const log = document.getelementbyid('log'); // log info address.childnodes.foreach(node => { const li = document.createelement('li'); li.textcontent = `${node.nodename}, ${node.nodevalue}`; log.appendchild(li); }); // highlight the street and city const startoffset = 2; // start at third node: 101 e.
... html <p id="content">0123456789</p> <p id="log"></p> javascript const element = document.getelementbyid('content'); const textnode = element.childnodes[0]; const range = document.createrange(); range.setstart(textnode, 0); // start at first character range.setend(textnode, 5); // end at fifth character document.getelementbyid('log').textcontent = range; result specifications specification status comment domthe definition of 'range.setstart()' in that specif...
ReadableStream.ReadableStream() - Web APIs
underlyingsource can contain the following: start(controller) this is a method, called immediately when the object is constructed.
... note: you could define your own custom queuingstrategy, or use an instance of bytelengthqueuingstrategy or countqueuingstrategy for this object value.
ReadableStream.cancel() - Web APIs
cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read.
...to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close().
ReadableStreamDefaultReader.cancel() - Web APIs
cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read.
...to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close().
RelativeOrientationSensor - Web APIs
examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an relativeorientationsensor with a frequency of 60 times a second.
... note that the intel demo this is based on uses the absoluteoreintationsensor.
Report - Web APIs
WebAPIReport
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside 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.
... the report details are displayed via the displayreports() fuction, which takes the observer callback's reports parameter as its parameter: function displayreports(reports) { const outputelem = document.queryselector('.output'); const list = document.createelement('ul'); outputelem.appendchild(list); for(let i = 0; i < reports.length; i++) { let listitem = document.createelement('li'); let textnode = document.createtextnode('report ' + (i + 1) + ', type: ' + reports[i].type); listitem.appendchild(textnode); let innerlist = document.createelement('ul'); listitem.appendchild(innerlist); list.appendchild(listitem); for (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; i...
Resource Timing API - Web APIs
the first property in the processing model is starttime which returns the timestamp immediately before the resource loading process begins.
...the next stages are connectstart and connectend which are the timestamps immediately before and after connecting to the server, respectively.
Response.redirected - Web APIs
fetch("awesome-picture.jpg").then(function(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { elem.innerhtml = "unexpected redirect"; } else { elem.innerhtml = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out red...
...irects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this: fetch("awesome-picture.jpg", { redirect: "error" }).then(function(response) { return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); specifications specification status comment fetchthe definition of 'redirected' in that specification.
SVGAnimationElement - Web APIs
the svganimationelement interface is the base interface for all of the animation element interfaces: svganimateelement, svgsetelement, svganimatecolorelement, svganimatemotionelement and svganimatetransformelement.
... svganimationelement.targetelement read only an svgelement representing the element which is being animated.
SVGDocument - Web APIs
interface overview also implement none methods none properties domstring domain domstring referrer svgsvgelement rootelement domstring title domstring url normative document svg 1.1 (2nd edition) properties name type description domain domstring the domain name of the se...
... rootelement svgsvgelement the root "svg" in the document hierarchy.
SVGElement - Web APIs
svgelement.viewportelementread only the svgelement, which established the current viewport.
... abort fired when page loading is stopped before an svg element has been allowed to load completely.
SVGSVGElement - Web APIs
svgsvgelement.forceredraw() in rendering environments supporting interactivity, forces the user agent to immediately redraw all regions of the viewport that require updating.
... svgsvgelement.getelementbyid() searches this svg document fragment (i.e., the search is restricted to a subset of the document tree) for an element whose id is given by elementid.
SVGTransformList - Web APIs
any changes made to the item are immediately reflected in the list.
...any changes made to the item are immediately reflected in the list.
Using the Screen Capture API - Web APIs
a logical display surface is one which is in part or completely obscured, either by being overlapped by another object to some extent, or by being entirely hidden or offscreen.
... const videoelem = document.getelementbyid("video"); const logelem = document.getelementbyid("log"); const startelem = document.getelementbyid("start"); const stopelem = document.getelementbyid("stop"); // options for getdisplaymedia() var displaymediaoptions = { video: { cursor: "always" }, audio: false }; // set event listeners for the start and stop buttons startelem.addeventlistener("click", function(evt) { sta...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
use this method with clients.claim() to ensure that updates to the underlying service worker take effect immediately for both the current client and all other active clients.
... syntax serviceworkerglobalscope.skipwaiting().then(function() { //do something }); returns a promise that immediately resolves with undefined.
ServiceWorkerRegistration.showNotification() - Web APIs
if this value is absent or false, the desktop version of chrome will auto-minimize notifications after approximately twenty seconds.
...for example, this could be in the past when a notification is used for a message that couldn’t immediately be delivered because the device was offline, or in the future for a meeting that is about to start.
Service Worker API - Web APIs
download, install and activate at this point, your service worker will observe the following lifecycle: download install activate the service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.
... reacting to push messages: start up a service worker to send users a message to tell them new content is available.
Slottable: assignedSlot - Web APIs
the assignedslot read-only property of the slottable interface returns an htmlslotelement representing the <slot> element the node is inserted in.
... syntax var slotelement = elementinstance.assignedslot value an htmlslotelement instance, or null if the element is not assigned to a slot, or if the associated shadow root was attached with its mode set to closed (see element.attachshadow for further details).
SpeechSynthesis.cancel() - Web APIs
if an utterance is currently being spoken, speaking will stop immediately.
...this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); synth.cancel(); // utterance1 stops being spoken immediately, and both are removed from the queue specifications specification status comment web speech apithe definition of 'cancel()' in that specification.
Storage - Web APIs
WebAPIStorage
if(!localstorage.getitem('bgcolor')) { populatestorage(); } setstyles(); function populatestorage() { localstorage.setitem('bgcolor', document.getelementbyid('bgcolor').value); localstorage.setitem('font', document.getelementbyid('font').value); localstorage.setitem('image', document.getelementbyid('image').value); } function setstyles() { var currentcolor = localstorage.getitem('bgcolor'); var currentfont = localstorage.getitem('font'); var currentimage = localstorage.getitem('image'); document.getelementbyid('bgcolor').value =...
... currentcolor; document.getelementbyid('font').value = currentfont; document.getelementbyid('image').value = currentimage; htmlelem.style.backgroundcolor = '#' + currentcolor; pelem.style.fontfamily = currentfont; imgelem.setattribute('src', currentimage); } note: to see this running as a complete working example, see our web storage demo.
SubtleCrypto.deriveBits() - Web APIs
}, privatekey, 128 ); const buffer = new uint8array(sharedsecret, 0, 5); const sharedsecretvalue = document.queryselector(".ecdh .derived-bits-value"); sharedsecretvalue.classlist.add("fade-in"); sharedsecretvalue.addeventlistener("animationend", () => { sharedsecretvalue.classlist.remove("fade-in"); }); sharedsecretvalue.textcontent = `${buffer}...[${sharedsecret.bytelength} bytes total]`; } // generate 2 ecdh key pairs: one for alice and one for bob // in more normal usage, they would generate their key pairs // separately and exchange public keys securely const generatealiceskeypair = window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivebits"] ); const generatebobskeypair = window.crypto.subtle.generatekey(...
...56" }, keymaterial, 256 ); const buffer = new uint8array(derivedbits, 0, 5); const derivedbitsvalue = document.queryselector(".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.queryselector(".pbkdf2 .derive-bits-button"); derivebitsbutton.addeventlistener("click", () => { getderivedbits(); }); specifications specification status comment web cryptography apithe definition of 'subtlecrypto.derivebits()' in that specification.
Text - Web APIs
WebAPIText
text.assignedslot read only returns the htmlslotelement object associated with the element.
... slotable.assignedslot read only returns a htmlslotelement representing the <slot> the node is inserted in.
TextMetrics - Web APIs
html <canvas id="canvas" width="550" height="500"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const baselinesabovealphabetic = ['fontboundingboxascent', 'actualboundingboxascent', 'emheightascent', 'hangingbaseline']; const baselinesbelowalphabetic = ['ideographicbaseline', 'emheightdescent', 'actualboundingboxdescent', 'fontboundingboxdescent']; const baselines = [...baselinesabovealphabetic, ...
... it can therefore be useful to use the sum of actualboundingboxleft and actualboundingboxright as a more accurate way to get the absolute text width: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const text = 'abcdefghijklmnop'; ctx.font = 'italic 50px serif'; const textmetrics = ctx.measuretext(text); console.log(textmetrics.width); // 459.8833312988281 console.log(math.abs(textmetrics.actualboundingboxleft) + math.abs(textmetrics.actualboundingboxright)); // 462.8833333333333 specifications specification ...
Using the User Timing API - Web APIs
[" + i + "] = " + entries[i].name, 0); } // display each mark using getentriesname(); must look for each mark separately entries = performance.getentriesbyname("mark-1","mark"); for (var i=0; i < entries.length; i++) { if (i == 0) log("= getentriesbyname('mark-1', 'mark')", 0); log("...
...[" + i + "] = " + entries[i].name, 1); } // display each measure using getentriesname() - have to look for each measure separately entries = performance.getentriesbyname("measure-1","measure"); for (var i=0; i < entries.length; i++) { if (i == 0) log("= getentriesbyname('measure-1', 'measure')", 1); log("...
ValidityState.patternMismatch - Web APIs
if the field supports the pattern attribute -- which means the <input> is of type text, tel, email, url, password, or search -- and the pattern value is set to a valid regular expression, if the value don't doesn't conform to the constraints set by the pattern value, the patternmismatch property will be true.
... examples given the following: <p> <label>enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>)- <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-label="4-digit number" size="3"/> </label> </p> here we have 3 sections for a north american phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the pattern attribute set on each.
ValidityState - Web APIs
toolong read only a boolean that is true if the value exceeds the specified maxlength for htmlinputelement or htmltextareaelement objects, or false if its length is less than or equal to the maximum length.
... tooshort read only a boolean that is true if the value fails to meet the specified minlength for htmlinputelement or htmltextareaelement objects, or false if its length is greater than or equal to the minimum length.
WEBGL_compressed_texture_astc - Web APIs
availability: astc compression is typically available on mali arm gpus, intel gpus, and nividia tegra chips.
... constants blocks bits per pixel arraybuffer bytelength bytes if height and width are 512 ext.compressed_rgba_astc_4x4_khr ext.compressed_srgb8_alpha8_astc_4x4_khr 4x4 8.00 floor((width + 3) / 4) * floor((height + 3) / 4) * 16 262144 ext.compressed_rgba_astc_5x4_khr ext.compressed_srgb8_alpha8_astc_5x4_khr 5x4 6.40 floor((width + 4) / 5) * floor((height + 3) / 4) * 16 210944 ext.compr...
WebGL2RenderingContext - Web APIs
to get an object of this interface, call getcontext() on a <canvas> element, supplying "webgl2" as the argument: var canvas = document.getelementbyid('mycanvas'); var gl = canvas.getcontext('webgl2'); webgl 2 is an extension to webgl 1.
... webgl2renderingcontext.waitsync() returns immediately, but waits on the gl server until the given webglsync object is signaled.
WebGLProgram - Web APIs
examples using the program the steps to actually do some work with the program involve telling the gpu to use the program, bind the appropriate data and configuration options, and finally draw something to the screen.
... // use the program gl.useprogram(program); // bind existing attribute data gl.bindbuffer(gl.array_buffer, buffer); gl.enablevertexattribarray(attributelocation); gl.vertexattribpointer(attributelocation, 3, gl.float, false, 0, 0); // draw a single triangle gl.drawarrays(gl.triangles, 0, 3); deleting the program if there is an error linking the program or you wish to delete an existing program, then it is as simple as running webglrenderingcontext.deleteprogram().
Creating 3D objects using WebGL - Web APIs
// tell webgl how to pull out the positions from the position // buffer into the vertexposition attribute { const numcomponents = 3; ...
... drawing the cube next we need to add code to our drawscene() function to draw using the cube's index buffer, adding new gl.bindbuffer() and gl.drawelements() calls: // tell webgl which indices to use to index the vertices gl.bindbuffer(gl.element_array_buffer, buffers.indices); ...
Lighting in WebGL - Web APIs
fortunately, it's not all that hard to do, and this article will cover some of the basics.
... then we add the code to drawscene() to bind the normals array to a shader attribute so the shader code can get access to it: // tell webgl how to pull out the normals from // the normal buffer into the vertexnormal attribute.
Using WebRTC data channels - Web APIs
the rtcdatachannel object is returned immediately by createdatachannel(); you can tell when the connection has been made successfully by watching for the open event to be sent to the rtcdatachannel.
...this makes it easy to write efficient routines that make sure there's always data ready to send without over-using memory or swamping the channel completely.
Using bounded reference spaces - Web APIs
each vertex in the array has a y coordinate of 0 since the entire boundary is defined at floor level, extending upward to the ceiling or indefinitely.
... keep in mind that by default, the viewer's position is placed immediately above the floor, like a camera lying on the ground.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
if your app provides a way for the user to move through the virtual world without physically moving in the real world (a so-called teleportation mechanic), you can simply accept the new position and continue, allowing the jump from your previously-assumed position to be immediately corrected with the new position.
...instead, use the difference between the current position and the new tracking position to compute the new teleportation offset; that is, a transform applied to everything to adapt the position and orientation data from webxr to your needs.
Starting up and shutting down a WebXR session - Web APIs
be aware, however, that the emulator does not yet completely emulate all of the webxr api, so you may run into problems you're not expecting.
... const immersiveok = await navigator.xr.issessionsupported("immersive-vr"); if (immersiveok) { // create and use an immersive vr session } else { // create an inline session instead, or tell the user about the // incompatibility if inline is required } creating and starting the session a webxr session is represented by an xrsession object.
Web Authentication API - Web APIs
note that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it must be generated on the server in order to ensure the security of the registration process.
...note that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it must be generated on the server in order to ensure the security of the authentication process.
Web Locks API - Web APIs
the lock is automatically released when the callback returns, so usually the callback is an async function, which causes the lock to be released only when the async function has completely finished.
... ifavailable: if specified, the lock request will fail if the lock cannot be granted immediately without waiting.
Using the Web Speech API - Web APIs
this can sometimes be useful, say if a result is not completely clear and you want to display a list if alternatives for the user to choose the correct one from.
...we use the htmlselectelement selectedoptions property to return the currently selected <option> element.
Window.devicePixelRatio - Web APIs
in simpler terms, this tells the browser how many of the screen's actual pixels should be used to draw a single css pixel.
... html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // set display size (css pixels).
Window.getDefaultComputedStyle() - Web APIs
example simple example var elem1 = document.getelementbyid("elemid"); var style = window.getdefaultcomputedstyle(elem1); longer example <style> #elem-container { position: absolute; left: 100px; top: 200px; height: 100px; } </style> <div id="elem-container">dummy</div> <div id="output"></div> <script> var elem = document.getelementbyid("elem-container"); var thecssprop = 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).
window.postMessage() - Web APIs
this mechanism provides control over where messages are sent; for example, if postmessage() was used to transmit a password, it would be absolutely critical that this argument be a uri whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party.
...this is a completely foolproof way to avoid security problems.
Window.requestAnimationFrame() - Web APIs
the window.requestanimationframe() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint.
... const element = document.getelementbyid('some-element-you-want-to-animate'); let start; function step(timestamp) { if (start === undefined) start = timestamp; const elapsed = timestamp - start; // `math.min()` is used here to make sure that the element stops at exactly 200px.
Window.scrollX - Web APIs
WebAPIWindowscrollX
window.pagexoffset : (document.documentelement || document.body.parentnode || document.body).scrollleft; var y = (window.pageyoffset !== undefined) ?
... window.pageyoffset : (document.documentelement || document.body.parentnode || document.body).scrolltop; specification specification status comment css object model (cssom) view modulethe definition of 'window.scrollx' in that specification.
Window.scrollY - Web APIs
WebAPIWindowscrollY
document.documentelement.scrollleft : document.body.scrollleft; var y = supportpageoffset ?
...document.documentelement.scrolltop : document.body.scrolltop; specification specification status comment css object model (cssom) view modulethe definition of 'window.scrolly' in that specification.
Window - Web APIs
WebAPIWindow
window.requestanimationframe() tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
... domcontentloaded fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
self.createImageBitmap() - Web APIs
a sprite sheet is an image containing multiple smaller images, each of which you want to be able to render separately.
... var canvas = document.getelementbyid('mycanvas'), ctx = canvas.getcontext('2d'), image = new image(); // wait for the sprite sheet to load image.onload = function() { promise.all([ // cut out two sprites from the sprite sheet createimagebitmap(image, 0, 0, 32, 32), createimagebitmap(image, 32, 0, 32, 32) ]).then(function(sprites) { // draw each sprite onto the canvas ctx.drawimage(sprites[0], 0, 0); ctx.drawimage(sprites[1], 32, 32); }); } // load the sprite sheet from an image file image.src = 'sprites.png'; specifications specification status comment html living standardthe definition of 'createimagebitmap' in that specification.
Worker.terminate() - Web APIs
WebAPIWorkerterminate
the terminate() method of the worker interface immediately terminates the worker.
... example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated.
WorkerGlobalScope.navigator - Web APIs
ou call the following console.log(navigator); inside a worker (which would basically be the equivalent of self.console.log(self.navigator);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workernavigator object written to the console — something like the following: object {online: true, useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) ap…ml, like gecko) chrome/40.0.2214.93 safari/537.36", product: "gecko", platform: "macintel", appversion: "5.0 (macintosh; intel mac os x 10_10_1) applewebki…ml, like gecko) chrome/40.0.2214.93 safari/537.36"…} appcodename: "mozilla" appname: "netscape" appversion: "5.0 (macintosh; intel mac os x 10_10_1) applewebkit/537.36 (khtml, like gecko) chrome/40.0.2214...
....93 safari/537.36" hardwareconcurrency: 4 online: true platform: "macintel" product: "gecko" useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) applewebkit/537.36 (khtml, like gecko) chrome/40.0.2214.93 safari/537.36" __proto__: object you could use this navigator object to return more information about the runtime envinronment, as you might do with a normal navigator object.
WritableStream - Web APIs
methods writablestream.abort() aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
... the promise returned by the sink's write() method (line 40) tells the writablestream and its writer when to resolve defaultwriter.ready.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
by setting the mozbackgroundrequest property of the request object and modifying the example appropriately, you can create your own alert dialog to handle ssl exceptions in your firefox extension or xulrunner application.
...nsserrorsservice.nss_sec_error_base) - (status & 0xffff); switch (nsserr) { case 11: // sec_error_expired_certificate, sec(11) errname = 'securityexpiredcertificateerror'; break; case 12: // sec_error_revoked_certificate, sec(12) errname = 'securityrevokedcertificateerror'; break; // per bsmith, we will be unable to tell these errors apart very soon, // so it makes sense to just folder them all together already.
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
teleporting or setting the position of the viewer upon first creating a scene, you may need to set the user's position within the 3d world.
...applymousemovement() should be called when drawing a frame, immediately before fetching the viewer's pose using getviewerpose(), and the rendering should be performed in this reference space.
XRReferenceSpace: reset event - Web APIs
however, if that kind of "teleportation" is being used, you actually want to avoid jumping the user's position after tracking recovery, this can introduce additional and potentially jarring jumping.
... instead of allowing this to happen, you can integrate the emulatedposition into the teleportation offset calculated prior to calling getoffsetreferencespace() to create a new reference space whose updated effective origin is adjusted by the distance the viewer's position jumped since the previous frame.
XRSession - Web APIs
WebAPIXRSession
the select event is sent after the selectstart event is sent and immediately before the selectend event is sent.
...it is sent immediately before the squeezeend event is sent to indicate that the squeeze action is over.
XRViewerPose - Web APIs
for example, every player in a mmorpg might have an instance of xrviewerpose to provide a way to calculate what they can see; if the game provides a mechanism that tells the player if another player sees them, or that they see another player, this information becomes crucial.
...the returned xrviewerpose tells you where the viewer is and what direction they're facing at the time at which the frame takes place.
XRWebGLLayerInit.ignoreDepthValues - Web APIs
the depth buffer is typically used to assist in ordering vertices and, by extension, polygons while compositing, to ensure that the scene is correctly composited, with objects the correct distance away and with clipping and other distance-related computations performed as accurately as possible.
... using a depth buffer while compositing allows the xr compositor to help ensure the compositing is done as accurately as possible.
ARIA live regions - Accessibility
<div id="clock" role="timer" aria-live="polite"></div> /* basic javascript to update the clock */ setinterval(function() { var now = new date(); document.getelementbyid('clock').innerhtml = "time: " + now.gethours() + ":" + ("0"+now.getminutes()).substr(-2); }, 60000); the first time the function executes, the entirety of the string that is added will be announced.
... a working example of a simple year control for better understanding: <div id="date-input"> <label>year: <input type="text" id="year" value="1990" onblur="change(event)"/> </label> </div> <div id="date-output" aria-live="polite"> the set year is: <span id="year-output">1990</span> </div> function change(event) { var yearout = document.getelementbyid("year-output"); switch (event.target.id) { case "year": yearout.innerhtml = event.target.value; break; default: return; } }; without aria-atomic="true" the screenreader announces only the changed value of year.
Using the link role - Accessibility
> fake accessible link created using a span </span> <p><a href="https://mozilla.org" target="_blank">actual real link</a></p> css span[role="link"] { color: blue; text-decoration: underline; cursor: pointer; } span[role="link"]:focus { outline: 1px dotted black; } javascript const spanelem = document.queryselector('span'); //handles clicks and keydowns on the link function navigatelink(e) { if (e.type === 'click' || e.key === 'enter') { let ref = e.target != null ?
... e.target : e.srcelement; if (ref) { window.open(ref.getattribute('data-href'), '_blank'); } } } spanelem.addeventlistener('click', navigatelink); spanelem.addeventlistener('keydown', navigatelink); result notes if pressing the link triggers an action but does not change browser focus or navigate to a new page, you might wish to consider using the button role instead of the link role.
ARIA - Accessibility
unfortunately, there isn't a more semantic tag available to developers in html 4, so we need to include aria roles and properties.
...var progressbar = document.getelementbyid("percent-loaded"); // set its aria roles and states, // so that assistive technologies know what kind of widget it is.
Keyboard-navigable JavaScript widgets - Accessibility
the event handler on the container must respond to key and mouse events by updating the value of aria-activedescendant and ensuring that the current item is styled appropriately (for example, with a border or background color).
... don't rely on consistent behavior for key repeat, at this point unfortunately onkeydown may or may not repeat depending on what browser and os you're running on.
Web accessibility for seizures and physical reactions - Accessibility
the point is, seizures most definitely can be and are fatal, and developers and designers are incredibly important to making the web a safer place for those with sensitivities to photosensitive or musicogenic triggers.
...the epilepsy foundation's article, photosensitivity and seizures, provides a list of triggers that may cause seizures in photosensitive people; here's an excerpt from that list: television screens or computer monitors due to the flicker or rolling images.
Operable - Accessibility
completing a hotel or flight booking often has a time limit), the user should be given controls to allow them to adjust, extend or turn off the time limit.
... 2.4.10 section headings (aaa) as well as creating a useful document structure, headings should also accurately describe and break up content areas into logical sections.
-webkit-overflow-scrolling - CSS: Cascading Style Sheets
syntax values auto use "regular" scrolling, where the content immediately ceases to scroll when you remove your finger from the touchscreen.
... </p> </div> css div { width: 100%; overflow: auto; } p { width: 200%; background: #f5f9fa; border: 2px solid #eaf2f4; padding: 10px; } .scroll-touch { -webkit-overflow-scrolling: touch; /* lets it scroll lazy */ } .scroll-auto { -webkit-overflow-scrolling: auto; /* stops scrolling immediately */ } results specifications not part of any standard.
:scope - CSS: Cascading Style Sheets
WebCSS:scope
javascript let paragraph = document.getelementbyid("para"); let output = document.getelementbyid("output"); if (paragraph.matches(":scope")) { output.innertext = "yep, the element is its own scope as expected!"; } html <p id="para"> this is a paragraph.
... javascript var context = document.getelementbyid('context'); var selected = context.queryselectorall(':scope > div'); document.getelementbyid('results').innerhtml = array.prototype.map.call(selected, function (element) { return '#' + element.getattribute('id'); }).join(', '); html <div id="context"> <div id="element-1"> <div id="element-1.1"></div> <div id="element-1.2"></div> </div> <div id="element-2"> <div id="element-2.1"></div> </div> </div> <p> selected elements ids : <span id="results"></sp...
height - CSS: Cascading Style Sheets
WebCSS@viewportheight
if the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as 0.max-height: the percentage is calculated with respect to the height of the generated box's containing block.
... if the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as none.computed valueas each of the properties of the shorthand:min-height: the percentage as specified or the absolute lengthmax-height: the percentage as specified or the absolute length or none formal syntax <viewport-length>{1,2}where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage> examples setting minimum and maximum height @viewport { height: 500px; } specifications specification status comment css device adaptationthe definition of '"height" descriptor' in that specification.
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.
Alternative style sheets - CSS: Cascading Style Sheets
when the user selects a different style, the page will immediately be re-rendered using that style sheet.
...this tells the browser which style sheet title should be selected by default, and makes that default selection apply in browsers that do not support alternate style sheets.
Using multi-column layouts - CSS: Cascading Style Sheets
unfortunately this is impossible to do with css and html without forcing column breaks at fixed positions, or severely restricting the markup allowed in the text, or using heroic scripting.
...pteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum </div> css #columns_12 { columns: 12 8em; } result height balancing the css3 column specification requires that the column heights must be balanced: that is, the browser automatically sets the maximum column height so that the heights of the content in each column are approximately equal.
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
however, prefixes ultimately were used in production code, and changes to the experimental specification caused people to need to update their sites to keep up.
... ultimately the specification was updated to define display: flex as the way to create a flex container.
Block and inline layout in normal flow - CSS: Cascading Style Sheets
this means that if you have an element with a top margin immediately after an element with a bottom margin, rather than the total space being the sum of these two margins, the margin collapses, and so will essentially become as large as the larger of the two margins.
... this concept of the outer and inner display type is important as this tells us that a container using a layout method such as flexbox (display: flex) and grid layout (display: grid) is still participating in block and inline layout, due to the outer display type of those methods being block.
Introduction to formatting contexts - CSS: Cascading Style Sheets
a new bfc is created in the following situations: elements made to float using float absolutely positioned elements (including position: fixed or position: sticky) elements with display: inline-block table cells or elements with display: table-cell, including anonymous table cells created when using the display: table-* properties table captions or elements with display: table-caption block elements where overflow has a value other than visible elements with display: flow-root or disp...
... the problem with using overflow to create a new bfc is that the overflow property is meant for telling the browser how you wish to deal with overflowing content.
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
in addition to the ability to place items accurately onto a created grid, the css grid layout specification contains rules that control what happens when you create a grid and do not place some or all of the child items.
...this can be helpful, if you have a document order that reflects the order in which items sit on the grid you may not need to write css rules to place absolutely everything.
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
this is in contrast to omitting align-items completely, in which case the height of each <div> stretches to fill its grid area.
... setting auto margins, using margin-right or margin-left however, or absolutely positioning items using the top, right, bottom and left offsets would not honor writing modes.
Stacking context example 3 - CSS: Cascading Style Sheets
the second-level menu is absolutely positioned inside the parent element.
... 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.
The stacking context - CSS: Cascading Style Sheets
each stacking context is completely independent of its siblings: only descendant elements are considered when stacking is processed.
...the hierarchy of stacking contexts is organized as follows: root div #1 div #2 div #3 div #4 div #5 div #6 it is important to note that div #4, div #5 and div #6 are children of div #3, so stacking of those elements is completely resolved within div#3.
Basic concepts of CSS Scroll Snap - CSS: Cascading Style Sheets
the mandatory keyword tells the browser whether the content has to snap to a certain point, no matter where the scroll is.
... the scroll-snap-stop property the scroll-snap-stop property tells the browser whether it should snap to each defined snap point — meaning that in our examples above we would stop at the start of each section — or be able to skip past sections.
CSS selectors - CSS: Cascading Style Sheets
this means that the second element follows the first (though not necessarily immediately), and both share the same parent.
... syntax: a ~ b example: p ~ span will match all <span> elements that follow a <p>, immediately or not.
CSS values and units - CSS: Cascading Style Sheets
otherwise, the unit identifier is required, is case insensitive, and must come immediately after the numeric part of the value, with no space in-between.
...the syntax starts with the name of the function immediately followed by a left parenthesis ( followed by the argument(s) to the notation followed by a right parenthesis ).
CSS reference - CSS: Cascading Style Sheets
WebCSSReference
combinators combinators are selectors that establish a relationship between two or more simple selectors, such as "a is a child of b" or "a is adjacent to b." adjacent sibling combinator a + b specifies that the elements selected by both a and b have the same parent and that the element selected by b immediately follows the element selected by a horizontally.
... general sibling combinator a ~ b specifies that the elements selected by both a and b share the same parent and that the element selected by a comes before—but not necessarily immediately before—the element selected by b.
<blend-mode> - CSS: Cascading Style Sheets
any change occurs immediately.
...n>exclusion</option> <option>hue</option> <option>saturation</option> <option>color</option> <option>luminosity</option> </select> css div { width: 300px; height: 300px; background: url(https://media.prod.mdn.mozit.cloud/attachments/2020/07/29/17350/3b4892b7e820122ac6dd7678891d4507/firefox.png) no-repeat center, linear-gradient(to bottom, blue, orange); } javascript const selectelem = document.queryselector('select'); const divelem = document.queryselector('div'); selectelem.addeventlistener('change', () => { divelem.style.backgroundblendmode = selectelem.value; }); result specifications specification status comment compositing and blending level 1the definition of '<blend-mode>' in that specification.
bottom - CSS: Cascading Style Sheets
WebCSSbottom
syntax /* <length> values */ bottom: 3px; bottom: 2.4em; /* <percentage>s of the height of the containing block */ bottom: 10%; /* keyword value */ bottom: auto; /* global values */ bottom: inherit; bottom: initial; bottom: unset; values <length> a negative, null, or positive <length> that represents: for absolutely positioned elements, the distance to the bottom edge of the containing block.
... auto specifies that: for absolutely positioned elements, the position of the element is based on the top property, while height: auto is treated as a height based on the content; or if top is also auto, the element is positioned where it should vertically be positioned if it were a static element.
break-after - CSS: Cascading Style Sheets
the type of this break is that of the immediately-containing fragmentation context.
...ut turpis leo, malesuada quis nisl nec, volutpat egestas tellus.
break-before - CSS: Cascading Style Sheets
the type of this break is that of the immediately-containing fragmentation context.
...ut turpis leo, malesuada quis nisl nec, volutpat egestas tellus.
clamp() - CSS: Cascading Style Sheets
WebCSSclamp
pellentesque convallis ante nec augue porttitor, id tempus ante luctus.</p> <p>integer rutrum sollicitudin tellus, quis cursus nulla scelerisque nec.
...maecenas faucibus sapien eleifend, semper tellus at, pharetra quam.
clip - CSS: Cascading Style Sheets
WebCSSclip
the clip property applies only to absolutely positioned elements — that is, elements with position:absolute or position:fixed.
... formal definition initial valueautoapplies toabsolutely positioned elementsinheritednocomputed valueauto if specified as auto, otherwise a rectangle with four values, each of which is auto if specified as auto or the computed length otherwiseanimation typea rectangle formal syntax <shape> | autowhere <shape> = rect(<top>, <right>, <bottom>, <left>) examples clipping an image css .dotted-border { border: dotted; position: relative; width: ...
<dimension> - CSS: Cascading Style Sheets
WebCSSdimension
syntax the syntax of <dimension> is a <number> immediately followed by a unit which is an identifier.
... examples valid dimensions 12px 12 pixels 1rem 1 rem 1.2pt 1.2 points 2200ms 2200 milliseconds 5s 5 seconds 200hz 200 hertz 200hz 200 hertz (values are case insensitive) invalid dimensions 12 px the unit must come immediately after the number.
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
the new syntax accurately describes what is happening with this value.
...if you consider the outer and inner values when you change the value of display, you will understand immediately what impact the value will have on the box itself, and how it displays and behaves in the layout, and the direct children.
brightness() - CSS: Cascading Style Sheets
a value of 0% will create an image that is completely black, while a value of 100% leaves the input unchanged.
... examples setting brightness using numbers and percentages brightness(0%) /* completely black */ brightness(0.4) /* 40% brightness */ brightness(1) /* no effect */ brightness(200%) /* double brightness */ specifications specification status filter effects module level 1the definition of 'brightness()' in that specification.
contrast() - CSS: Cascading Style Sheets
a value of 0% will create an image that is completely gray, while a value of 100% leaves the input unchanged.
... examples setting contrast using numbers and percentages contrast(0) /* completely gray */ contrast(65%) /* 65% contrast */ contrast(1) /* no effect */ contrast(200%) /* double contrast */ specifications specification status filter effects module level 1the definition of 'contrast()' in that specification.
grayscale() - CSS: Cascading Style Sheets
a value of 100% is completely grayscale, while a value of 0% leaves the input unchanged.
... examples grayscale(0) /* no effect */ grayscale(.7) /* 70% grayscale */ grayscale(100%) /* completely grayscale */ specifications specification status filter effects module level 1the definition of 'grayscale()' in that specification.
invert() - CSS: Cascading Style Sheets
a value of 100% is completely inverted, while a value of 0% leaves the input unchanged.
... examples invert(0) /* no effect */ invert(.6) /* 60% inversion */ invert(100%) /* completely inverted */ specifications specification status filter effects module level 1the definition of 'invert()' in that specification.
opacity() - CSS: Cascading Style Sheets
a value of 0% is completely transparent, while a value of 100% leaves the input unchanged.
... examples opacity(0%) /* completely transparent */ opacity(50%) /* 50% transparent */ opacity(1) /* no effect */ specifications specification status filter effects module level 1the definition of 'opacity()' in that specification.
saturate() - CSS: Cascading Style Sheets
a value of 0% is completely unsaturated, while a value of 100% leaves the input unchanged.
... examples saturate(0) /* completely unsaturated */ saturate(.4) /* 40% saturated */ saturate(100%) /* no effect */ saturate(200%) /* double saturation */ specifications specification status filter effects module level 1the definition of 'saturate()' in that specification.
sepia() - CSS: Cascading Style Sheets
a value of 100% is completely sepia, while a value of 0% leaves the input unchanged.
... examples sepia(0) /* no effect */ sepia(.65) /* 65% sepia */ sepia(100%) /* completely sepia */ specifications specification status filter effects module level 1the definition of 'sepia()' in that specification.
font-optical-sizing - CSS: Cascading Style Sheets
when optical sizing is used, small text sizes are often rendered with thicker strokes and larger serifs, whereas larger text is often rendered more delicately with more contrast between thicker and thinner strokes.
... you should see a difference in supporting browsers.</p> @font-face { src: url('amstelvaralpha-vf.ttf'); font-family:'amstelvar'; font-style: normal; } p { font-size: 36px; font-family: amstelvar; } .no-optical-sizing { font-optical-sizing: none; } note: the font referenced above — which includes optical sizing and is freely-licensed — is good for testing.
font-style - CSS: Cascading Style Sheets
html <header> <input type="range" id="slant" name="slant" min="-90" max="90" /> <label for="slant">slant</label> </header> <div class="container"> <p class="sample">...it would not be wonderful to meet a megalosaurus, forty feet long or so, waddling like an elephantine lizard up holborn hill.</p> </div> css /* amstelvaralpha-vf is created by david berlow (https://github.com/typenetwork/amstelvar) and is used here under the terms of its license: https://github.com/typenetwork/amstelvar/blob/master/ofl.txt */ @font-face { src: url('https://mdn.mozillademos.org/files/16044/amstelvaralpha-vf.ttf'); font-family:'amstelvaralpha'; font-style: normal; } label { font: 1rem monospace; } .container { max-he...
...ight: 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.queryselector('label[for="slant"]'); let slantinput = document.queryselector('#slant'); let sampletext = document.queryselector('.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...
image-orientation - CSS: Cascading Style Sheets
from-image the exif information contained in the image will be used to rotate the image appropriately.
...ata css #image { image-orientation: from-image; /* can be changed in the live sample */ } html <img id="image" src="https://udn.realityripple.com/samples/db/4f9fbd7dfb.svg" alt="orientation taken from the image"> <select id="imageorientation"> <option value="from-image">from-image</option> <option value="none">none</option> </select> javascript var imageorientation = document.getelementbyid("imageorientation"); imageorientation.addeventlistener("change", function (evt) { document.getelementbyid("image").style.imageorientation = evt.target.value; }); result specifications specification status comment css images module level 3the definition of 'image-orientation' in that specification.
left - CSS: Cascading Style Sheets
WebCSSleft
syntax /* <length> values */ left: 3px; left: 2.4em; /* <percentage>s of the width of the containing block */ left: 10%; /* keyword value */ left: auto; /* global values */ left: inherit; left: initial; left: unset; values <length> a negative, null, or positive <length> that represents: for absolutely positioned elements, the distance to the left edge of the containing block.
... auto specifies that: for absolutely positioned elements, the position of the element is based on the right property, while width: auto is treated as a width based on the content; or if right is also auto, the element is positioned where it should horizontally be positioned if it were a static element.
<length> - CSS: Cascading Style Sheets
WebCSSlength
; 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.queryselector('.inner'); const inputelem = document.queryselector('input'); const resultsdiv = document.queryselector('.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>`; resultsdiv.appendchild(result); ...
... inputelem.value = ''; inputelem.focus(); }) result specifications specification status comment css values and units module level 4the definition of '<length>' in that specification.
order - CSS: Cascading Style Sheets
WebCSSorder
flexbox & the keyboard navigation disconnect — tink source order matters | adrian roselli mdn understanding wcag, guideline 1.3 explanations understanding success criterion 1.3.2 | w3c understanding wcag 2.0 formal definition initial value0applies toflex items and absolutely-positioned flex container childreninheritednocomputed valueas specifiedanimation typean integer formal syntax <integer> examples ordering items in a flex container this example uses css to create a classic two-sidebar layout surrounding a content block.
... candidate recommendation initial definition initial value0applies toflex items and absolutely-positioned flex container childreninheritednocomputed valueas specifiedanimation typean integer ...
place-content - CSS: Cascading Style Sheets
r</option> <option value="start">start</option> <option value="end">end</option> <option value="flex-start">flex-start</option> <option value="flex-end">flex-end</option> <option value="left">left</option> <option value="right">right</option> <option value="safe">safe</option> <option value="unsafe">unsafe</option> </select><code>;</code> var update = function () { document.getelementbyid("container").style.placecontent = document.getelementbyid("aligncontentalignment").value + " " + document.getelementbyid("justifycontentalignment").value; } var aligncontentalignment = document.getelementbyid("aligncontentalignment"); aligncontentalignment.addeventlistener("change", update); var justifycontentalignment = document.getelementbyid("justifycontentalignment"); justifyconte...
...ntalignment.addeventlistener("change", update); var writingm = document.getelementbyid("writingmode"); writingm.addeventlistener("change", function (evt) { document.getelementbyid("container").style.writingmode = evt.target.value; }); var direction = document.getelementbyid("direction"); direction.addeventlistener("change", function (evt) { document.getelementbyid("container").style.direction = evt.target.value; }); css #container { display: flex; height:240px; width: 240px; flex-wrap: wrap; background-color: #8c8c8c; writing-mode: horizontal-tb; /* can be changed in the live sample */ direction: ltr; /* can be changed in the live sample */ place-content: flex-end center; /* can be changed in the live sample */ } div > div { border: 2px solid #8c8c8c; width: 50...
text-underline-position - CSS: Cascading Style Sheets
aliquam accumsan tellus ac erat posuere.</p> <p class="vertical">lorem ipsum dolor sit amet, consectetur adipiscing elit.
...aliquam accumsan tellus ac erat posuere.</p> our css looks like this: p { font-size: 1.5rem; text-transform: capitalize; text-decoration: underline; text-decoration-thickness: 2px; } .horizontal { text-underline-position: under; } .vertical { writing-mode: vertical-rl; text-underline-position: left; } in this example we set both the paragraphs to have a thick underline.
top - CSS: Cascading Style Sheets
WebCSStop
syntax /* <length> values */ top: 3px; top: 2.4em; /* <percentage>s of the height of the containing block */ top: 10%; /* keyword value */ top: auto; /* global values */ top: inherit; top: initial; top: unset; values <length> a negative, null, or positive <length> that represents: for absolutely positioned elements, the distance to the top edge of the containing block.
... auto specifies that: for absolutely positioned elements, the position of the element is based on the bottom property, while height: auto is treated as a height based on the content; or if bottom is also auto, the element is positioned where it should vertically be positioned if it were a static element.
<transform-function> - CSS: Cascading Style Sheets
the translation vector (tx, ty) must be expressed separately, as two additional parameters.
...ba(210,0,0,.7); transform: 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.queryselector('select'); const example = document.queryselector('#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) }...
transition-delay - CSS: Cascading Style Sheets
the delay may be zero, positive, or negative: a value of 0s (or 0ms) will begin the transition effect immediately.
... a negative value will begin the transition effect immediately, and partway through the effect.
WAI ARIA Live Regions/API Support - Developer guides
ut to go away) object shown or inserted children_changed::add (fired on the parent, with event data pointing to the child index of the inserted accessible object) event_object_show* (fired on the actual new accessible object) object replaced with different object (this happens especially if an object's interfaces or role changes) children_changed::remove followed immediately by children_change::add event_object_hide followed immediately by event_object_show text removed text_changed::delete ia2_event_text_removed (use iaccessibletext::get_oldtext to retrieve the offsets and removed text) text inserted text_changed::insert ia2_event_text_inserted (use iaccessibletext::get_newtext to retrieve the offsets and inserted text) tex...
...t replaced text_changed::delete followed immediately by text_changed::insert ia2_event_text_removed followed immediately by ia2_event_text_inserted * we do not use msaa's create/destroy at the request of screen reader vendors, who avoid those events because they cause crashes on some important system -- show/hide are the equivalent of those events.
Video player styling basics - Developer guides
as mentioned in the previous article, there is a fallback provided for browsers that do not support the <progress> element; this also needs to be styled appropriately: .controls progress[data-state="fake"] { background:#e6e6e6; height:65%; } .controls progress span { width:0%; height:100%; display:inline-block; background-color:#2a84cd; } a .data-state class is also used here when a <progress> element is being "faked"; when it's in this state the background colour needs to be set.
... there are some browser-specific properties that need to be set to ensure that firefox and chrome use the required colour for the progress bar: .controls progress::-moz-progress-bar { background-color:#0095dd; } .controls progress::-webkit-progress-value { background-color:#0095dd; } although the same properties are set to the same value, these rules need to be defined separately, otherwise chrome ignores it.
Writing Web Audio API code that works in every browser - Developer guides
unfortunately, chrome, safari and opera still use the webkitaudiocontext prefixed name.
...if you're porting moderately "old" code (say, a year old) it's possible that it uses some methods that audiocontext-monkeypatch doesn't alias, because it helps you to write code in the new style.
Audio and Video Delivery - Developer guides
to grab the stream from your webcam, first set up a <video> element: <video id="webcam" width="480" height="360"></video> next, if supported connect the webcam source to the video element: if (navigator.mediadevices) { navigator.mediadevices.getusermedia({ video: true, audio: false }) .then(function onsuccess(stream) { var video = document.getelementbyid('webcam'); video.autoplay = true; video.srcobject = stream; }) .catch(function onerror() { alert('there has been a problem retreiving the streams - are you running on file:/// or did you disallow access?'); }); } else { alert('getusermedia is not supported in this browser.'); } to find out more, read our mediadevices.getusermedia page.
... a quick example — first set up your audio and custom controls in html: <audio id="my-audio" src="http://jplayer.org/audio/mp3/miaow-01-tempered-song.mp3"></audio> <button id="my-control">play</button> add a bit of javascript to detect events to play and pause the audio: window.onload = function() { var myaudio = document.getelementbyid('my-audio'); var mycontrol = document.getelementbyid('my-control'); function switchstate() { if (myaudio.paused == true) { myaudio.play(); mycontrol.innerhtml = "pause"; } else { myaudio.pause(); mycontrol.innerhtml = "play"; } } function checkkey(e) { if (e.keycode == 32 ) { //spacebar switchstate(); } } mycontrol.addevent...
Block formatting context - Developer guides
absolutely positioned elements (elements where position is absolute or fixed).
... the problem with using overflow to create a new bfc is that the overflow property is meant for telling the browser how you want to deal with overflowing content.
Localizations and character encodings - Developer guides
unfortunately, using utf-8 and declaring that utf-8 was used was not always the prevalent way of offering web content.
... unfortunately, this means that the web-exposed functionality of firefox differs by locale and it is hard to read legacy content across locales with different fallback encodings.
A hybrid approach - Developer guides
if your mobile and desktop use cases are similar enough, this is definitely the preferred option for layout changes.
...instead of maintaining two completely different sites, we simply redirect users to pages for the content they care about.
HTML attribute: required - HTML: Hypertext Markup Language
the required attribute is supported by text, search, url, tel, email, password, date, month, week, time, datetime-local, number, checkbox, radio, file, <input> types along with the <select> and <textarea> form control elements.
... note: setting aria-required="true" tells a screen reader that an element (any element) is required, but has no bearing on the optionality of the element.
Date and time formats used in HTML - HTML: Hypertext Markup Language
although the calendar year is normally 365 days long, it actually takes the planet earth approximately 365.2422 days to complete a single orbit around the sun.
... the time zone string is appended immediately following the time in the date and time string.
<basefont> - HTML: Hypertext Markup Language
WebHTMLElementbasefont
in html5, this element has been removed completely.
... dom interface this element implements the htmlbasefontelement interface.
<dialog>: The Dialog element - HTML: Hypertext Markup Language
WebHTMLElementdialog
option>red panda</option> <option>spider monkey</option> </select> </label></p> <menu> <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.queryselector('output'); var selectel = document.queryselector('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"); } }); // "favorite animal" input sets the value of the submit button selectel.addeventlistener('change', function onselect(e) { confirmbtn.value = selectel.value; }); // "confirm" button of form triggers "close" on dialog because of [method="dialog"] favdialog.addeventlistener('close', function onclose() { outputbox.value = favdialog.returnvalue + " button clicked - " + (new date()).tostring(); }); result specifications specification status comment html living standardthe definition of '<dialog>' in that specification.
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
intrinsicsize this attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute.
... loading indicates how the browser should load the image: eager: loads the image immediately, regardless of whether or not the image is currently within the visible viewport (this is the default value).
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
...to detect whether the browser supports <input type="week">, we create a new <input> element, try setting its type to week, then immediately check what its type is set to.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
WebHTMLElementlink
integrity contains inline metadata — a base64-encoded cryptographic hash of the resource (file) you’re telling the browser to fetch.
...eet'); 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, and immediately before the styles start being applied to the content.
<object> - HTML: Hypertext Markup Language
WebHTMLElementobject
implicit aria role no corresponding role permitted aria roles application, document, image dom interface htmlobjectelement attributes this element includes the global attributes.
...in html5, repeat the <object> element completely each that that the resource is reused.
<ol>: The Ordered List element - HTML: Hypertext Markup Language
WebHTMLElementol
implicit aria role list permitted aria roles directory, group, listbox, menu, menubar, none, presentation, radiogroup, tablist, toolbar, tree dom interface htmlolistelement attributes this element also accepts the global attributes.
... html5the definition of 'htmlolistelement' in that specification.
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
WebHTMLElementrb
tag omission the end tag can be omitted if the element is immediately followed by an <rt>, <rtc>, or <rp> element or another <rb> element, or if there is no more content in the parent element.
... note that we could also write this example with the two base text parts annotated completely separately.
<rp>: The Ruby Fallback Parenthesis element - HTML: Hypertext Markup Language
WebHTMLElementrp
permitted content text tag omission the end tag can be omitted if the element is immediately followed by an <rt> or another <rp> element, or if there is no more content in the parent element.
...<rp> must be positioned immediately before or after an <rt> element.
<tbody>: The Table Body element - HTML: Hypertext Markup Language
WebHTMLElementtbody
when a table is presented in a screen context (such as a window) which is not large enough to display the entire table, the user agent may let the user scroll the contents of the <thead>, <tbody>, <tfoot>, and <caption> blocks separately from one another for the same parent table.
...this lets you divide the rows in large tables into sections, each of which may be separately formatted if so desired.
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
the html content template (<template>) element is a mechanism for holding html that is not to be rendered immediately when a page is loaded but may be instantiated subsequently during runtime using javascript.
... consider the following html and javascript: html <div id="container"></div> <template id="template"> <div>click me</div> </template> javascript const container = document.getelementbyid("container"); const template = document.getelementbyid("template"); function clickhandler(event) { alert("clicked a div"); } const firstclone = template.content.clonenode(true); firstclone.addeventlistener("click", clickhandler); container.appendchild(firstclone); const secondclone = template.content.firstelementchild.clonenode(true); secondclone.addeventlistener("click", clickhandl...
inputmode - HTML: Hypertext Markup Language
tel a telephone keypad input, including the digits 0–9, the asterisk (*), and the pound (#) key.
... inputs that require a telephone number should typically use <input type="tel">instead.
Global attributes - HTML: Hypertext Markup Language
classes allows css and javascript to select and access specific elements via the class selectors or functions like the method document.getelementsbyclassname().
...this attribute must not be used to hide content that could legitimately be shown.
Choosing between www and non-www URLs - HTTP
this has no impact on the human reader of the page, but tells search engine crawlers where the page actually lives.
... when adding such a tag, you serve the same content for both domains, telling search engines which url is canonical.
Compression in HTTP - HTTP
in practice, web developers don't need to implement compression mechanisms, both browsers and servers have it implemented already, but they have to be sure that the server is configured adequately.
...the browser sends an accept-encoding header with the algorithm it supports and its order of precedence, the server picks one, uses it to compress the body of the response and uses the content-encoding header to tell the browser the algorithm it has chosen.
Configuring servers for Ogg media - HTTP
consider using the preload attribute the html <audio> and <video> elements provide the preload attribute, which tells the browser to attempt to download the entire media when the page loads.
...setting payload to auto tells the browser to automatically begin downloading the media as soon as the page is loaded, under the assumption that the user will play it.
Content negotiation - HTTP
the vary header was added in the version 1.1 of http and is necessary in order to allow caches to work appropriately.
... unfortunately, the http standard does not specify the format of the page allowing to choose between the available resource, which prevents to easily automatize the process.
Access-Control-Allow-Origin - HTTP
header type response header forbidden header name no syntax access-control-allow-origin: * access-control-allow-origin: <origin> access-control-allow-origin: null directives * for requests without credentials, the literal value "*" can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource.
...the "null" value for the acao header should therefore be avoided." examples a response that tells the browser to allow code from any origin to access a resource will include the following: access-control-allow-origin: * a response that tells the browser to allow requesting code from the origin https://developer.mozilla.org to access a resource will include the following: access-control-allow-origin: https://developer.mozilla.org limiting the possible access-control-allow-origin values t...
CSP: child-src - HTTP
use this sparingly and definitely not for scripts.
... 'nonce-<base64-value>' a whitelist for specific inline scripts using a cryptographic nonce (number used once).
CSP: font-src - HTTP
use this sparingly and definitely not for scripts.
... 'nonce-<base64-value>' a whitelist for specific inline scripts using a cryptographic nonce (number used once).
CSP: frame-src - HTTP
use this sparingly and definitely not for scripts.
... 'nonce-<base64-value>' a whitelist for specific inline scripts using a cryptographic nonce (number used once).
CSP: manifest-src - HTTP
use this sparingly and definitely not for scripts.
... 'nonce-<base64-value>' a whitelist for specific inline scripts using a cryptographic nonce (number used once).
CSP: media-src - HTTP
use this sparingly and definitely not for scripts.
... 'nonce-<base64-value>' a whitelist for specific inline scripts using a cryptographic nonce (number used once).
CSP: object-src - HTTP
use this sparingly and definitely not for scripts.
... 'nonce-<base64-value>' a whitelist for specific inline scripts using a cryptographic nonce (number used once).
CSP: style-src - HTTP
use this sparingly and definitely not for scripts.
...however, if you absolutely have to use it, there are a few mechanisms that will allow them.
CSP: worker-src - HTTP
use this sparingly and definitely not for scripts.
... 'nonce-<base64-value>' a whitelist for specific inline scripts using a cryptographic nonce (number used once).
Content-Type - HTTP
in responses, a content-type header tells the client what the content type of the returned content actually is.
... in requests, (such as post or put), the client tells the server what type of data is actually sent.
ETag - HTTP
WebHTTPHeadersETag
they might also be set to persist indefinitely by a tracking server.
... the client will send the value of its etag along in an if-none-match header field: if-none-match: "33a64df551425fcc55e4d42a148795d9f25f89d4" the server compares the client's etag (sent with if-none-match) with the etag for its current version of the resource, and if both values match (that is, the resource has not changed), the server sends back a 304 not modified status, without a body, which tells the client that the cached version of the response is still good to use (fresh).
Large-Allocation - HTTP
the non-standard large-allocation response header tells the browser that the page being loaded is going to want to perform a large allocation.
...the large-allocation tells the browser that the web content in the to-be-loaded page is going to want to perform a large contiguous memory allocation and the browser can react to this header by starting a dedicated process for the to-be-loaded document, for example.
User-Agent - HTTP
examples mozilla/5.0 (windows nt 6.1; win64; x64; rv:47.0) gecko/20100101 firefox/47.0 mozilla/5.0 (macintosh; intel mac os x x.y; rv:42.0) gecko/20100101 firefox/42.0 chrome ua string the chrome (or chromium/blink-based engines) user agent string is similar to firefox’s.
... examples mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, like gecko) chrome/51.0.2704.106 safari/537.36 opr/38.0.2220.41 older, presto-based opera releases used: opera/9.80 (macintosh; intel mac os x; u; en) presto/2.2.15 version/10.00 opera/9.60 (windows nt 6.0; u; en) presto/2.1.1 safari ua string in this example, the user agent string is mobile safari’s version.
OPTIONS - HTTP
WebHTTPMethodsOPTIONS
in this example, we will request permission for these parameters: the access-control-request-method header sent in the preflight request tells the server that when the actual request is sent, it will have a post request method.
... the access-control-request-headers header tells the server that when the actual request is sent, it will have the x-pingother and content-type headers.
Redirections in HTTP - HTTP
when browsers receive a redirect, they immediately load the new url provided in the location header.
... it is important to avoid redirection loops, as they completely break the user experience.
A typical HTTP session - HTTP
WebHTTPSession
http://developer.mozilla.org/, and telling the server that the user-agent would prefer the page in french, if possible: get / http/1.1 host: developer.mozilla.org accept-language: fr observe that final empty line, this separates the data block from the header block.
... structure of a server response after the connected agent has sent its request, the web server processes it, and ultimately returns a response.
HTTP response status codes - HTTP
WebHTTPStatus
205 reset content tells the user-agent to reset the document which sent this request.
...it tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
A re-introduction to JavaScript (JS tutorial) - JavaScript
more accurately, they are sequences of utf-16 code units; each code unit is represented by a 16-bit number.
...you can use named iifes (immediately invoked function expressions) as shown below: var charsinbody = (function counter(elm) { if (elm.nodetype == 3) { // text_node return elm.nodevalue.length; } var count = 0; for (var i = 0, child; child = elm.childnodes[i]; i++) { count += counter(child); } return count; })(document.body); the name provided to a function expression as above is only available to the function...
Concurrency model and the event loop - JavaScript
"run-to-completion" each message is processed completely before any other message is processed.
... here is an example that demonstrates this concept (settimeout does not run immediately after its timer expires): const s = new date().getseconds(); settimeout(function() { // prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
Control flow and error handling - JavaScript
"standalone" blocks in javascript can produce completely different results from what they would produce in c or java.
...if any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block.
Indexed collections - JavaScript
the simplest way to do this is as follows: let colors = ['red', 'green', 'blue'] for (let i = 0; i < colors.length; i++) { console.log(colors[i]) } if you know that none of the elements in your array evaluate to false in a boolean context—if your array consists only of dom nodes, for example—you can use a more efficient idiom: let divs = document.getelementsbytagname('div') for (let i = 0, div; div = divs[i]; i++) { /* process div in some way */ } this avoids the overhead of checking the length of the array, and ensures that the div variable is reassigned to the current item each time around the loop for added convenience.
... working with array-like objects some javascript objects, such as the nodelist returned by document.getelementsbytagname() or the arguments object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods.
JavaScript modules - JavaScript
these are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly.
... fortunately there are a number of ways to get around this.
Numbers and dates - JavaScript
if the digits after 0x are outside the range (0123456789abcdef), the following syntaxerror is thrown: "identifier starts immediately after numeric literal".
... with the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately.
Assertions - JavaScript
if the multiline flag is set to true, also matches immediately after a line break character.
...if the multiline flag is set to true, also matches immediately before a line break character.
Regular expressions - JavaScript
these flags can be used separately or together in any order, and are included as part of the regular expression.
...</p> <form action="#"> <input id="phone"> <button onclick="testinfo(document.getelementbyid('phone'));">check</button> </form> javascript var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/; function testinfo(phoneinput) { var ok = re.exec(phoneinput.value); if (!ok) { console.error(phoneinput.value + ' isn\'t a phone number with area code!'); } else { console.log('thanks, your phone number is ' + ok[0]);} } result tools regexr an online tool to learn,...
Inheritance and the prototype chain - JavaScript
making your javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the spec...
...making your javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the spec...
TypeError: Reduce of empty array with no initial value - JavaScript
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.
... var names = document.getelementsbyclassname("names"); var name_list1 = ""; if (names1.length >= 1) name_list1 = array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); // name_list1 == "" when names is empty.
InternalError: too much recursion - JavaScript
as there is no exit condition, the function will call itself infinitely.
...this causes the function to call itself, again and again, making it infinitely recursive.
JavaScript error reference - JavaScript
these errors can be a helpful debugging aid, but the reported problem isn't always immediately clear.
...use //# insteadsyntaxerror: a declaration in the head of a for-of loop can't have an initializersyntaxerror: applying the "delete" operator to an unqualified name is deprecatedsyntaxerror: for-in loop head declarations may not have initializerssyntaxerror: function statement requires a namesyntaxerror: identifier starts immediately after numeric literalsyntaxerror: illegal charactersyntaxerror: invalid regular expression flag "x"syntaxerror: missing ) after argument listsyntaxerror: missing ) after conditionsyntaxerror: missing : after property idsyntaxerror: missing ; before statementsyntaxerror: missing = in const declarationsyntaxerror: missing ] after element listsyntaxerror: missing formal parametersyntaxerror: missin...
Functions - JavaScript
when functions are used only once, a common pattern is an iife (immediately invoked function expression).
...ly: function multiply(x, y) { return x * y; } // there is no semicolon here a function expression of an anonymous function assigned to the variable multiply: var multiply = function(x, y) { return x * y; }; a function expression of a function named func_name assigned to the variable multiply: var multiply = function func_name(x, y) { return x * y; }; differences all do approximately the same thing, with a few subtle differences: there is a distinction between the function name and the variable the function is assigned to.
Array.prototype.every() - JavaScript
if such an element is found, the every method immediately returns false.
... the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
Array.prototype.some() - JavaScript
if such an element is found, some() immediately returns true.
...the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
Array.prototype.sort() - JavaScript
firstel the first element for comparison.
...the value of each code unit is taken separately into account for the comparison.
Error.prototype.toSource() - JavaScript
this string can be evaluated to create an (approximately) equal object.
... note: be aware that the properties used by the tosource method in the creation of this string are mutable and may not accurately reflect the function used to create an error instance or the filename or line number where the actual error occurred.
Intl.DateTimeFormat() constructor - JavaScript
possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
...possible values include: "arab", "arabext", " bali", "beng", "deva", "fullwide", " gujr", "guru", "hanidec", "khmr", " knda", "laoo", "latn", "limb", "mlym", " mong", "mymr", "orya", "tamldec", " telu", "thai", "tibt".
Intl.NumberFormat() constructor - JavaScript
gonm", "gujr", "guru", "hanidec", "hmng", "hmnp", "java", "kali", "khmr", "knda", "lana", "lanatham", "laoo", "latn", "lepc", "limb", "mathbold", "mathdbl", "mathmono", "mathsanb", "mathsans", "mlym", "modi", "mong", "mroo", "mtei", "mymr", "mymrshan", "mymrtlng", "newa", "nkoo", "olck", "orya", "osma", "rohg", "saur", "segment", "shrd", "sind", "sinh", "sora", "sund", "takr", "talu", "tamldec", "telu", "thai", "tibt", "tirh", "vaii", "wara", "wcho".
...possible values include: "arab", "arabext", " bali", "beng", "deva", "fullwide", " gujr", "guru", "hanidec", "khmr", " knda", "laoo", "latn", "limb", "mlym", " mong", "mymr", "orya", "tamldec", " telu", "thai", "tibt".
JSON.stringify() - JavaScript
all symbol-keyed properties will be completely ignored, even when using the replacer function.
... issue with plain json.stringify for use as javascript historically, json was not a completely strict subset of javascript.
Object.create() - JavaScript
custom and null objects a new object created from a completely custom object (especially one created from the null object, which is basically a custom object with no members) can behave in unexpected ways.
... var obj = object.create({ a: 1, b: 2 }); > console.log(object.entries(obj)); // shows "[]" some non-solutions a good solution for the missing object-methods is not immediately apparent.
Object.freeze() - JavaScript
> object.freeze(1) typeerror: 1 is not an object // es5 code > object.freeze(1) 1 // es2015 code an arraybufferview with elements will cause a typeerror, as they are views over memory and will definitely cause other possible issues: > object.freeze(new uint8array(0)) // no elements uint8array [] > object.freeze(new uint8array(1)) // has elements typeerror: cannot freeze array buffer views with elements > object.freeze(new dataview(new arraybuffer(32))) // no elements dataview {} > object.freeze(new float64array(new arraybuffer(64), 63, 0)) // no elements float64array [] > object.freeze(new ...
...float64array(new arraybuffer(64), 32, 2)) // has elements typeerror: cannot freeze array buffer views with elements note that; as the standard three properties (buf.bytelength, buf.byteoffset and buf.buffer) are read-only (as are those of an arraybuffer or sharedarraybuffer), there is no reason for attempting to freeze these properties.
Set.prototype.forEach() - JavaScript
the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
... examples logging the contents of a set object the following code logs a line for each element in a set object: function logsetelements(value1, value2, set) { console.log('s[' + value1 + '] = ' + value2); } new set(['foo', 'bar', undefined]).foreach(logsetelements); // logs: // "s[foo] = foo" // "s[bar] = bar" // "s[undefined] = undefined" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.foreach' in that specification.
SharedArrayBuffer.prototype.slice() - JavaScript
if end is omitted, slice extracts through the end of the sequence (sab.bytelength).
... examples using slice var sab = new sharedarraybuffer(1024); sab.slice(); // sharedarraybuffer { bytelength: 1024 } sab.slice(2); // sharedarraybuffer { bytelength: 1022 } sab.slice(-2); // sharedarraybuffer { bytelength: 2 } sab.slice(0, 1); // sharedarraybuffer { bytelength: 1 } specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.slice' in that specification.
SharedArrayBuffer - JavaScript
instance properties sharedarraybuffer.prototype.bytelength the size, in bytes, of the array.
... examples creating a new sharedarraybuffer var sab = new sharedarraybuffer(1024); slicing the sharedarraybuffer sab.slice(); // sharedarraybuffer { bytelength: 1024 } sab.slice(2); // sharedarraybuffer { bytelength: 1022 } sab.slice(-2); // sharedarraybuffer { bytelength: 2 } sab.slice(0, 1); // sharedarraybuffer { bytelength: 1 } using it in a webgl buffer const canvas = document.queryselector('canvas'); const gl = canvas.getcontext('webgl'); const buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buf...
TypedArray.prototype.every() - JavaScript
if such an element is found, the every method immediately returns false.
... the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
TypedArray.prototype.some() - JavaScript
if such an element is found, some immediately returns true.
... the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
WebAssembly.Module() constructor - JavaScript
a webassembly.module() constructor creates a new module object containing stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.
... syntax important: since compilation for large modules can be expensive, developers should only use the module() constructor when synchronous compilation is absolutely required; the asynchronous webassembly.compilestreaming() method should be used at all other times.
Function expression - JavaScript
a function expression can be used as an iife (immediately invoked function expression) which runs as soon as it is defined.
...the function returns the square of its argument: var x = function(y) { return y * y; }; using a function as a callback more commonly it is used as a callback: button.addeventlistener('click', function(event) { console.log('button is clicked!') }) using an immediately executed function expression an anonymous function is created and called: (function() { console.log('code runs!') })(); specifications specification ecmascript (ecma-262)the definition of 'function definitions' in that specification.
yield - JavaScript
the next time next() is called, execution resumes with the statement immediately after the yield.
... unfortunately, next() is asymmetric, but that can’t be helped: it always sends a value to the currently suspended yield, but returns the operand of the following yield.
Transitioning to strict mode - JavaScript
the only legitimate use case would be to reuse a function as in: // example taken from vanillajs: http://vanilla-js.com/ var s = document.getelementbyid('thing').style; s.opacity = 1; (function() { if ((s.opacity-=.1) < 0) s.display = 'none'; else settimeout(arguments.callee, 40); })(); which can be rewritten as: 'use strict'; var s = document.getelementbyid('thing').style; s.opacity = 1; (function fadeout() { // name the function if((s.opacity-=.1) < 0) s.display = 'none'; else settimeout(fadeout, 40); // use t...
...fortunately, this careful review can be done gradually down the function granularity.
OpenSearch description format
note: for icons loaded remotely (that is, from https:// uris as opposed to data: uris), firefox will reject icons larger than 10 kilobytes.
... remotely fetched favicons must not be larger than 10kb (see bug 361923).
Animation performance and frame rate - Web Performance
the predominance of green is telling us that we're spending a lot of time painting.
...in the screenshot above we've highlighted a paint operation, and the box on the right tells us it took 13.11ms.
Populating the page: how browsers work - Web Performance
tcp's three way handshaking technique is often referred to as "syn-syn-ack"—or more accurately syn, syn-ack, ack—because there are three messages transmitted by tcp to negotiate and start a tcp session between two computers.
... in our example above, the request is definitely less than 14kb, but the linked resources aren't requested until the browser encounters the links during parsing, described below.
Progressive web app structure - Progressive web apps (PWAs)
that way, the next time someone visits the app from the device, the ui loads from the cache immediately and any new content is requested from the server (if it isn’t available in the cache already).
...var entry = template.replace(/pos/g,(i+1)) .replace(/slug/g,games[i].slug) .replace(/name/g,games[i].name) .replace(/author/g,games[i].author) .replace(/twitter/g,games[i].twitter) .replace(/website/g,games[i].website) .replace(/github/g,games[i].github); entry = entry.replace('<a href=\'http:///\'></a>','-'); content += entry; }; document.getelementbyid('content').innerhtml = content; next, it registers a service worker: if('serviceworker' in navigator) { navigator.serviceworker.register('/pwa-examples/js13kpwa/sw.js'); }; the next code block requests permission for notifications when a button is clicked: var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.reques...
Progressive loading - Progressive web apps (PWAs)
this is all about deferring loading of as many resources as possible (html, css, javascript), and only loading those immediately that are really needed for the very first experience.
...we can also split css files and add media types to them: <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="print.css" media="print"> this will tell the browser to load them only when the condition is met.
Media - Progressive web apps (PWAs)
for double-sided printing, you can specify the margins separately for @page:left and @page:right.
...keep in mind that you can't completely control the printed format.
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
you can make changes to the svg in real time and see them immediately affect the rendering of the html.
... for example, you can resize the circle in the clip path established above: function toggleradius() { var circle = document.getelementbyid("circle"); circle.r.baseval.value = 0.40 - circle.r.baseval.value; } example: filtering this demonstrates applying a filter to html content using svg.
SVG 1.1 Support in Firefox - SVG: Scalable Vector Graphics
doesn't completely follow <svg:use> cascading rules (bug 265894).
... various presentation attributes don't work (alignment-baseline, baseline-shift, dominant-baseline, kerning, letter-spacing, word-spacing, writing-mode, glyph-orientation-horizontal, glyph-orientation-vertical) recently implemented presentation attributes: direction, unicode-bidi, font-variant, text-decoration svgtextelement recently imlemented bindings: selectsubstring recently implemented attributes: textlength, lengthadjust tspan implemented.
Clipping and masking - SVG: Scalable Vector Graphics
color, opacity and such have no effect as long as they don't let parts vanish completely.
...for the fill and stroke there are two separate attributes, fill-opacity and stroke-opacity, that control each of those property opacities separately.
Fills and Strokes - SVG: Scalable Vector Graphics
<rect x="10" y="10" width="100" height="100" stroke="blue" fill="purple" fill-opacity="0.5" stroke-opacity="0.8"/> in addition, you can specify the opacity of either the fill or stroke separately in svg.
...but for compatibility with other viewers, it's often best to specify the fill/stroke opacity separately.
Gradients in SVG - SVG: Scalable Vector Graphics
these nodes tell the gradient what color it should be at certain positions by specifying an offset attribute for the position, and a stop-color attribute.
...for instance, this one tells the gradient to start at the color red, change to transparent-black in the middle, and end at the color blue.
SVG In HTML Introduction - SVG: Scalable Vector Graphics
source here is the source to the example: <html> <head> <title>xtech svg demo</title> <style> stop.begin { stop-color:yellow; } stop.end { stop-color:green; } body.invalid stop.end { stop-color:red; } #err { display:none; } body.invalid #err { display:inline; } </style> <script> function signalerror() { document.getelementbyid('body').setattribute("class", "invalid"); } </script> </head> <body id="body" style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;"> <form> <fieldset> <legend>html form</legend> <p><label>enter something:</label> <input type="text"> <span id="err">incorrect value!</span></p> <p><input type="button" value="activate!
...ach has the following points in its favor: we have taken a regular html form that could have been part of an existing web site, and added an attractive, interactive background the approach is backwards compatible to browsers that do not support svg; simply, no background appears in them it's very simple and performs very well the picture dynamically sizes itself to the required size in an intelligent way we can have declarative style rules applying to both html and svg the same script manipulates both html and svg the document is entirely standards-based to add a linked image with dom methods to an embedded svg element, one has to use setattributens to set href.
Texts - SVG: Scalable Vector Graphics
WebSVGTutorialTexts
« previousnext » when talking about text in svg we have to differentiate two almost completely separate topics.
...the latter may be described in a later section of the tutorial, while we will focus completely on the first part: bringing text into an svg image.
Transport Layer Security - Web security
the transport layer security (tls) protocol is the standard for enabling two networked applications or devices to exchange information privately and robustly.
...clients that reconnect to the server can send requests immediately, eliminating the latency of the tls handshake entirely.
Common XSLT Errors - XSLT: Extensible Stylesheet Language Transformations
or use a download tool, those usually tell the mime type.
... missing features there are some features in the xslt 1.0 specification which firefox unfortunately does not yet support.
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
// importnode is used to clone the nodes we want to process via xslt - true makes it do a deep clone var mynode = document.getelementbyid("example"); var clonednode = xmlref.importnode(mynode, true); // after cloning, we append xmlref.appendchild(clonednode); // set the sorting parameter in the xsl file var sortval = xsltprocessor.getparameter(null, "myorder"); if (sortval == "" || sortval == "descending") xsltprocessor.setparameter(null, "myorder", "ascending"); else xsltprocessor.setparameter(nul...
...l, "myorder", "descending"); // initiate the transformation var fragment = xsltprocessor.transformtofragment(xmlref, document); // clear the contents document.getelementbyid("example").innerhtml = ""; mydom = fragment; // add the new content from the transformation document.getelementbyid("example").appendchild(fragment) } // xsl stylesheet: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="html" indent="yes" /> <xsl:param name="myorder" /> <xsl:template match="/"> <xsl:apply-templates select="/div//div"> <xsl:sort select="." data-type="number" order="{$myorder}" /> </xsl:apply-template...
Loading Content Scripts - Archive of obsolete content
it takes one of three possible values: "start" loads the scripts immediately after the document element for the page is inserted into the dom.
self - Archive of obsolete content
note that the self object in content scripts is completely different from the self module, which provides an api for an add-on to access its data files and id.
Contributor's Guide - Archive of obsolete content
unfortunately, javascript does not yet have native support for modules: it has to rely on the host application to provide it with functionality such as loading subscripts, and exporting/ importing names.
Testing the Add-on SDK - Archive of obsolete content
with jpm (which is not part of the add-on sdk repo, and must be installed separately) things more difficult without the gulp commands provided by the gulpscript.js file in the addon-sdk repo.
hotkeys - Archive of obsolete content
for example, accel-s is typically used to save a file, but if you use it for something completely different, then it would be extremely confusing for users.
tabs - Archive of obsolete content
a string telling you the load state of the document hosted by this tab.
/loader - Archive of obsolete content
resolve the optional resolve option enables you to completely customize module resolution logic.
content/loader - Archive of obsolete content
this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read...
core/namespace - Archive of obsolete content
also, multiple namespaces can be used with one object: // ./widget.js let { cu } = require('chrome'); let { ns } = require('sdk/core/namespace'); let { view } = require('./view'); // note this is completely independent from view's internal namespace object.
core/promise - Archive of obsolete content
defer module exports defer function, which is where all promises ultimately come from.
frame/utils - Archive of obsolete content
usage module exports create function that takes the nsidomdocument of a privileged document and creates a browser element in its documentelement: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,foo'); let frame = create(window.document); optionally create can be passed set of options to configure created frame even further.
io/file - Archive of obsolete content
unfortunately this api does not currently provide a way to obtain an absolute base path which you could then use with join.
io/text-streams - Archive of obsolete content
if the stream is already closed, an exception is thrown immediately.
system/child_process - Archive of obsolete content
since it emulates the node.js child_process api, it's not documented separately here.
package.json - Archive of obsolete content
updatelink same as the updatelink for an update.rdf file.
Creating annotations - Archive of obsolete content
here's the code: var textarea = document.getelementbyid('annotation-box'); textarea.onkeyup = function(event) { if (event.keycode == 13) { self.postmessage(textarea.value); textarea.value = ''; } }; self.on('message', function() { var textarea = document.getelementbyid('annotation-box'); textarea.value = ''; textarea.focus(); }); save this inside data/editor as annotation-editor.js.
Chrome Authority - Archive of obsolete content
your modules should refrain from using chrome privileges unless they are absolutely necessary.
Display a Popup - Archive of obsolete content
var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline.
Listening for Load and Unload - Archive of obsolete content
if your add-on exports a function called main(), that function will be called immediately after the overall main.js is evaluated, and after all top-level require() statements have run (so generally after all dependent modules have been loaded).
Open a Web Page - Archive of obsolete content
to open a new web page, you can use the tabs module: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); this function is asynchronous, so you don't immediately get back a tab object which you can examine.
Unit Testing - Archive of obsolete content
unfortunately these functions are attached to the window object: since this object is not available in your main add-on code, atob() and btoa() aren't available either.
Localization - Archive of obsolete content
for example, here's a "package.json" defining a german localization for title and description: { "locales": { "de": { "title": "monstergenerator", "description": "erstelle dein eigenes monster" } }, "name": "monster-builder", "license": "mpl 2.0", "author": "me", "version": "0.1", "title": "monster builder", "id": "monster-builder@me.org", "description": "build your own monster" } using localized strings in preferences by including a "preferences" structure in your add-on's "package.json" file, you can define preferences...
Downloading Files - Archive of obsolete content
var privacy = privatebrowsingutils.privacycontextfromwindow(aurlsourcewindow); var progresselement = document.getelementbyid("progress_element"); persist.progresslistener = { onprogresschange: function(awebprogress, arequest, acurselfprogress, amaxselfprogress, acurtotalprogress, amaxtotalprogress) { var percentcomplete = math.round((acurtotalprogress / amaxtotalprogress) * 100); progresselement.textcontent = percentcomplete +"%"; }, onstatechange: function(awebprogress, arequest, astateflags, as...
Forms related code snippets - Archive of obsolete content
function ondayclick () { const othiscal = ainstances[this.id.replace(rbgnandend, "")]; othiscal.target.value = (this.innerhtml / 100).tofixed(2).substr(-2) + "\/" + (othiscal.current.getmonth() + 1) + "\/" + othiscal.current.getfullyear(); othiscal.container.parentnode.removechild(othiscal.container); return false; } function buildcalendars () { const afields = document.getelementsbyclassname(sdpclass), nlen = afields.length; for (var nitem = 0; nitem < nlen; new datepicker(afields[nitem++])); } const /* customizable by user */ sprefs = "zdp"; sdpclass = "date-picker", smonthsnames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"], sdays = ["m", "t", "w", "t", "f", "s", "s"], bzeroismonday = true, ...
Examples and demos from articles - Archive of obsolete content
determine if an element has been totally scrolled [html] this example shows how to determine whether a user has completely scrolled an element or not.
IsDefaultNamespace - Archive of obsolete content
} } } if (node.parentnode) { // entityreferences may have to be skipped to get to it return isdefaultnamespace(node.parentnode, namespaceuri); } else { return false; // unknown; } case 9: // document_node return isdefaultnamespace(node.documentelement, namespaceuri); case 6: // entity_node case 12: // notation_node case 10: // document_type_node case 11: // document_fragment_node return false; // unknown case 2: // attribute_node: if (node.ownerelement ) { return isdefaultnamespace(node.ownerelement , namespaceuri); } else { ...
JS XPCOM - Archive of obsolete content
accessing xpcom components from javascript xpcom objects are either created as new instances (each creation gives you a completely new com object) or as services (each access gives you the same com object, often called a singleton).
LookupNamespaceURI - Archive of obsolete content
} } if (node.parentnode && node.parentnode.nodetype !== 9) { // entityreferences may have to be skipped to get to it return lookupnamespaceurihelper(node.parentnode, prefix); } return null; case 9: // document_node return lookupnamespaceurihelper(node.documentelement, prefix); case 6: // entity_node case 12: // notation_node case 10: // document_type_node case 11: // document_fragment_node return null; // unknown case 2: // attribute_node if (node.ownerelement) { return lookupnamespaceurihelper(node.ownerelement, prefix); } ...
LookupPrefix - Archive of obsolete content
ext/html') { // shouldn't use this in text/html for mozilla as will return null return node.lookupprefix(namespaceuri); } if (namespaceuri === null || namespaceuri === '') { return null; } switch (node.nodetype) { case 1: // node.element_node return _lookupnamespaceprefix(namespaceuri, node); case 9: // node.document_node return _lookupnamespaceprefix(namespaceuri, node.documentelement); case 6: // node.entity_node case 12: // node.notation_node case 11: // node.document_fragment_node case 10: // node.document_type_node return null; // type is unknown case 2: // node.attribute_node if (node.ownerelement) { return _lookupnamespaceprefix(namespaceuri, node.ownerelement); } return null; default: if (node.parentnode) { // entityreferences ma...
On page load - Archive of obsolete content
pt to your overlay (see "attaching a script to an overlay") that adds a load event listener to appcontent element (browsers) or messagepane (mail): window.addeventlistener("load", function load(event){ window.removeeventlistener("load", load, false); //remove listener, no longer needed myextension.init(); },false); var myextension = { init: function() { var appcontent = document.getelementbyid("appcontent"); // browser if(appcontent){ appcontent.addeventlistener("domcontentloaded", myextension.onpageload, true); } var messagepane = document.getelementbyid("messagepane"); // mail if(messagepane){ messagepane.addeventlistener("load", function(event) { myextension.onpageload(event); }, true); } }, onpageload: function(aevent) { var doc =...
Preferences - Archive of obsolete content
you may wish for such changes to be applied immediately in your extension.
Rosetta - Archive of obsolete content
getsource(oscript) : createscript(oscript); } } function parsedocument () { for ( var ascripts = document.getelementsbytagname("script"), nidx = 0; nidx < ascripts.length; parsescript(ascripts[nidx++]) ); } var odicts = {}, rignoremimes = /^\s*(?:text\/javascript|text\/ecmascript)\s*$/; this.translatescript = parsescript; this.translateall = parsedocument; this.appendcompiler = function (vmimetypes, fcompiler) { if (arguments.length < 2) { throw new ...
Tabbox - Archive of obsolete content
handling onclosetab event assuming the tabbox, tabs, and tabpanels widgets with id's the same as their nodename, this function will correctly remove the current tab and tab panel for the onclosetab tabs event: function removetab(){ var tabbox = document.getelementbyid("tabbox"); var currentindex = tabbox.selectedindex; if(currentindex>=0){ var tabs=document.getelementbyid("tabs"); var tabpanels=document.getelementbyid("tabpanels"); tabpanels.removechild(tabpanels.childnodes[currentindex]); tabs.removeitemat(currentindex); /*work around if last tab is removed, widget fails to advance to next tab*/ if(-1 == tabbox.selecte...
JavaScript Daemons Management - Archive of obsolete content
if the daemon is running it will be immediately updated with the new property.
Toolbar - Archive of obsolete content
@optional */ function installbutton(toolbarid, id, afterid) { if (!document.getelementbyid(id)) { var toolbar = document.getelementbyid(toolbarid); // if no afterid is given, then append the item to the toolbar var before = null; if (afterid) { let elem = document.getelementbyid(afterid); if (elem && elem.parentnode == toolbar) before = elem.nextelementsibling; } toolbar.insertitem(id, be...
Windows - Archive of obsolete content
var hr = document.createelementns("http://www.w3.org/1999/xhtml", "html:hr"); document.getelementbyid("id1").appendchild(hr); ...
XPath - Archive of obsolete content
thexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return; } var fields = [];//store the results if(window.activexobject) { var tobj = obj.documentelement.selectnodes("/root/field/item"); for(var i=0;i<tobj.length; i++) { fields.push(tobj[i].text); } } else { var tobj = obj.evaluate("/root/field/item",obj.documentelement,null, xpathresult.any_type, null); var ...
Code snippets - Archive of obsolete content
these examples demonstrate how to accomplish basic tasks that might not be immediately obvious.
Deploying a Plugin as an Extension - Archive of obsolete content
for example: <em:updateurl><http://www.rhapsody.com/update.rdf></em:updateurl> this url specifies an rdf file that can be used to tell firefox that there are updates available for your extension.
Developing add-ons - Archive of obsolete content
they can add anything from a toolbar button to a completely new feature.
Inline options - Archive of obsolete content
for example: var observer = { observe: function(asubject, atopic, adata) { if (atopic == "addon-options-displayed" && adata == "my_addon@my_domain") { var doc = asubject; var control = doc.getelementbyid("myaddon-pref-control"); control.value = "test"; } } }; services.obs.addobserver(observer, "addon-options-displayed", false); // don't forget to remove your observer when your add-on is shut down.
Appendix: What you should know about open-source software licenses - Archive of obsolete content
insert the license declaration in the top of every file in your source code; include the full text of the license in your source-code archive; place the source code on a website or otherwise make it accessible; tell all your friends.
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
listing 4: an example manipulation using the dom var bar = document.getelementbyid('toolbar'); bar.removechild(bar.childnodes[1]); bar.appendchild(document.createelement('button')); bar.lastchild.setattribute('label', 'hello!'); « previousnext » ...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
listing 21: loading a page by setting a referrer var browser = document.getelementbyid('browser'); var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var referrer = ioservice.newuri('http://www.gihyo.co.jp/', null, null); browser.loaduri('http://www.gihyo.co.jp/magazines/sd', referrer); listing 22: loading a page with data transmitted via the post method var content = encodeuricomponen...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
you'll probably still need to override a couple other css rules to get a completely plain look.
Introduction - Archive of obsolete content
the user agent string for firefox at the time of this writing (in us english, mac os x) is: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:25.0.1) gecko/20100101 firefox/25.0.1 the highlighted section is the gecko version: 25.0.1.
Observer Notifications - Archive of obsolete content
the observer notifications page lists some useful topics and is definitely worth spending time studying it.
User Notifications and Alerts - Archive of obsolete content
also, clicking on any of your custom buttons will cause the notification to be immediately closed, so you should only use notification boxes for single-step processes.
XPCOM Objects - Archive of obsolete content
the first parameter is an input that tells the method where to start looking.
Performance best practices in extensions - Archive of obsolete content
the listeners should be added to the most specific element possible, and removed when not immediately necessary.
Setting up an extension development environment - Archive of obsolete content
dom inspector, used to inspect and edit the live dom of any web document or xul application (firefox and thunderbird) venkman, a javascript debugger (firefox version, thunderbird version) thunderbird developer tools, enables debugging thunderbird remotely using using firefox developer tools extension developer's extension a suite of tools for extension development (firefox) extension test an add-on which makes it easier to detect problems which will lead to rejection by addons.mozilla.org console² enhanced javascript console (firefox version, thunderbird version) javascript command for writing/testing javascript on firefox windows inspect c...
Signing an XPI - Archive of obsolete content
u,u,cu certum root ca ct,c,c certum level iii ca ct,c,c the name given to the newly issued certificate in the mozilla firefox keystore is not the easiest key alias in the world to remember, so i've added an additional step here that lets you rename it (its not just a simple rename operation, unfortunately).
Firefox addons developer guide - Archive of obsolete content
each chapter should be tagged appropriately, based on content, and every chapter should include the tag "firefox addons developer guide".
Promises - Archive of obsolete content
this.saver = new deferredsave(this.path, () => json.stringify(this.data), 1000); return this; }.bind(this)); } /** * immediately save the data to disk.
Underscores in class and ID Names - Archive of obsolete content
this unfortunately complicated an already complex landscape.
XUL user interfaces - Archive of obsolete content
copy and paste the content from here, making sure that you scroll to get all of it: // xul demonstration var datebox, daybox, currentday, status; // elements // called by window onload function init() { datebox = document.getelementbyid("date-text") daybox = document.getelementbyid("day-box") status = document.getelementbyid("status") settoday(); } // called by clear button function cleardate() { datebox.value = "" refresh() } // called by today button function settoday() { var d = new date() datebox.value = (d.getmonth() + 1) + "/" + d.getdate() + "/" + d.getfullyear() refresh() } // ca...
CSS3 - Archive of obsolete content
formally defines the css data types of css 2.1, that were implicitely defined by their grammar token and some textual precisions.
dischargingtimechange - Archive of obsolete content
property type description batterymanager.dischargingtime double (float) the remaining time in seconds until the system's battery is completely discharged and the system is about to be suspended.
Getting the page URL in NPAPI plugin - Archive of obsolete content
there's unfortunately no trivial way to do that, but you can still do it, by asking the browser for the page url during plugin initialization.
Creating a Web based tone generator - Archive of obsolete content
d selected } var k = 2* math.pi * frequency / samplerate; for (var i=0, size=sounddata.length; i<size; i++) { sounddata[i] = math.sin(k * currentsoundsample++); } } var audiodestination = new audiodatadestination(samplerate, requestsounddata); function start() { currentsoundsample = 0; frequency = parsefloat(document.getelementbyid("freq").value); } function stop() { frequency = 0; } </script> </body> </html> ...
Environment variables affecting crash reporting - Archive of obsolete content
moz_crashreporter_disable disable breakpad crash reporting completely.
Images, Tables, and Mysterious Gaps - Archive of obsolete content
unfortunately, the buttons in the top cell are all now block-level and so end up stacked on top of one another instead of being shown side-by-side.
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
you can access the components value and value-data pair (telling you where the components directory is) in a similar manner, e.g.: components=c:\program files\netscape\netscape 6\components.
Monitoring WiFi access points - Archive of obsolete content
<html> <head> <title>wifi monitor example</title> <script> var count = 0; function test() { } test.prototype = { onchange: function (accesspoints) { netscape.security.privilegemanager.enableprivilege('universalxpconnect'); var d = document.getelementbyid("d"); d.innerhtml = ""; for (var i=0; i<accesspoints.length; i++) { var a = accesspoints[i]; d.innerhtml += "<p>" + a.mac + " " + a.ssid + " " + a.signal + "</p>"; } var c = document.getelementbyid("c"); c.innerhtml = "<p>" + count++ + "</p>"; }, onerror: function (value) { alert("error: " +value); }, queryinterface: function(iid) { ...
Source Navigator - Archive of obsolete content
let me know if this is wrong..) it can generate a class hierarchy quite easily (unfortunately, not for classnames which are defined by macro.) installing source navigator in ubuntu execute the following line in a terminal window: sudo apt-get install sourcenav this should install source-navigator.
Source code directories overview - Archive of obsolete content
for example, a scrolling view will find out the scroll bar positions and tell its content where to draw according the scroll bar thumbs.
Automated testing tips and tricks - Archive of obsolete content
files.ini and populate the new profile directory with a prefs.js file firefox-bin -createprofile "testprofile ${profile_dir}/testprofile" next, start firefox to populate the new profile directory with the rest of the default settings firefox-bin -p testprofile -chrome chrome://tests/content/quit.xul<code> the above process may exit before the profile is completely created.
How Mozilla finds its configuration files - Archive of obsolete content
mozilla includes a profile manager, but unfortunately this always include a random part (salt) into the profile's filename, and thus cannot be used to point mozilla to a profile of the our chosing.
Kill the XUL.mfl file for good - Archive of obsolete content
unfortunately, there appears to be no "clean" way of doing so (javascript command in prefs.js or registry setting).
Locked config settings - Archive of obsolete content
moreover, some settings (such as mail & news configuration) unfortunately seem to be inaccessible to mozilla.cfg, which means that these cannot be locked.
Protecting Mozilla's registry.dat file - Archive of obsolete content
in other windows versions, internet explorer (which is hard to kick off completely) likes to install "personnalized settings" when the user logs in for the first time, and this seems to have the interesting "side-effect" of wiping any non-microsoft subfolders from %userprofile%\application data, including mozilla's .
Conclusion - Archive of obsolete content
future directions for development of the tutorial and/or coursework: in addition to build status, tinderbox also tells you if the cvs tree is open or closed for check-ins.
Enabling the behavior - updating the status bar panel - Archive of obsolete content
function updatetinderboxstatus() { var icon = document.getelementbyid('tinderbox-status'); if (gxmlhttprequest.responsetext.match("ee0000")) icon.setattribute("status", "busted"); else if (gxmlhttprequest.responsetext.match("ffaa00")) icon.setattribute("status", "testfailed"); else if (gxmlhttprequest.responsetext.match("11dd11")) icon.setattribute("status", "success"); else icon.setattribute("status", ""); } updatetinderboxstatus() retrieves a reference to the statusbarpanel element then searches through the retrieved html document (stored in the responsetext property of the xmlhttprequest instance) for one of several color references.
Finding the file to modify - Archive of obsolete content
mention the localization layer (note: these layers are not completely mutually exclusive.
Tinderbox - Archive of obsolete content
the tool enables mozilla.org to be immediately notified of changes to the code that prevent mozilla from compiling and running (or compromise performance and footprint) so they can get someone to fix the problem or reverse the changes.
Getting Started - Archive of obsolete content
css files the css files in these directories tell the browser how to display the buttons and other controls, where to put the images, what border and padding it should put around them, and so on.
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
css files the css files in these directories tell the browser how to display the buttons and other controls, where to put the images, what border and padding it should put around them, and so on.
Installing Dehydra - Archive of obsolete content
(alternately, build from source) a modern linux distribution.
Drag and drop events - Archive of obsolete content
this support is added in firefox 3.5, and is documented separately on the page [drag and drop].
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
it implements the iappfilelocprovider interface, and tells xpcom where to find certain files and directories.
Layout FAQ - Archive of obsolete content
how do you find out if there are any reflows that are pending and wait to show the view until afterwards, but if none are pending, show the view immediately?
Repackaging Firefox - Archive of obsolete content
the following diagram represents an overview of the process and the pieces involved: you will need the following to get started: a macintosh computer (even for repackaging windows or linux only); it may be either powerpc or intel based.
Style System Overview - Archive of obsolete content
a rule node that uses the same struct as its parent is marked with a “dependent bit” for that struct, which tells nsrulenode::getstyledata to just get the struct from the parent.
GRE - Archive of obsolete content
unfortunately, the mozilla suite-based gre is not as forgiving, especially on linux.
Creating a Help Content Pack - Archive of obsolete content
however, while it may seem like this is a disadvantage, it's actually an advantage - if you make an error you'll know immediately, and you should be able to easily figure out what the problem is by directly loading the file in firefox.
generateCRMFRequest() - Archive of obsolete content
acceptable values are (the mentioned values for keyusage pertain to the keyusage value of the certificate extension that will ultimately be in the issued certificate): "rsa-ex" - generate an rsa key for key exchange only (this will have eyencipherment set for keyusage.) "rsa-dual-use" - generate a single rsa key for both signing and encryption.
popChallengeResponse - Archive of obsolete content
challenge ::= sequence { owf algorithmidentifier optional, -- must be present in the first challenge; may be omitted in any -- subsequent challenge in popodeckeychallcontent (if omitted, -- then the owf used in the immediately preceding challenge is -- to be used).
Java in Firefox Extensions - Archive of obsolete content
one example seems to be the fact that the "java" global is not immediately available if the extension operates in a sidebar (using settimeout solved it at least).
First run - Archive of obsolete content
for example, you may want to tell users how to use your jetpack or link to your jetpack's homepage.
First Run - Archive of obsolete content
for example, you may want to tell users how to use your jetpack or link to your jetpack's homepage.
Jetpack Snippets - Archive of obsolete content
true); }}); calling into a slidebar from the global jetpack scope jetpack.slidebar.append({ onready: function (slide) { // call out to a global function, passing the slidebar object exinitslidebar(slide); }, ...});function exinitslidebar(aslidebar) { // this variable will now be global slider = aslidebar;} // then, accessing the slidebar htmlvar tl = slider.contentdocument.getelementbyid("thumblist"); // or calling slidebar api methods or accessing propertiesslider.notify(); ...
Makefile.mozextension.2 - Archive of obsolete content
note: unfortunately, this wiki system at developer.mozilla.org will try to parse xml declarations - even if they are within a pre tag!!
Message Summary Database - Archive of obsolete content
the mork code uses a lot of terminology of its own invention, as near as i can tell (though i suspect most db code would be that way).
Microsummary topics - Archive of obsolete content
thus if your cache headers tell firefox not to refresh a page on your site more than once per hour, and the user reloads the page within that time period, the user will see the cached version of your page, which may not be what you want.
Modularization techniques - Archive of obsolete content
this mechanism can be used both inside an executable at run-time and externally using the apersist flag to tell the repository to store the class id/library relationship in its permenant store.
Plug-n-Hack Phase1 - Archive of obsolete content
the preference is ringleader.check.origin this can be set to 'off' to disble origin checks completely, or 'noport' to disable only port checks.
Plug-n-Hack - Archive of obsolete content
while some of the pnh capabilities do have a fixed meaning, particularly around proxy configuration, most of the capabilities are completely generic, allowing tools to expose whatever functionality they want.
Plugin Architecture - Archive of obsolete content
if a frame comes into existance independent of that, it tells the content node that it exists now (nsiobjectloadingcontent::hasnewframe).
Porting NSPR to Unix Platforms - Archive of obsolete content
usually <tt>jmp_buf</tt> is an array of integers, and some platforms have a <tt>jb_sp</tt> macro that tells you which array element is the stack pointer.
BundleLibrary - Archive of obsolete content
slimtimer client slimtimer.webapp a very useful time-tracking tool with a "slim" client spagobi spagobi.webapp a web collaborative business intelligence platform streamy streamy.webapp ( streamy is a pretty powerful, next-gen online rss feed reader.
Reading textual data - Archive of obsolete content
is.init(file, -1, -1, 0); var lis = fis.queryinterface(components.interfaces.nsilineinputstream); var linedata = {}; var cont; do { cont = lis.readline(linedata); var line = converter.converttounicode(linedata.value); // now you can do something with line } while (cont); fis.close(); see also writing textual data joel on software: the absolute minimum every software developer absolutely, positively must know about unicode and character sets ...
Rsyncing the CVS Repository - Archive of obsolete content
references thanks also to bz for telling me the exact commands that i need ...
Running Windows Debug Builds Downloaded From Tinderbox - Archive of obsolete content
unfortunately these dlls are not redistributable.
Safely loading URIs - Archive of obsolete content
there's no way to do this completely securely in gecko versions prior to 1.8.0.4.
Merging TraceMonkey Repo - Archive of obsolete content
inspecting the files at those two changesets can be helpful: hg cat -c changeset filename once all the conflict markers are removed, you've performed the manual resolution, which you tell to mercurial by running hg resolve -m filename.
Standard Makefile Header - Archive of obsolete content
this header sets variables which tell the makefile where it is and where the source directory is, and then include autoconf.mk, to pick up makefile variables which are set during configuration.
Running Tamarin acceptance tests - Archive of obsolete content
tests complete at 2010-09-28 10:39:26.751797 start date: 2010-09-28 10:38:07.221457 end date : 2010-09-28 10:39:26.751797 test time : 0:01:19.530340 passes : 59291 failures : 0 expected failures : 75 tests skipped : 76 the -f flag tells runtests.py to force recompilation of all the scripts.
Tamarin Releases - Archive of obsolete content
upcoming release name(s)release datelinks tc next~ april 2009roadmap current release namerelease datelinks tc "mar 2009" a5c9ed928c9603/27/09tamarin-devel announcement prior release name(s)release datelinks tc "feb 2009" a5c9ed928c9602/19/09tamarin-devel announcement tamarin-central rev 703:2cee46be9ce0 12/02/08tamarin-devel announcement ...
Tuning Pageload - Archive of obsolete content
content.interrupt.parsing this preference, when true, means that the content sink can tell the parser to stop for now and return to the event loop, which allows layout and painting to happen.
URIs and URLs - Archive of obsolete content
unfortunately, this can conflict with the correct parsing of non-hierarchical uri.
Venkman Internals - Archive of obsolete content
to obtain the antecedent files: doc.getelementsbytagname("script"); then extract the urls from the src attributes.
Using Breakpoints in Venkman - Archive of obsolete content
the log result checkbox tells venkman you want the result of the script to show up in the interactive session view.
When To Use ifdefs - Archive of obsolete content
this can mean that there are completely different interfaces with the same name which are built conditionally.
Writing textual data - Archive of obsolete content
passing 0 ensures that data will be immediately written to the underlying stream; however, for better perfomance you should pass a value like 4096 instead.
Binding Implementations - Archive of obsolete content
for example, a binding could override the setattribute method on element or the retrieval of the value property for an htmlinputelement.
XBL - Archive of obsolete content
unfortunately, the actual implementation in mozilla is different from the specification, and there's no known document available describing the differences.
Mac stub installer - Archive of obsolete content
unfortunately, at the time of this writing there is no convenient way to test an installer build like there is on unix (deliver.pl) and windows (build.pl).
Install script template - Archive of obsolete content
// this block also invokes a function to write registry keys (plid) and checks return from key writing // this block invokes refreshplugins() to ensure that plugin and xpt are available for use immediately if (errblock1 == success) { // installation to the current browser was a success - this is the most important job of this script!
addDirectory - Archive of obsolete content
xpisourcepath a string specifying the location of the directory within the xpi file.an empty string ("") causes the creation of a subdirectory node in the registry without actually unpacking any files, which may be useful when you are updating a package that contains subcomponents that could also be updated separately.
execute - Archive of obsolete content
the following line, for example, passes the "-c" command-line parameter to the executable: err = file.execute(myfile, "-c", true); when you want to pass more than one parameter to the executable itself, however, you must format the args string in a particular way so that the parameters can be broken up and passed separately as required.
initInstall - Archive of obsolete content
you must call this method immediately after the constructor.
setPackageFolder - Archive of obsolete content
you should only call this method once, and you should always call it immediately after you call initinstall.
Learn XPI Installer Scripting by Example - Archive of obsolete content
note also that for the installation script in a xpi to be automatically triggered from a web page, you must use a "trigger script." the following installtrigger function, called from an event handler on a regular web page, will point to the remotely-hosted xpi (called here 'cdrip.xpi') and trigger its installation: function putit() { xpi={'cd_ripper':'cdrip.xpi'}; installtrigger.install(xpi); } ...
afterselected - Archive of obsolete content
« xul reference home afterselected type: boolean this is set to true if the tab is immediately after the currently selected tab.
beforeselected - Archive of obsolete content
« xul reference home beforeselected type: boolean this is set to true if the tab is immediately before the currently selected tab.
buttons - Archive of obsolete content
if it is set to true any changes to settings are supposed to be applied immediately.
disabled - Archive of obsolete content
// disabling an element document.getelementbyid('buttonremove').setattribute("disabled", "disabled"); // enabling back an element by removing the "disabled" attribute document.getelementbyid('buttonremove').removeattribute("disabled"); firefox 3.5 note for keyset elements, support for this attribute was added in firefox 3.5.
oninput - Archive of obsolete content
--> <script language="javascript"> function setlabel(txtbox){ document.getelementbyid('lbl').value = txtbox.value; } </script> <label id="lbl"/> <textbox oninput="setlabel(this);"/> this is similar to the onkeypress event used in html documents.
resizeafter - Archive of obsolete content
closest the element immediately to the right or below the splitter resizes.
resizebefore - Archive of obsolete content
closest the element immediately to the left or above the splitter resizes.
statustext - Archive of obsolete content
stext="connect to remote server" onmouseover="setstatusmessage(this)" onmouseout="clearstatusmessage()"/> <button label="ping" statustext="ping the server" onmouseover="setstatusmessage(this)" onmouseout="clearstatusmessage()"/> <statusbar> <statusbarpanel id="mystatuspanel" label="" flex="1"/> <spacer flex="1"/> </statusbar> <script> function setstatusmessage(obj){ document.getelementbyid('mystatuspanel').label = obj.getattribute('statustext'); } function clearstatusmessage(obj){ document.getelementbyid('mystatuspanel').label = ''; } </script> see also statusbar and statusbarpanel ...
textbox.disablehistory - Archive of obsolete content
this attribute only works correctly in seamonkey 1.x; for thunderbird and seamonkey 2.0 you should also set the enablehistory attribute; as of gecko 2.0 this attribute is completely superseded by it.
validate - Archive of obsolete content
this would be useful if the images are stored remotely or you plan on swapping the image frequently.
Reading from Files - Archive of obsolete content
fortunately as a character is always at least one byte long in the default utf-8 encoding, the number of characters will always be equal to or smaller than the number of bytes available.
findbar - Archive of obsolete content
possible values are: find_normal (0): normal find find_typeahead (1): typeahead find find_links (2): link find methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
How to implement a custom XUL query processor component - Archive of obsolete content
the variable passed into getbindingfor still has the "?" prepended to it, so be sure to handle it appropriately.
appendItem - Archive of obsolete content
example <script language="javascript"> function additemstolist(){ var list = document.getelementbyid('mymenulist'); // add item with just the label list.appenditem('one'); // add item with label and value list.appenditem('two', 999); // select the first item list.selectedindex = 0; } </script> <button label="add items" oncommand="additemstolist()"/> <menulist id="mymenulist"> <menupopup/> </menulist> see also insertitemat() removeitemat() ...
hidePopup - Archive of obsolete content
« xul reference home method of: popup, menupopup, tooltip hidepopup() return type: no return value closes the popup immediately.
insertItemAt - Archive of obsolete content
note: you cannot insert an item to an index that does not exist, eg: trying to insert an item at the end with element.getrowcount() + 1 example <!-- this example inserts at the selected item or appends, then selects the newly created item --> <script language="javascript"> function insertitemtolist(){ var mylistbox = document.getelementbyid('mylistbox'); // create a date to get some labels and values var somedate = new date(); if(mylistbox.selectedindex == -1){ // no item was selected in list so append to the end mylistbox.appenditem( somedate.tolocaletimestring(), somedate.gettime() ); var newindex = mylistbox.getrowcount() -1 }else{ // item was selected so insert at the s...
removeAllNotifications - Archive of obsolete content
if immediate is true, the messages are removed immediately.
removeItemAt - Archive of obsolete content
<script language="javascript"> function removeselecteditem(){ var mylistbox = document.getelementbyid('mylistbox'); if(mylistbox.selectedindex == -1){ return; // no item selected so return }else{ mylistbox.removeitemat(mylistbox.selectedindex); } } function removeallitems(){ var mylistbox = document.getelementbyid('mylistbox'); var count = mylistbox.itemcount; while(count-- > 0){ mylistbox.removeitemat(0); } } </script> <button label="remove selected item" oncommand="removeselecteditem()"/> <button label="remove all items" oncommand="re...
Namespaces - Archive of obsolete content
<foo/> the answer is that it's in no namespace, or alternately, it's in the namespace denoted by the empty string: <foo xmlns=""/> this second example is semantically equivalent to the first.
Menus - Archive of obsolete content
for example, to have an item initially hidden in a window: function initmenus() { var item = document.getelementbyid("menu-file-open"); item.hidden = true; } the hidden property is set to true to hide the menu with the id 'menu-fileopen'.
Special per-platform menu considerations - Archive of obsolete content
for example, using document.getelementbyid() for the quit menu item returns the hidden item that still sits in the file menu.
controllers - Archive of obsolete content
example <window id="controller-example" title="controller example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init() { var list = document.getelementbyid("thelist"); var listcontroller = { supportscommand : function(cmd){ return (cmd == "cmd_delete"); }, iscommandenabled : function(cmd){ if (cmd == "cmd_delete") return (list.selecteditem != null); return false; }, docommand : function(cmd){ list.removeitemat(list.selectedindex); }, onevent : function(evt){ } }; list.controllers.appendcontr...
currentIndex - Archive of obsolete content
<script language ="javascript"> function treerowclicked(){ var tree = document.getelementbyid("my-tree"); var selection = tree.view.selection; var celltext = tree.view.getcelltext(tree.currentindex, tree.columns.getcolumnat(0)); alert(celltext); } </script> <tree id="my-tree" seltype="single" onselect="treerowclicked()"> <treecols> <treecol label="title" flex="1"/><treecol label="url" flex="1"/> </treecols> <treechildren> <treeitem> <treerow> ...
disabled - Archive of obsolete content
<!-- checkbox enables/disables the button --> <checkbox label="enable button" oncommand="document.getelementbyid('buttremove').disabled = !
itemCount - Archive of obsolete content
example var bucket = document.getelementbyid("attachmentbucket"); if(bucket.itemcount == 0) { dump("\n\n no attachments \n\n"); } else { dump("\n\n attachment exists \n\n"); } ...
Actions - Archive of obsolete content
you can use getelementbyid to get at particular results, for instance document.getelementbyid("http://www.xulplanet.com/rdf/c") would retrieve the second generated button.
Additional Navigation - Archive of obsolete content
it may be difficult to tell whether the builder will look for arcs pointing out from a node or into a node just by looking at the triple element.
Building Menus With Templates - Archive of obsolete content
the special feature of menus to not generate content immediately applies only to the menu itself.
Introduction - Archive of obsolete content
if the datasource is already loaded, the builder can construct content all in one step, although even this isn't completely true as we'll see later.
Simple Example - Archive of obsolete content
you might note that the image's src attribute uses the member variable ?photo <action> <vbox uri="?photo" align="start"> <image src="?photo"/> <label value="?title"/> </vbox> </action> it shouldn't be too difficult to tell what would appear in the window in this example.
Simple Query Syntax - Archive of obsolete content
function applyfilter(country) { var rule = document.getelementbyid("filterrule"); if (country){ rule.setattributens("http://www.xulplanet.com/rdf/", "country", country); } else { rule.removeattributens("http://www.xulplanet.com/rdf/", "country"); } document.getelementbyid("photoslist").builder.rebuild(); } this version of the applyfilter function only needs to set or remove the attribute on the rule as necessary.
Sorting Results - Archive of obsolete content
changing the sort to change the sorting for a template's generated contents, you can either change the sort related attributes and rebuild the template, or you can call the sort method of the sort service: var listbox = document.getelementbyid("alistbox"); var sortservice = components.classes["@mozilla.org/xul/xul-sort-service;1"].
Special Condition Tests - Archive of obsolete content
the iscontainer attribute will also match containers appropriately if you have used the containment attribute in the template to change the predicates that indicate containership.
Code Samples - Archive of obsolete content
change the first line to specify the page that you want to open: const url = "http://www.mozilla.org/" document .getelementbyid("content") .webnavigation .loaduri(url, 0, null, null, null) if your button is in thunderbird or sunbird, use code like this to open a web page.
Complete - Archive of obsolete content
to tell the application that the files it needs are in a jar, there are changes to chrome.manifest (for firefox etc.) and to install.js (for seamonkey).
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
this page tells you step-by-step how to make a custom toolbar button in seamonkey 1.x.
Custom toolbar button - Archive of obsolete content
this page tells you step-by-step how to make a custom toolbar button in firefox, seamonkey 2.0, thunderbird or sunbird.
Adding Event Handlers - Archive of obsolete content
the syntax is as follows: example 3 : source view <button id="okbutton" label="ok"/> <script> function buttonpressed(event){ alert('button was pressed!'); } var button = document.getelementbyid("okbutton"); button.addeventlistener('command', buttonpressed, true); </script> the getelementbyid() function returns the element with a given id, in this case the button.
Adding Methods to XBL-defined Elements - Archive of obsolete content
xul: <box id="num" class="labeledbutton" title="number of things:" value="52"/> <button label="show" oncommand="document.getelementbyid('num').showtitle(true)"/> <button label="hide" oncommand="document.getelementbyid('num').showtitle(false)"/> xbl: <binding id="labeledbutton"> <content> <xul:label xbl:inherits="value=title"/> <xul:label xbl:inherits="value"/> </content> <implementation> <method name="showtitle"> <parameter name="state"/> <body> if (state) { document.geta...
Adding Style Sheets - Archive of obsolete content
if your xul file is stored remotely and accessed via an http url, you can store the style sheet remotely as well.
Advanced Rules - Archive of obsolete content
you can view the rdf file separately: wheater.rdf example 1 : source <tree id="weathertree" flex="1" datasources="weather.rdf" ref="http://www.xulplanet.com/rdf/weather/cities"> <treecols> <treecol id="city" label="city" primary="true" flex="1"/> <treecol id="pred" label="prediction" flex="1"/> </treecols> <template> <rule> <conditions> <content uri="?list"/> <member container="?list...
Broadcasters and Observers - Archive of obsolete content
example 3 : source view <broadcasterset> <broadcaster id="colorchanger" style="color: black"/> </broadcasterset> <button label="test"> <observes element="colorchanger" attribute="style" onbroadcast="alert('color changed');"/> </button> <button label="observer" oncommand="document.getelementbyid('colorchanger').setattribute('style','color: red');" /> two buttons have been created, one labeled test and the other labeled observer.
Install Scripts - Archive of obsolete content
the adddirectory() function tells the installer that a directory from the xpi archive (and all of its contents) should be installed to a particular location.
More Tree Features - Archive of obsolete content
this can sometimes be quite tricky, but fortunately, the built-in content tree view does all of the hard work for us.
More Wizards - Archive of obsolete content
wizard example source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="thewizard" title="secret code wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkcode(){ document.getelementbyid('thewizard').canadvance = (document.getelementbyid('secretcode').value == "cabbage"); } </script> <wizardpage onpageshow="checkcode(); return true;"> <label value="enter the secret code:"/> <textbox id="secretcode" onkeyup="checkcode();"/> </wizardpage> <wizardpage> <label value="that is the correct secret code."/> </wizardpage> </wizard> there is also a ...
RDF Datasources - Archive of obsolete content
the rdf file is fairly large and can be viewed separately: source rdf example 2 : source view <tree flex="1" width="200" height="200" datasources="animals.rdf" ref="http://www.some-fictitious-zoo.com/all-animals"> <treecols> <treecol id="name" label="name" primary="true" flex="1"/> <treecol id="species" label="species" flex="1"/> </treecols> <template> <rule> <treechildren> <treeitem uri="rdf:*"> <treerow...
Simple Menu Bars - Archive of obsolete content
this element can be placed on a menubar or can be placed separately.
Stack Positioning - Archive of obsolete content
stacks have the advantage that when one absolutely positioned element changes its position, the position of the other elements is not affected.
Stacks and Decks - Archive of obsolete content
this method has advantages over using text-shadow because you could completely style the shadow apart from the main text.
Updating Commands - Archive of obsolete content
fortunately, the extra code is fairly simple.
XPCOM Examples - Archive of obsolete content
<script> function getcookies() { var menu = document.getelementbyid("cookiemenu"); menu.removeallitems(); var cookiemanager = components.classes["@mozilla.org/cookiemanager;1"] .getservice(components.interfaces.nsicookiemanager); var iter = cookiemanager.enumerator; while (iter.hasmoreelements()){ var cookie = iter.getnext(); if (cookie instanceof components.interfaces.nsicookie){ if (cookie.host == "www.mo...
Using nsIXULAppInfo - Archive of obsolete content
id you can tell which application you're running under using the nsixulappinfo.id property.
Writing Skinnable XUL and CSS - Archive of obsolete content
for example, the sidebar should not import the global skin, since it could appear in messenger and in navigator (which could have two completely different color schemes).
XUL Parser in Python/source - Archive of obsolete content
import sys, glob, xmllib import os, re el_list = {} w = open('res.html', 'w') # unfortunately, i had to put this hack in here to suppress the printing out of the resolved namespace: # "xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul window", etc.
XUL element attributes - Archive of obsolete content
you can use this as a parameter to getelementbyid() and other dom functions and to reference the element in style sheets.
XUL Template Primer - Bindings - Archive of obsolete content
fortunately, this is the natural way one would write bindings, so in practice this should not be a burden.
XUL accessibility guidelines - Archive of obsolete content
ultimately, for applications that must be completely accessible, it is best to have the application tested by a variety of end users with different software and assistive technology configurations.
action - Archive of obsolete content
s, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
arrowscrollbox - Archive of obsolete content
inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
assign - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
bbox - Archive of obsolete content
ArchiveMozillaXULbbox
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
binding - Archive of obsolete content
es, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
bindings - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
box - Archive of obsolete content
ArchiveMozillaXULbox
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
broadcaster - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
broadcasterset - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
browser - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
button - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
caption - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
checkbox - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
colorpicker - Archive of obsolete content
value property gets and sets color attribute methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
column - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
columns - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
command - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
commandset - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
conditions - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
content - Archive of obsolete content
métodos inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
deck - Archive of obsolete content
ArchiveMozillaXULdeck
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
dialogheader - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
dropmarker - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
grid - Archive of obsolete content
ArchiveMozillaXULgrid
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
grippy - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
groupbox - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
hbox - Archive of obsolete content
ArchiveMozillaXULhbox
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
keyset - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
label - Archive of obsolete content
ArchiveMozillaXULlabel
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
listcell - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
listcol - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
listcols - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
listhead - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
listheader - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
listitem - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
member - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
menu - Archive of obsolete content
ArchiveMozillaXULmenu
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
menubar - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
menuseparator - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
notification - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
observes - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
page - Archive of obsolete content
ArchiveMozillaXULpage
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
param - Archive of obsolete content
ArchiveMozillaXULparam
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
popupset - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
preferences - Archive of obsolete content
inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
promptBox - Archive of obsolete content
a tab may have multiple prompts on it; the tabmodalpromptshowing attribute on the tabbrowser will tell you how many prompts a given tab has.
query - Archive of obsolete content
ArchiveMozillaXULquery
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
queryset - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
radio - Archive of obsolete content
ArchiveMozillaXULradio
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
resizer - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
richlistbox - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
richlistitem - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
row - Archive of obsolete content
ArchiveMozillaXULrow
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
rows - Archive of obsolete content
ArchiveMozillaXULrows
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
rule - Archive of obsolete content
ArchiveMozillaXULrule
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
scale - Archive of obsolete content
ArchiveMozillaXULscale
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
script - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
scrollbar - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
scrollbox - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
scrollcorner - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
separator - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
spacer - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
spinbuttons - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
stack - Archive of obsolete content
ArchiveMozillaXULstack
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
statusbar - Archive of obsolete content
es, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
<statusbarpanel> - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
stringbundle - Archive of obsolete content
inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
stringbundleset - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
tabbox - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
tabbrowser - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
tabpanel - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
tabpanels - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
tabs - Archive of obsolete content
ArchiveMozillaXULtabs
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
template - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
textbox - Archive of obsolete content
inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
textnode - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
titlebar - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbar - Archive of obsolete content
inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbargrippy - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbaritem - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbarpalette - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbarseparator - Archive of obsolete content
es, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbarset - Archive of obsolete content
es, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbarspacer - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbarspring - Archive of obsolete content
es, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
toolbox - Archive of obsolete content
methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributeno...
treecell - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
treechildren - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
treecol - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
treecols - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
treeitem - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
treerow - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
treeseparator - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
triple - Archive of obsolete content
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
vbox - Archive of obsolete content
ArchiveMozillaXULvbox
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
where - Archive of obsolete content
ArchiveMozillaXULwhere
, ordinal, orient, , pack, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
wizardpage - Archive of obsolete content
, , persist, , , , ref, resource, , , , , statustext, style, ,, tooltip, tooltiptext, top, width methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), remov...
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
right now mozilla recommends that xulrunner should be deployed privately with each application.
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
right now mozilla recommends that xulrunner should be deployed privately with each application.
XULRunner 1.9.1 Release Notes - Archive of obsolete content
right now mozilla recommends that xulrunner should be deployed privately with each application.
XULRunner 1.9.2 Release Notes - Archive of obsolete content
right now mozilla recommends that xulrunner should be deployed privately with each application.
XULRunner 1.9 Release Notes - Archive of obsolete content
right now mozilla recommends that xulrunner should be deployed privately with each application.
XULRunner 2.0 Release Notes - Archive of obsolete content
right now mozilla recommends that xulrunner should be deployed privately with each application.
Building XULRunner with Python - Archive of obsolete content
for example def onload(): btntest = document.getelementbyid("btntest") btntest.addeventlistener('command', ontest, false) def ontest(): window.alert('button activated') window.addeventlistener('load', onload, false) one possible gotcha is that the default python path used to find modules that areimported explicitly includes the xulrunner executable directory and the directory that is current when xulrunner launches.
XULRunner FAQ - Archive of obsolete content
right now mozilla recommends that xulrunner should be deployed privately with each application.
XULRunner Hall of Fame - Archive of obsolete content
build instructions kirix strata a new specialty browser for accessing and manipulating data from the web telekast an open source teleprompter and script editor.
XULRunner tips - Archive of obsolete content
in order to satisfy these dependencies, you can save firefox's brand.dtd/brand.properties to chrome/locale/branding folder, modify them appropriately, and register a locale provider for branding by adding the following line to your chrome manifest: locale branding en-us chrome/locale/branding/ the location you put the branding files in doesn't matter, as long as you register it appropriately in the manifest.
mozilla.dev.platform FAQ - Archive of obsolete content
in order to use xr successfully in <tt>--disable-libxul</tt> mode, you have to setup dyld_library_path to include <tt>/library/frameworks/xul.framework/versions/1.9a1</tt> - benjamin smedberg, fri, oct 20 2006 9:12 am q: when i try to build a completely standalone xul app on os x (10.4.8).
xbDesignMode.js - Archive of obsolete content
* contributor(s): doron rosenberg <doron@netscape.com> (original author) * * * * ***** end license block ***** */ /* xbdesignmode a javascript wrapper for browsers that support designmode */ function xbdesignmode(aiframe){ this.meditordocument = null; this.miframeelement = null; // argument is a string, therefore an id if ( (typeof(aiframe) == "string") && (document.getelementbyid(aiframe).tagname.tolowercase()=="iframe") ){ this.miframeelement = document.getelementbyid(aiframe); } else if( (typeof(aiframe)=="object") && (aiframe.tagname.tolowercase() == "iframe") ){ this.miframeelement = aiframe; } else { throw "argument isn't an id of an iframe or an iframe reference"; } if (this.miframeelement.contentdocument){ // gecko this.meditor...
2006-10-26 - Archive of obsolete content
debug minefield on intel mac an inqury about how to debug minefield on an intel mac.
2006-10-27 - Archive of obsolete content
debug minefield on intel mac an inqury about how to debug minefield on an intel mac.
2006-09-29 - Archive of obsolete content
he has already tried archiving the changed files but unfortunately this does not work with a static build because the .exe files change every time.
2006-11-24 - Archive of obsolete content
announcments bon echo status mike beltzner posted a small to-do list with regards to bon echo firefox 1.5.0.9/2.0.0.1 jay patel posted an update of bugs for the firefox 1.5.0.9/2.0.0.1 releases discussion non-ascii rendering performance boris zbarsky made some suggestions on how to improve international font rendering cvs commit access changes a large discussion went on about changes to policies surrounding cvs commit access project drivers and technical oversight mike connor suggested ways to better organize project management, policy making, and technical oversight.
2006-09-29 - Archive of obsolete content
summary of newsgroup moz.dev.platform summary: mozilla.dev.platform - september 22 - 29, 2006 announcements firefox 2 release candidate 1 is now available for download announcing that firefox 2 rc 1 is available for download discussions xulrunner fails without feedback on osx intel 10.4.7 will morton is trying to port a xul application to osx.
2006-09-29 - Archive of obsolete content
* @param ashrinkwrap whether the frame is in a context where * non-replaced blocks should shrink-wrap (e.g., * it's floating, absolutely positioned, or * inline-block).
2006-10-13 - Archive of obsolete content
discussion about the problem remotely connecting to a particular calendar meetings none this week.
2006-12-01 - Archive of obsolete content
universal binary or mac intel version of sb/lightning?
External resources for plugin creation - Archive of obsolete content
platforms supported include windows, linux, and mac os x (intel).
NPAPI plugin developer guide - Archive of obsolete content
dowed plug-ins mac os windows unix event handling for windowed plug-ins windowless plug-ins specifying that a plug-in is windowless invalidating the drawing area forcing a paint message making a plug-in opaque making a plug-in transparent creating pop-up menus and dialog boxes event handling for windowless plug-ins streams receiving a stream telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode sending a stream creating a stream pushing data into the stream deleting the stream example of sending a stream urls getting urls getti...
Multi-process plugin architecture - Archive of obsolete content
in addition to crash protection, the multi-process plugin architecture allows firefox to see plugins which respond very slowly or have completely stopped responding.
Browser-side plug-in API - Archive of obsolete content
this chapter describes methods in the plug-in api that are provided by the browser; these allow call back to the browser to request information, tell the browser to repaint part of the window, and so forth.
NPFullPrint - Archive of obsolete content
if you want an embedded plug-in to simply render its area of the page, set pluginprinted to false and return immediately; the browser calls npp_print again with the npembedprint substructure of npprint.
NPN_ForceRedraw - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary asks the plugin host to immediately (synchronously) repaint invalid areas.
NPN_InvalidateRect - Archive of obsolete content
to immediately send a paint message, the plug-in can call npn_forceredraw() after calling this method.
NPN_PluginThreadAsyncCall - Archive of obsolete content
calling npn_pluginthreadasynccall() on the "browser main thread" or the "plug-in thread" is legal; the call to npn_pluginthreadasynccall() returns immediately.
NPN_PostURL - Archive of obsolete content
npn_posturl is typically asynchronous: it returns immediately and only later handles the request.
NPN_PostURLNotify - Archive of obsolete content
npn_posturlnotify is typically asynchronous: it returns immediately and only later handles the request and calls npp_urlnotify.
NPN_SetValue - Archive of obsolete content
true=windowed, false=windowless nppvplugintransparentbool: sets transparent mode for display of a plugin; true=transparent, false=opaque nppvjavaclass nppvpluginwindowsize nppvplugintimerinterval nppvpluginscriptableinstance nppvpluginscriptableiid nppvjavascriptpushcallerbool: specifies whether you are pushing or popping the jscontext off the stack nppvpluginkeeplibraryinmemory: tells browser that the plugin dll should live longer than usual nppvpluginneedsxembed nppvpluginscriptablenpobject nppvformvalue nppvplugindrawingmodel value the value of the specified variable to be set.
NPP_DestroyStream - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary tells the plug-in that a stream is about to be closed or destroyed.
NPP_HandleEvent - Archive of obsolete content
description the browser calls npp_handleevent to tell the plug-in when events take place in the plug-in's window or drawable area.
NPP_NewStream - Archive of obsolete content
npp_streamasfile is simply called immediately.
NPP_SetWindow - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary tells the plug-in when a window is created, moved, sized, or destroyed.
NPP_Write - Archive of obsolete content
the buf parameter is not persistent, so the plug-in must process data immediately or allocate memory and save a copy of it.
NP_Initialize - Archive of obsolete content
np_initialize tells the plug-in that the browser has loaded it and provides global initialization.
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
the unpack property is necessary to tell applications using newer versions of gecko to unpack the plugin because dlls can't be loaded from xpi files.
Writing a plugin for Mac OS X - Archive of obsolete content
if you want to implement your plugin in c++ or objective-c++, you need to tell the compiler to export them in c format by using extern "c" in the header, like this: #pragma gcc visibility push(default) extern "c" { nperror np_initialize(npnetscapefuncs *browserfuncs); nperror np_getentrypoints(nppluginfuncs *pluginfuncs); void np_shutdown(void); } #pragma gcc visibility pop you can check to be sure your symbols are visible and in standard c format by using the n...
Plugins - Archive of obsolete content
plugins can be written completely from scratch using c apis (usually in c or c++) or they may be built on a plugin framework such as firebreath, juce, or qtbrowserplugin.
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
one of the shortcomings of the <slash:comments> element is that does not tell you what that moment in time was.
Syndicating content with RSS - Archive of obsolete content
when you make a blog, an internet radio show, or an internet television show, you are syndicating.
Why use RSS - Archive of obsolete content
people are using it to syndicate all sorts of things: news articles, blogs, bookmarks, internet radio shows, internet television shows, software updates, e-mails, mailing lists, music playlists, and more.
Vulnerabilities - Archive of obsolete content
ultimately, organizations need to know how difficult it is for someone to exploit each vulnerability and, if a vulnerability is exploited, what the possible impact would be.
Sunbird Theme Tutorial - Archive of obsolete content
copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest" em:id="just-testing@example.com" em:name="just testing" em:creator="rod whiteley" em:description="a test theme for sunbird" em:homepageurl="http://developer.mozilla.org/" em:version="0.1" em:internalname="testing" em:type="4" > <em:targetapplication><!-- sunbird --> <description em:id="{718e30fb-e89b-41dd-9da7-e25a45638b28}" em:minversion="0.2.9" em:maxversion="0.4" /> </em:targetapplication> </description> </r...
Tamarin Tracing Build Documentation - Archive of obsolete content
this is a shared resource, each request takes approximately 3+ hours to run so please use wisely.
Using IO Timeout And Interrupt On NT - Archive of obsolete content
unfortunately, <tt>cancelio()</tt> is not available on nt 3.51.
Summary of Changes - Archive of obsolete content
l 4.01 object deprecated applet html 4.01 object non-standard marquee html 4.01 div plus scripting non-standard bgsound html 4.01 object proprietary or deprecated feature w3c feature or recommended replacement ie5+ id_attribute_value document.all.id_attribute_value document.all[id_attribute_value] dom level 2: document.getelementbyid(id_attribute_value) ie5+ formname.inputname.value dom level 1: document.forms["formname"].inputname.value ie5+ inputname.value dom level 1: document.forms["formname"].inputname.value ie5+ formctrlname dom level 1: document.forms["formname"].formctrlname ie5+ document.forms(0) dom level 1: document.forms[0] ...
-moz-stack-sizing - Archive of obsolete content
normally, a <xul:stack> will change its size so that all of its child elements are completely visible.
-ms-content-zoom-snap-points - Archive of obsolete content
in the second selector, each snap-point is listed separately—100%, 200%, 300%, and so on.
-ms-hyphenate-limit-lines - Archive of obsolete content
in the flow above the consecutive hyphenated lines limit would be an infinitely large positive number.
-ms-scroll-snap-points-x - Archive of obsolete content
in the second selector, each snap-point is listed separately — 100%, 200%, 300%, and so on.
-ms-scroll-snap-points-y - Archive of obsolete content
in the second selector, each snap-point is listed separately — 100%, 200%, 300%, and so on.
::-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.
azimuth - Archive of obsolete content
ArchiveWebCSSazimuth
this is important in that it provides a natural way to tell several voices apart, as each can be positioned to originate at a different location on the sound stage.
Processing XML with E4X - Archive of obsolete content
it's been disabled by default for chrome in firefox 17, and completely removed in firefox 21.
VBArray.getItem - Archive of obsolete content
<head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(i, j) = k document.writeln(k) k = k + 1 next document.writeln("<br>") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function getitemtest(vbarray) { var i, j; var a = new vbarray(vbarray); for (i = 0; i <= 2; i++) { for (j =0; j <= 2; j++) { document.writeln(a.getitem(i, j)); } } } --> </script> </head> <body> <scr...
VBArray.toArray - Archive of obsolete content
<head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k document.writeln(k) k = k + 1 next document.writeln("<br>") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray) { var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- vb...
VBArray - Archive of obsolete content
<head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k document.writeln(k) k = k + 1 next document.writeln("<br />") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray){ var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- v...
Old Proxy API - Archive of obsolete content
moreover, the respective method (freeze(), seal(), or preventextension()) is immediately called on the fixed object.
StopIteration - Archive of obsolete content
the stopiteration object was used to tell the end of the iteration in the legacy iterator protocol.
background-size - Archive of obsolete content
agreed; we should definitely encourage people to look stuff up by engine rather than browser.
XForms Custom Controls - Archive of obsolete content
focus() is used by the processor to tell the control that it is getting focus through one of a variety of ways (i.e.
Troubleshooting XForms Forms - Archive of obsolete content
repeat and tables not working unfortunately you cannot do: <table> <xf:repeat nodeset="..."> <tr> ...
XForms Alert Element - Archive of obsolete content
the alert element's message can also be displayed immediately after the containing form control element in the xforms document's layout.
XForms Switch Module - Archive of obsolete content
example <switch> <case id="in" selected="true"> <input ref="yourname"> <label>please tell me your name</label> <toggle ev:event="domactivate" case="out"/> </input> </case> <case id="out" selected="false"> <html:p>hello <output ref="yourname" /> <trigger id="editbutton"> <label>edit</label> <toggle ev:event="domactivate" case="in"/> </trigger> </html:p> </case> </switch> ...
Archived open Web documentation - Archive of obsolete content
if you're using older versions of tools that rely on old browser bugs or generate browser-specific code, it may be time to upgrade: stopiteration the stopiteration object was used to tell the end of the iteration in the legacy iterator protocol.
Describing microformats in JavaScript - Archive of obsolete content
possible values are: datetime an iso date anyuri a uri email an email address tel a telephone number html html including tags float a floating-point number microformat a microformat microformat_property a specific property within the microformat specified by microformat.
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
fortunately, the behavior can be overcome in all cases with a single css2 rule.
Styling Abbreviations and Acronyms - Archive of obsolete content
the underline tells readers that the word in question has extra information associated with it.
Archive of obsolete content
creating a status bar extension many of the concepts introduced here apply to any xul-based application; however, to keep from getting completely overwhelmed, we're going to focus specifically on firefox.
Introduction to game development for the Web - Game development
webrtc the webrtc (real-time communications) api gives you the power to control audio and video data, including teleconferencing and transmitting other application data back and forth between two users.
Game monetization - Game development
remember that it can be cancelled, so it's not an indefinitely working solution.
3D collision detection - Game development
aabb checking if a point is inside an aabb is pretty simple — we just need to check whether the point's coordinates fall inside the aabb; considering each axis separately.
Building up a basic demo with Three.js - Game development
right after the function declaration, we're invoking it for the first time to start the loop, after which it will be used indefinitely.
3D games on the Web - Game development
you should definitely check out glsl shaders article to learn more about them.
Async scripts for asm.js - Game development
two common situations in which a script is *not* async (as defined by the html spec) are: <script async>code</script> and var script = document.createelement('script'); script.innerhtml = "code"; document.body.appendchild(script); both are counted as 'inline' scripts and get compiled and then run immediately.
Desktop gamepad controls - Game development
after a certain threshold is reached we can assume the input is done deliberately by the user and can act accordingly.
Desktop mouse and keyboard controls - Game development
remember: it's a secret, so don't tell anyone!
Implementing controls using the Gamepad API - Game development
it takes two parameters — the button we want to listen to and the (optional) way to tell the game that holding the button is accepted.
Crisp pixel art look with image-rendering - Game development
vas: <canvas id="game" width="128" height="128"></canvas> css to size the canvas and render a crisp image: canvas { width: 512px; height: 512px; image-rendering: -moz-crisp-edges; image-rendering: -webkit-crisp-edges; image-rendering: pixelated; image-rendering: crisp-edges; } and some javascript to set up the canvas and load the image: // get canvas context var ctx = document.getelementbyid('game').getcontext('2d'); // load image var image = new image(); image.onload = function () { // draw the image into the canvas ctx.drawimage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; this code used together produces the following result: note: you can check out the original code on github (and a live example.) ...
asm.js - Game development
asm.js code resembles c in many ways, but it's still completely valid javascript that will run in all current engines.
Collision detection - Game development
next steps we are definitely getting there now; let's move on!
Create the Canvas and draw on it - Game development
var canvas = document.getelementbyid("mycanvas"); var ctx = canvas.getcontext("2d"); here we're storing a reference to the <canvas> element to the canvas variable.
Finishing up - Game development
he same place where we declared our other variables: var lives = 3; drawing the life counter looks almost the same as drawing the score counter — add the following function to your code, below the drawscore() function: function drawlives() { ctx.font = "16px arial"; ctx.fillstyle = "#0095dd"; ctx.filltext("lives: "+lives, canvas.width-65, 20); } instead of ending the game immediately, we will decrease the number of lives until they are no longer available.
Mouse controls - Game development
the paddle will now follow the position of the mouse cursor, but since we're restricting the movement to the size of the canvas, it won't disappear completely off either side.
Paddle and keyboard controls - Game development
the ball is bouncing off the walls freely and you can watch it indefinitely, but currently there's no interactivity.
Bounce off the walls - Game development
bouncing off the world boundaries the easiest way to get our ball bouncing off the walls is to tell the framework that we want to treat the boundaries of the <canvas> element as walls and not let the ball move past them.
Move the ball - Game development
this would take several lines of code — a significantly more complex step than we have seen so far, especially if we want to add paddle and brick collisions too — but fortunately phaser allows us to do this much more easily than if we wanted to use pure javascript.
Randomizing gameplay - Game development
it's not completely random of course, but it does make the gameplay a bit more unpredictable and therefore more interesting.
2D maze game with device orientation - Game development
the good news is that the framework will take care of calculating the collision detection, we only have to specify the colliding objects in the update() function: this.physics.arcade.collide(this.ball, this.bordergroup, this.wallcollision, null, this); this.physics.arcade.collide(this.ball, this.levels[this.level-1], this.wallcollision, null, this); this will tell the framework to execute the wallcollision function when the ball hits any of the walls.
Plug-in Development Overview - Gecko Plugin API Reference
consider the following example, where a media player plug-in can be controlled with an advancetonextsong() method called inside the script element: <object id="myplugin" type="audio/wav" data="music.wav"> </object> <script type="application/javascript"> var theplugin = document.getelementbyid('myplugin'); if (theplugin && theplugin.advancetonextsong) theplugin.advancetonextsong(); else alert("plugin not installed correctly"); </script> in the past, liveconnect and later xpconnect were used to make plug-ins scriptable.
502 - MDN Web Docs Glossary: Definitions of Web-related terms
internet protocols are quite explicit, and so a 502 usually means that one or both machines were incorrectly or incompletely programmed.
Alpha (alpha channel) - MDN Web Docs Glossary: Definitions of Web-related terms
as you can see, the color without an alpha channel completely blocks the background text, while the box with the alpha channel leaves it visible through the purple background color.
Block cipher mode of operation - MDN Web Docs Glossary: Definitions of Web-related terms
using an inappropriate mode, or using a mode incorrectly, can completely undermine the security provided by the underlying cipher.
Bézier curve - MDN Web Docs Glossary: Definitions of Web-related terms
in vector images, they are used to model smooth curves that can be scaled indefinitely.
CRLF - MDN Web Docs Glossary: Definitions of Web-related terms
a cr immediately followed by a lf (crlf, \r\n, or 0x0d0a) moves the cursor down to the next line and then to the beginning of the line.
CalDAV - MDN Web Docs Glossary: Definitions of Web-related terms
caldav (calendaring extensions to webdav) is a protocol standardized by the ietf and used to remotely access calendar data from a server.
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
ultimately, the stack is empty again.
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
here is a quick example: function greeting(name) { alert('hello ' + name); } function processuserinput(callback) { var name = prompt('please enter your name.'); callback(name); } processuserinput(greeting); the above example is a synchronous callback, as it is executed immediately.
Client hints - MDN Web Docs Glossary: Definitions of Web-related terms
basically, with the client hints header, the developer or application can tell the browser to advertise information about itself to the server, such as the device pixel ratio, the viewport width, and the display width.
Code splitting - MDN Web Docs Glossary: Definitions of Web-related terms
then features required at page load can be downloaded immediately with additional scripts being lazy loaded after the page or application is interactive, thus improving performance.
Computer Programming - MDN Web Docs Glossary: Definitions of Web-related terms
these tell a computer/software program what to do in a language which the computer understands.
Endianness - MDN Web Docs Glossary: Definitions of Web-related terms
by far the most common ordering of multiple bytes in one number is the little-endian, which is used on all intel processors.
Entity header - MDN Web Docs Glossary: Definitions of Web-related terms
a few request headers after a get request: in the following example, content-length is an entity header, while host and user-agent are requests headers: post /myform.html http/1.1 host: developer.mozilla.org user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 content-length: 128 learn more technical knowledge list of all http headers ...
Fuzz testing - MDN Web Docs Glossary: Definitions of Web-related terms
fuzzing is a technique for testing software using automated tools to provide invalid or unexpected input to a program or function in a program, then checking the results to see if the program crashes or otherwise acts inappropriately.
Gonk - MDN Web Docs Glossary: Definitions of Web-related terms
since firefox os has full control over gonk, we can expose interfaces to gecko that aren't accessible on other operating systems, for example the full telephony stack and display frame buffer.
HPKP - MDN Web Docs Glossary: Definitions of Web-related terms
http public key pinning (hpkp) is a security feature that tells a web client to associate a specific cryptographic public key with a certain web server to decrease the risk of mitm attacks with forged certificates.
HSTS - MDN Web Docs Glossary: Definitions of Web-related terms
in other words, it tells the browser that changing the protocol from http to https in a url works (and is more secure) and asks the browser to do it for every request.
HTTP - MDN Web Docs Glossary: Definitions of Web-related terms
http is textual (all communication is done in plain text) and stateless (no communication is aware of previous communications).
HTTP header - MDN Web Docs Glossary: Definitions of Web-related terms
headers are case-insensitive, begins at the start of a line and are immediately followed by a ':' and a value depending of the header itself.
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
unfortunately, there are no clear rules and the way idl attributes behave in conjunction with their corresponding content attributes depends on the attribute.
JSON - MDN Web Docs Glossary: Definitions of Web-related terms
(date objects by default serialize to a string containing the date in iso format, so the information isn't completely lost.) if you need json to represent additional data types, transform values as they are serialized or before they are deserialized.
Media (Audio-visual presentation) - MDN Web Docs Glossary: Definitions of Web-related terms
the term media (more accurately, multimedia) refers to audio, video, or combined audio-visual material such as music, recorded speech, movies, tv shows, or any other form of content that is presented over a period of time.
Media - MDN Web Docs Glossary: Definitions of Web-related terms
media (audio-visual presentation) the term media (more accurately, multimedia) refers to audio, video, or combined audio-visual material such as music, recorded speech, movies, tv shows, or any other form of content that is presented over a period of time.
MitM - MDN Web Docs Glossary: Definitions of Web-related terms
learn more owasp article: man-in-the-middle attack wikipedia: man-in-the-middle attack the public-key-pins header (hpkp) can significantly decrease the risk of mitm by instructing browsers to require a whitelisted certificate for all subsequent connections to that website.
Modem - MDN Web Docs Glossary: Definitions of Web-related terms
different kinds are used for different networks: dsl modems for telephone wires, wifi modems for short-range wireless radio signals, 3g modems for cellular data towers, and so on.
Mozilla Firefox - MDN Web Docs Glossary: Definitions of Web-related terms
first released in november 2004, firefox is completely customizable with themes, plug-ins, and add-ons.
NaN - MDN Web Docs Glossary: Definitions of Web-related terms
fortunately, since the result will be nan and i know my divisor may turn out to be 0, i can set up testing conditions that prevent any such computations in the first place or notify me of where they happen.
Packet - MDN Web Docs Glossary: Definitions of Web-related terms
over time the number packets can cause traversing within closed circuits, the number of pa ckets circulating would build up and then ultimately lead to the networking in failing.
Page prediction - MDN Web Docs Glossary: Definitions of Web-related terms
page prediction is a browser feature or script which, when enabled, tells the browser to download resources the user is likely to visit before the user requests the content.
Quality values - MDN Web Docs Glossary: Definitions of Web-related terms
the importance of a value is marked by the suffix ';q=' immediately followed by a value between 0 and 1 included, with up to three decimal digits, the highest value denoting the highest priority.
RAIL - MDN Web Docs Glossary: Definitions of Web-related terms
in acronym order, the main tenets are: response respond to users immediately, acknowledging any user input in 100ms or less.
RTP (Real-time Transport Protocol) and SRTP (Secure RTP) - MDN Web Docs Glossary: Definitions of Web-related terms
rtp is suitable for video-streaming application, telephony over ip like skype and conference technologies.
RTSP: Real-time streaming protocol - MDN Web Docs Glossary: Definitions of Web-related terms
if your computer were a remote control and the streaming server a television, rtsp would describe how the instruction of the remote control affects the tv.
SCTP - MDN Web Docs Glossary: Definitions of Web-related terms
it's used for sending traditional telephone calls over the internet, but is also used for webrtc data.
SVG - MDN Web Docs Glossary: Definitions of Web-related terms
as a vector image format, svg graphics can scale infinitely, making them invaluable in responsive design, since you can create interface elements and graphics that scale to any screen size.
Self-Executing Anonymous Function - MDN Web Docs Glossary: Definitions of Web-related terms
also known as an iife (immediately invoked function expression).
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
would you need to look at the code to understand what the function did if it was called build('peach'), or createliwithcontent('peach')?
Symmetric-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
using an inappropriate mode, or using a mode incorrectly, can completely undermine the security provided by the underlying cipher.
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
a human example is the telephone — during a telephone call you tend to respond to another person immediately.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
lately, the trend is to add experimental features behind user-controlled flags or preferences, and to create smaller specifications which can reach a stable state much more quickly.
WebDAV - MDN Web Docs Glossary: Definitions of Web-related terms
webdav (web distributed authoring and versioning) is an http extension that lets web developers update their content remotely from a client.
caret - MDN Web Docs Glossary: Definitions of Web-related terms
<input type="text"> <input type="password"> <input type="search"> <input type="date">, <input type="time">, <input type="datetime">, and <input type="datetime-local"> <input type="number">, <input type="range"> <input type="email">, <input type="tel">, and <input type="url"> <textarea> any element with its contenteditable attribute set ...
jQuery - MDN Web Docs Glossary: Definitions of Web-related terms
$(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 official website technical information offical api reference documentation ...
A cool-looking box - Learn web development
make it completely transparent at the start, gradiating to around 0.2 opacity by 30% along, and remaining at the same color until the end.
Creating fancy letterheaded paper - Learn web development
make it slightly dark right near the top and bottom, but completely transparent for a large part of the center.
Handling different text directions - Learn web development
however, ultimately we expect that people will transition to the logical versions for most things, as they make a lot of sense once you start also dealing with layout methods such as flexbox and grid.
Images, media, and form elements - Learn web development
for example, you may want to size an image so it completely covers a box.
Type, class, and ID selectors - Learn web development
we can tell the browser that we only want to match the element if it has two classes applied by chaining them together with no white space between them.
CSS selectors - Learn web development
it is a pattern of elements and other terms that tell the browser which html elements should be selected to have the css property values inside the rule applied to them.
Flexbox - Learn web development
not supporting flexbox features however will probably break a layout completely, making it unusable.
What is CSS? - Learn web development
on each property page on mdn you can see the status of the property you are interested in, so you can tell if you will be able to use it on a website.
create fancy boxes - Learn web development
<i>isaac asimov</i></blockquote> <blockquote lang="fr">l'intelligence, c'est comme les parachutes, quand on n'en a pas, on s'écrase.
Use CSS to solve common problems - Learn web development
LearnCSSHowto
how to change the box model completely using box-sizing how to control backgrounds how to control borders how to style an html table how to add shadows to boxes uncommon and advanced techniques css allows some advanced design techniques.
Styling links - Learn web development
m;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.queryselector(".html-input"); var cssinput = document.queryselector(".css-input"); var reset = document.getelementbyid("reset"); var htmlcode = htmlinput.value; var csscode = cssinput.value; var output = document.queryselector(".output"); var solution = document.getelementbyid("solution"); var styleelem = document.createelement('style'); var headelem = document.queryselector('head'); headelem.appendchild(styleelem); function drawoutput() { output.innerhtml = htmlinput.value; styleelem.textcontent =...
Styling lists - Learn web development
;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.queryselector(".html-input"); var cssinput = document.queryselector(".css-input"); var reset = document.getelementbyid("reset"); var htmlcode = htmlinput.value; var csscode = cssinput.value; var output = document.queryselector(".output"); var solution = document.getelementbyid("solution"); var styleelem = document.createelement('style'); var headelem = document.queryselector('head'); headelem.appendchild(styleelem); function drawoutput() { output.innerhtml = htmlinput.value; styleelem.textcontent =...
What text editors are available? - Learn web development
these functionalities are often helpful: search-and-replace, in one or multiple documents, based on regular expressions or other patterns as needed quickly jump to a given line view two parts of a large document separately view html as it will look in the browser select text in multiple places at once view your project's files and directories format your code automatically with code beautifier check spelling auto-indent code based on indentation settings do i want to add extra features to my text editor?
How do you host your website on Google App Engine? - Learn web development
the app.yaml file is a configuration file that tells app engine how to map urls to your static files.
How much does it cost to do something on the Web? - Learn web development
editors can be free (gimp, paint.net), moderately expensive (paintshop pro, less than $100), or several hundred dollars (adobe photoshop).
How do I start to design my website? - Learn web development
we have five goals connected to music, one goal related to personal life (finding your significant other), and the completely unrelated cat photos.
What are browser developer tools? - Learn web development
you can also click the closing curly brace of any rule to bring up a text box on a new line, where you can write a completely new declaration for your page.
How do you set up a local testing server? - Learn web development
remote files throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the html file, dragging and dropping it into the browser window, or choosing file > open...
HTML forms in legacy browsers - Learn web development
fortunately, there are a few tricks to know that can help you to solve most of the problems caused by legacy browsers.
Example - Learn web development
type:</span> </label> <select id="card" name="usercard"> <option value="visa">visa</option> <option value="mc">mastercard</option> <option value="amex">american express</option> </select> </p> <p> <label for="number"> <span>card number:</span> <strong><abbr title="required">*</abbr></strong> </label> <input type="tel" id="number" name="cardnumber"> </p> <p> <label for="date"> <span>expiration date:</span> <strong><abbr title="required">*</abbr></strong> <em>formatted as mm/dd/yyyy</em> </label> <input type="date" id="date" name="expiration"> </p> </section> <section> <p> <button type="submit">validate the payment</button> </p> </section> </form> ...
Test your skills: Advanced styling - Learn web development
can you add some kind of styling back in so that users can tell when the search box is being hovered or focused?
Web forms — Working with user data - Learn web development
form validation helps us achieve these goals — this article tells you what you need to know.
CSS basics - Learn web development
note: don't be too concerned if you don't completely understand display: block; or the differences between a block element and an inline element.
HTML basics - Learn web development
for example, try deliberately changing the path inside your src attribute to make it incorrect.
How the Web works - Learn web development
the other parts of the toolbox the client and server we've described above don't tell the whole story.
Installing basic software - Learn web development
that looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these.
Publishing your website - Learn web development
if your website does not display immediately, wait a few minutes.
The web and web standards - Learn web development
privacy refers to allowing people to go about their business privately and not spying on them or collecting more of their data than you absolutely need to.
Add a hitmap on top of an image - Learn web development
you may leave this attribute blank if you don’t want the current area to link anywhere (say, if you’re making a hollow circle.) alt a mandatory attribute, telling people where the link goes or what it does.
Creating hyperlinks - Learn web development
screen readers tell people there's a link.
Test your skills: Links - Learn web development
we'd also like you to give it a tooltip when moused over that tells the user that the page includes information on blue whales and sperm whales.
Mozilla splash page - Learn web development
unfortunately, no images or video have been added yet — this is your job!
Responsive images - Learn web development
you can supply mime types inside type attributes so the browser can immediately reject unsupported file types: <picture> <source type="image/svg+xml" srcset="pyramid.svg"> <source type="image/webp" srcset="pyramid.webp"> <img src="pyramid.png" alt="regular pyramid built from four equilateral triangles"> </picture> do not use the media attribute, unless you also need art direction.
HTML table advanced features and accessibility - Learn web development
the scope attribute a new topic for this article is the scope attribute, which can be added to the <th> element to tell screenreaders exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example?
Making asynchronous programming easier with async and await - Learn web development
so the async keyword is added to functions to tell them to return a promise rather than directly returning the value.
General asynchronous programming concepts - Learn web development
if you start task a running and then immediately try to run task b, you'll get an error, because the image won't be available yet.
Asynchronous JavaScript - Learn web development
if you are not familiar with the concept of asynchronous programming, you should definitely start with the general asynchronous programming concepts article in this module.
Image gallery - Learn web development
the html body looks like this: <h1>image gallery example</h1> <div class="full-img"> <img class="displayed-img" src="images/pic1.jpg"> <div class="overlay"></div> <button class="dark">darken</button> </div> <div class="thumb-bar"> </div> the example looks like this: the most interesting parts of the example's css file: it absolutely positions the three elements inside the full-img <div> — the <img> in which the full-sized image is displayed, an empty <div> that is sized to be the same size as the <img> and put right over the top of it (this is used to apply a darkening effect to the image via a semi-transparent background color), and a <button> that is used to control the darkening effect.
JavaScript building blocks - Learn web development
introduction to events events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired.
Handling text — strings in JavaScript - Learn web development
creating a string to start with, enter the following lines: let string = 'the revolution will not be televised.'; string; just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value.
Test your skills: Strings - Learn web development
we would like you to: retrieve the length of the quote, and store it in a variable called quotelength.
Storing the information you need — Variables - Learn web development
declaring a variable to use a variable, you've first got to create it — more accurately, we call this declaring the variable.
JavaScript First Steps - Learn web development
a first splash into javascript now you've learned something about the theory of javascript, and what you can do with it, we are going to give you a crash course in the basic features of javascript via a completely practical tutorial.
Solve common problems in your JavaScript code - Learn web development
some common built-in browser functions that cause problems are: correct wrong getelementsbytagname() getelementbytagname() getelementsbyname() getelementbyname() getelementsbyclassname() getelementbyclassname() getelementbyid() getelementsbyid() semi-colon position you need to make sure you don't place any semi-colons incorrectly.
JavaScript object basics - Learn web development
imply declaring the member you want to set (using dot or bracket notation), like this: person.age = 45; person['name']['last'] = 'cratchit'; try entering the above lines, and then getting the members again to see how they've changed, like so: person.age person['name']['last'] setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members.
Object prototypes - Learn web development
these all have a number of members defined on their prototype, which is why for example when you create a string, like this: let mystring = 'this is my string.'; mystring immediately has a number of useful methods available on it, like split(), indexof(), replace(), etc.
Measuring performance - Learn web development
next up, you'll look at perceived performance and some techniques to make unavoidable performance hits appear less severe to the user, or disguise them completely.
Multimedia: Images - Learn web development
progressive jpegs, in contrast to normal jpegs, render progressively (hence the name), meaning the user sees a low-resolution version that gains clarity as the image downloads, rather than the image loading at full resolution top-to-bottom or even only rendering once completely downloaded.
Perceived performance - Learn web development
if you're downloading all the assets in the end, the weight of all your assets hasn't improved -- in fact, you may need to add some code -- but because the download of non-immediately necessary assets are delayed in a manner that is not perceptible the the user, the user will feel like the download was faster.
Web performance - Learn web development
the following is a suggested order for working through them; you should definitely start with the first one.
Introduction to the server side - Learn web development
creating a separate static page for each product or post would be completely impractical.
Ember resources and troubleshooting - Learn web development
more concretely, using mut allows for template-only settings functions to be declared: <checkbox @value={{this.somedata}} @ontoggle={{fn (mut this.somedata) (not this.somedata)}} /> whereas, without mut, a component class would be needed: import component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class example extends c...
Routing in Ember - Learn web development
it also tells ember how to interact with your route, such as when loading arbitrary data, handling errors while loading that data, or interpreting dynamic segments of the url.
Ember app structure and componentization - Learn web development
this is because the default css absolutely positions the checkbox + label with negative top and left values to move it next to the input, rather than it being inside the "main" section.
React interactivity: Editing, filtering, conditional rendering - Learn web development
when you press a filter button, you should see its text take on a new outline — this tells you it has been selected.
Using Vue computed properties - Learn web development
update your <to-do-item></to-do-item> call as follows: <to-do-item :label="item.label" :done="item.done" :id="item.id" @checkbox-changed="updatedonestatus(item.id)"> </to-do-item> now if you check a todoitem, you should see the summary update appropriately!
Vue conditional rendering: editing existing todos - Learn web development
fixing this is fortunately quite easy — we can do this by converting our isdone data item into a computed property — another advantage of computed properties is that they preserve reactivity, meaning (among other things) that their state is saved when the template changes like ours is now doing.
Getting started with Vue - Learn web development
these components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required.
Adding a new todo form: Vue events, methods, and models - Learn web development
our app is now starting to feel interactive, but one issue is that we've completely ignored its look and feel up to now.
Understanding client-side JavaScript frameworks - Learn web development
react interactivity: events and state with our component plan worked out, it's now time to start updating our app from a completely static ui to one that actually allows us to interact and change things.
Git and GitHub - Learn web development
overview vcses are essential for software development: it is rare that you will work on a project completely on your own, and as soon as you start working with other people you start to run the risk of conflicting with each other's work — this is when both of you try to update the same piece of code at the same time.
Deploying our app - Learn web development
the test also exited with a special signal that tells the command line that it was successful — an exit signal of 0.
Chrome Worker Modules
stack traces unfortunately, the module loader doesn’t play nicely with error stack traces.
Accessibility/LiveRegionDevGuide
in this case, 'main' channel messages are queued according to the 'live' property and 'alert' channel messages bypass the queue and are output immediately.
Mozilla accessibility architecture
unfortunately, we still are not fully working with any major screen reader, screen magnifier or voice dictation product on the market.
CSUN Firefox Materials
this extension is useful for making ie specific sites, or site that read better in ie, open directly in firefox, while using the internet explorer engine tab mix plus completely enhances firefox's tab browsing capabilities.
Links and Resources
this tool will measure accurately the degree of legibility of a webpage.
Frequently Asked Questions for Lightweight themes
absolutely!
Theme concepts
you could combine the two, but it’s easier to treat them separately.
Benchmarking
some example tools include instruments on osx (part of xcode), rotateright zoom on linux (uses perf underneath), and intel vtune on windows or linux.
Bugzilla
how to tell if a bug has already been reported it's useful (but not mandatory) for you to check if the problem you're reporting has been already tracked.
Chrome registration
typically a contract id will be paired with a component entry immediately preceding.
Creating JavaScript callbacks in components
the function attribute tells the xpconnect machinery to treat the javascript function as if it was an implementation of the callback interface.
Creating a Firefox sidebar
such kind of sidebar can be a simple web panel or a full-featured extension that is completely integrated with the browser.
Debugging Chrome
unfortunately, it requires using --single-process which crashes on startup for me.
Debugging on Mac OS X
that are added may not be immediately available.
Debugging on Windows
unfortunately, it's hard to know which symbols to download without having vs hang and seeing the "downloading symbols for <library>" status at the bottom left of the main window.
Debugging
fortunately, over the years, mozilla developers have come up with not just technologies and features to help you debug code, but have devised tips and techniques that can help too.
Installing headers using EXPORTS
this is accomplished by setting make variables telling the build system which module the headers are for (since headers are organized by module under <tt>dist/include</tt>), and which headers need to be created from idl files by xpidl.
Simple Instantbird build
this means deleting the object directory so that your next build is completely fresh.
Simple Thunderbird build
if it is in your `mozconfig` file, you should go ahead and remove it when building thunderbird 74 or later, since support for it will eventually be removed completely.
Updating NSPR or NSS in mozilla-central
(because some developers might not be aware that nspr/nss are separately maintained and released, the mozilla hg server rejects accidental changes/forking, if the required keywords are missing in the commit comment.) if nspr or nss must be upgraded to a new static tag, follow this procedure: before starting, make sure your local repository is updated to mozilla-central tip and that there are no local changes: $ hg status -mard pull the new sources $ python client.py update_ns...
Windows SDK versions
note that if you're running a 64 bit version of windows you may require the "amd" version of the sdk even if you have an intel processor, and you may need to deselect the documentation component in the installer in order to avoid an installation error.
pymake
alternately, if you would like to simply type in pymake -f client.mk from within the mingw32 shell.
The Firefox codebase: CSS Guidelines
some examples to avoid: absolutely positioned elements hardcoded values such as: vertical-align: -2px; .
ESLint
my script is a frame-script, or includes items that loaded into content scripts: add a line to tell eslint to use the frame-script environment: /* eslint-env mozilla/frame-script */ my script is a worker: add a line to tell eslint to use the worker environment: /* eslint-env worker */ or, to use a chrome worker environment: /* eslint-env mozilla/chrome-worker */ my file uses chrome/xbl specific globals either, ...
Eclipse CDT Manual Setup
unfortunately, the build option discovery process outlined above does not pick up this information, so cdt needs to be told separately about c++11 mode.
Gecko Logging
sync print each log synchronously, this is useful to check behavior in real time or get logs immediately before crash.
Commenting IDL for better documentation
*/ [noscript] void sayyummy(in astring language); }; in conclusion with just a little extra help from you, the intrepid developer, the documentation team can crank out full, formatted documentation for your interface much more quickly and accurately.
Experimental features in Firefox
nightly 73 no developer edition 73 no beta 73 no release 73 no preference name dom.webgpu.enabled html dom api global event: beforeinput the global beforeinput event is sent to an <input> element—or any element whose contenteditable attribute is enabled—immediately before the element's value changes.
Frame script environment
in particular, note that a frame script accesses the dom window using content, not window: // frame script var links = content.document.getelementsbytagname("a"); all the frame scripts running in a tab share this global.
Limitations of chrome scripts
however, this "dummy" object is completely static and only exposes a few of the normal properties that windows and documents have.
Limitations of frame scripts
examples of apis add-on authors should avoid in frame scripts: nsifileinputstream nsifileoutputstream constructing a file from a string or nsifile (but file objects can be sent via message manager) htmlinputelement.mozsetfilenamearray (alternative: mozsetfilearray) xul and browser ui anything that tries to touch the browser ui or anything to do with xul is likely to not work in the content process.
Communicating with frame scripts
where absolutely necessary, frame scripts can pass wrappers called cross process object wrappers (also known as cpows) to chrome, and chrome can use these wrappers to get synchronous access to content objects.
Frame script environment
in particular, note that a frame script accesses the dom window using content, not window: // frame script var links = content.document.getelementsbytagname("a"); all of the frame scripts running in a tab share this global.
Frame script loading and lifetime
you need to send a message to your frame scripts, telling them to disable themselves; for example, by undoing any changes they've made or removing any event listeners.
Process scripts
for example, if you call the global frame message manager's loadframescript() function, then the script will be loaded separately into all open tabs.
Storage access policy: Block cookies from trackers
when storage access is granted to tracker.example on example.com, all resources loaded from tracker.example on any top-level document loaded from example.com are immediately given storage access.
Firefox and the "about" protocol
(question mark) > troubleshooting information) about:sync-log displays a synchronization protocol related to the sync feature about:telemetry displays telemetry data collected and sent to mozilla while firefox is running (in case the user enabled telemetry) about:url-classifier displays the status of the url classifier services that firefox uses (for example for safe browsing) about:webrtc information about webrtc usage about:welcome page first displayed when firefox is installed ab...
MozBeforePaint
<!doctype html> <html> <body> <div id="d" style="width:100px; height:100px; background:lime; position:relative;"></div> <script> var d = document.getelementbyid("d"); var start = window.mozanimationstarttime; function step(event) { var progress = event.timestamp - start; d.style.left = math.min(progress/10, 200) + "px"; if (progress < 2000) { window.mozrequestanimationframe(); } else { window.removeeventlistener("mozbeforepaint", step, false); } } window.addeventlistener("mozbeforepaint", step, false); window.mozrequestanimatio...
Embedding the editor
calling window.trytoclose) appropriately consult each editor for state.
Gecko Keypress Event
in the unfortunately situation where xul applications attempt to implement their own shortcut key handling, the decentralized implementation may need to be rewritten every time any of the above process is changed.
How to add a build-time test
in <tt>yourmoduledir/tests_type/makefile.in</tt> change depth, module, and xpcshell_tests appropriately: depth should be a relative path pointing to <tt>mozilla/</tt>, e.g.
How to get a stacktrace with WinDbg
q: windbg tells me that it is unable to verify checksum for firefox.exe.
IPDL Best Practices
the main concern you have now is that you absolutely, certainly, positively call send__delete__ in all possible circumstances or your protocol can and will leak.
Implementing QueryInterface
it tests for bad input with an ns_assertion, to find logic errors immediately in debug builds.
Introduction to Layout in Mozilla
(tables, blocks, xul boxes) reflow “global” reflows initial, resize, style-change processed immediately via presshell method incremental reflows targeted at a specific frame dirty, content-changed, style-changed, user-defined nshtmlreflowcommand object encapsulates info queued and processed asynchronously, nsipressshell::appendreflowcommand, processreflowcommands incremental reflow recursively descend to target recovering reflow state child ...
JavaScript-DOM Prototypes in Mozilla
here are a few of the properties of obj's prototype: obj.__proto__ parentnode (getter function) src (getter and setter functions) getelementsbytagname (function) text_node (number property, constant) ...
Add-on Repository
a new search will immediately fail if the addonrepository is already handling another search request.
CustomizableUI.jsm
this can only be called immediately after reset().
Dict.jsm
methods copy() returns a shallow copy of the dictionary; that is, a copy of the dictionary including the items immediately included within the dictionary; however, any objects referenced by those top-level objects are not copied.
PerfMeasurement.jsm
number of available event types the num_measurable_events constant tells you how many types of events can be measured.
PromiseWorker.jsm
the following sections tell you which content to use in your worker and main thread files, in order to use promiseworker objects.
Services.jsm
uritymanager nsiscriptsecuritymanager script security manager search nsibrowsersearchservice browser search service startup nsiappstartup application startup service storage mozistorageservice storage api service strings nsistringbundleservice string bundle service sysinfo nsipropertybag2 system info service telemetry nsitelemetry telemetry service tm nsithreadmanager thread manager service urifixup nsiurifixup uri fixup service urlformatter nsiurlformatter url formatter service vc nsiversioncomparator version comparator service wm nsiwindowmediator window mediator service ww nsiwindowwatcher window watcher se...
SourceMap.jsm
is immediately passed to sourcenode.prototype.add, see below.
Task.jsm
function async( atask ); async() is similar to spawn(), except that: it doesn't immediately start the task, rather it returns an "async function" that starts the task when the function is called; it binds the task to the async function's this object and arguments; it requires the task to be a function.
Using JavaScript code modules
firefox 3.6 doesn't support them at all, and there's only one case in which it's remotely useful: a firefox 4-only add-on which must be installed unpacked.
Using workers in JavaScript code modules
to create a chromeworker for this purpose, you need to use the nsiworkerfactory interface: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); var worker = workerfactory.newchromeworker('script_url.js'); this will create a new chrome worker that will immediately begin to run the script at the specified url (in this case, "script_url.js").
WebRequest.jsm
this tells the browser to wait for your event listener to return before continuing with the request.
Bootstrapping a new locale
with that level of authority, you will be able to push and pull and manage the repository remotely.
Localization and Plurals
of files # example: 111 files - downloads downloadstitlefiles=#1 file - downloads;#1 files - downloads # localization note (timepair): #1 time number; #2 time unit # example: 1 second; 11 seconds timepair=#1 #2 seconds=second;seconds minutes=minute;minutes hours=hour;hours downloads.js: components.utils.import("resource://gre/modules/pluralform.jsm"); let getstr = function(string) document.getelementbyid("strings").getstring(string); // get the correct plural form for the title let numdownloads = 3; let title = pluralform.get(numdownloads, getstr("downloadstitlefiles")); // put in the correct number of downloads print(title.replace("#1", numdownloads)); // get the correct plural form of seconds let timeleft = 55; let seconds = pluralform.get(timeleft, getstr("seconds")); // print the l...
Localizing with Mercurial
la-hosted repositories, you have to have committer access, and you must edit the file (your-local-hg-root aka the directory you pulled your locale into)/.hg/hgrc (note, this is not your ~/.hgrc) to add these lines (replacing ab-cd with your locale code): [paths] default = https://hg.mozilla.org/l10n-central/ab-cd/ default-push = ssh://hg.mozilla.org/l10n-central/ab-cd/ you’ll also need to tell ssh which account to use for your pushes, too, by editing ~/.ssh/config and adding these lines, where user@host.domain is your account: host hg.mozilla.org user user@host.domain now you can push your work to the repository (and check the result on the dashboard) by entering this command from your local directory: hg push and tah dah!
Localizing with Mozilla Translator
if you have opted for the first solution, you will find yourself with some new products completely untranslated (once you update each of them).
Initial setup
unfortunately, other varieties of make won't do.
QA phase
you can either: create a langpack, which is installed on top of your mozilla application, or repack the application's binary (aka, a l10n repack), which allows you to install next to your existing mozilla application installation and use separately.
Translation phase
the thunderbird® email client includes intelligent spam filters, powerful search and customizable views.
Writing localizable code
this page tells you about best practices and guidelines when dealing with ui code with respect to localization.
gettext
for example, --keyword=n___:1,2,4c tells xgettext to look for n___() calls, and extract the first argument as the singular string, the second argument as the plural string and the fourth argument as the context (the third argument is reserved for the number in this example).
Extras
>n</mi> <mo>!</mo> </mrow> </mfrac> </mrow> </math> </foreignobject> <text>exp(α)</text> </switch> </g> </g> </svg> </div> inline javascript html content <math display="block"> <mfrac> <mtext id="num">mouse</mtext> <mtext id="denum">over</mtext> </mfrac> </math> javascript content function whoistherealert(evt) { alert("who is there?"); } function attachlistener(id) { document.getelementbyid(id).addeventlistener("mouseover", whoistherealert); } function init() { attachlistener("num"); attachlistener("denum"); } window.addeventlistener("load", init); ...
Fonts for Mozilla 2.0's MathML engine
if no appropriate font is ultimately found for a given character, mozilla will instead display a box containing the hexadecimal representation of the unicode code point for the character.
MathML Torture Test
{ font-family: stix two math; } .texgyrebonum math { font-family: tex gyre bonum math; } .texgyrepagella math { font-family: tex gyre pagella math; } .texgyreschola math { font-family: tex gyre schola math; } .texgyretermes math { font-family: tex gyre termes math; } .xits math { font-family: xits math; } javascript content function updatemathfont() { var mathfont = document.getelementbyid("mathfont").value; if (mathfont == "default") { document.body.removeattribute("class"); } else { document.body.setattribute("class", mathfont); } } function load() { document.getelementbyid("mathfont").
MathML In Action
n> <mi>a</mi> </mrow> </mfrac> </mrow> </mstyle> </math> </p> javascript content function zoomtoggle() { if (this.hasattribute("mathsize")) { this.removeattribute("mathsize"); } else { this.setattribute("mathsize", "200%"); } } function load() { document.getelementbyid("zoomablemath").
MathML Demo: <mtable> - tables and matrices
as a visual aid, the examples deliberately draw attention to the math axis and the baseline: ----------------------- this is the math axis .....................
Mozilla Port Blocking
ports user_pref("network.security.ports.banned", "port3,port4"); blocked ports ports blocked by default in mozilla: port service 1 tcpmux 7 echo 9 discard 11 systat 13 daytime 15 netstat 17 qotd 19 chargen 20 ftp data 21 ftp control 22 ssh 23 telnet 25 smtp 37 time 42 name 43 nicname 53 domain 77 priv-rjs 79 finger 87 ttylink 95 supdup 101 hostriame 102 iso-tsap 103 gppitnp 104 acr-nema 109 pop2 110 pop3 111 sunrpc 113 auth 115 ...
Mozilla Web Services Security Model
mozilla allows sites hosting such web services to tell mozilla that other sites can access the service.
Mozilla Development Tools
it is how we are able to tell when a checkin has broken the build on some platform, and how we know which person needs to be viciously flogged.
Mozilla projects on GitHub
dxr an intelligent tool for browsing source code.
mozilla::MutexAutoLock
this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply.
mozilla::MutexAutoUnlock
this is because mutexautounlocks can be nested within mutexautolocks and vice versa, indefinitely deeply.
GC and CC logs
to get cycle collector logs on try server, set moz_cc_log_directory to moz_upload_dir, then set the other variables appropriately to generate cc logs.
Gecko Profiler FAQ
nothing stands out in the profile, how can i accurately find the next bottleneck?
JS::PerfMeasurement
ults .major_page_faults page faults that required disk access ::context_switches .context_switches context switches involving the profiled thread ::cpu_migrations .cpu_migrations migrations of the profiled thread from one cpu core to another these events map directly to "generic events" in the linux 2.6.31+ <linux/perf_event.h> interface, and so unfortunately are a little vague in their specification; for instance, we can't tell you exactly which level of cache you get misses for if you measure cache_misses.
Leak-hunting strategies and tips
because (1) large graphs of leaked objects tend to include some objects pointed to by global variables that confuse gc-based leak detectors, which can make leaks look smaller (as in bug 99180) or hide them completely and (2) large graphs of leaked objects tend to hide smaller ones, it's much better to go after the large graphs of leaks first.
Measuring performance using the PerfMeasurement.jsm code module
since we enable monitoring immediately before calling code_to_be_benchmarked(), and disable it as soon as it returns, the code in set_up_some_state() and clean_up_afterward() is not measured.
Profiling with Xperf
"-stackwalk profile" tells xperf to capture a stack for each profile event; you could also do "-stackwalk profile+file_io" to capture a stack on each cpu profile tick and each file io completion event.
Profiling with the Firefox Profiler
here, i'm hovering over the last layer in the layer tree (a paintedlayercomposite), and a strip at the top of the right panel is highlighted, telling me that this layer is for the system notification bar in b2g.
Profiling with the Gecko Profiler and Local Symbols on Windows
unfortunately, 32 bit is still the default when building firefox locally.
TimerFirings logging
first, on mac the code uses dladdr to get the name immediately, and the output will look like the following.
perf
energy estimates perf can access the intel rapl energy estimates.
turbostat
the various "watt" measurements come from the intel rapl msrs.
A brief guide to Mozilla preferences
preference changes via user interface usually take effect immediately.
javascript.options.strict
var name2= "peter"; document.getelementbyid("sample").innerhtml = name1; </script> </body> </html> possible values and their effects: true: show javascript errors and warnings.
Preferences system
using this system it is possible to create preferences windows that display and operate appropriately on various platforms (windows, macos x and gnome).
Profile Manager
system requirements: mac: an intel processor, i386 or x86_64 linux: any version capable of running firefox 4.0 windows: xp or later source code you can download the source as well: hg clone http://hg.mozilla.org/automation/profilemanager/ instructions for building can be found in build.txt.
Crash reporting
see also understanding crash reports a guide to searching crash reports crash-stats crash pings (telemetry) and crash reports (socorro/crash stats) building firefox with debug symbols environment variables affecting crash reporting in-code documentation crash reporter crash manager crash ping ...
Emscripten
emscripten makes native code immediately available on the web: a platform that is standards-based, has numerous independent compatible implementations, and runs everywhere from pcs to ipads.
Installing JSHydra
by default, the configure script will obtain a known working copy of spidermonkey; it is possible via the --moz-src and --moz-obj configure arguments to tell jshydra to use existing copies of the source and build.
Midas editor module security preferences
this functionality is completely removed since 2013-12-14 18:23 pst, see: bugs 38966 and 913734 note: if you've reached this page from a message box in firefox or another mozilla product, try using keyboard shortcuts for the cut, copy, and paste commands: copy: ctrl+c or ctrl+insert (command+c on mac) paste: ctrl+v or shift+insert (command+v on mac) cut: ctrl+x or shift+delete (command+x on mac) the information on the rest of this page is for web developers and advanced users.
Midas
createlink a uri.
Nonblocking IO In NSPR
an io function on a nonblocking file descriptor either succeeds immediately or fails immediately with <tt>pr_would_block_error</tt>.
Programs Using NSPR
netscape alumni took nspr with them to their new companies: good technology, kontiki, tellme networks.
Interval Timing
nspr defines a platform-dependent type, printervaltime, for timing intervals of fewer than approximately 6 hours.
PL_HashTableLookup
this means that one cannot tell whether a null return value means the entry does not exist or the value of the entry is null.
PR_AcceptRead
pr_acceptread blocks indefinitely until the connection is accepted; the read will time out after the timeout interval elapses.
PR_CallOnce
from that time on, the client should consider the object read-only (or even opaque) and allow the runtime to manipulate its content appropriately.
PR_Cleanup
when the primordial thread returns from main, the process immediately and silently exits.
PR EnumerateAddrInfo
description pr_enumerateaddrinfo is a stateless enumerator.
PR_EnumerateHostEnt
description pr_enumeratehostent is a stateless enumerator.
PR_Interrupt
unfortunately the standard input, output, and error streams are treated as files by nspr, so a pr_read call on pr_stdin cannot be interrupted even though it may block indefinitely.
PR_TransmitFile
pr_transmitfile_close_socket indicates that the connection should be closed immediately after successful transfer of the file.
PR_WaitCondVar
the value pr_interval_no_wait causes the thread to release the lock, possibly causing a rescheduling within the runtime, then immediately attempt to reacquire the lock and resume.
NSS CERTVerify Log
the log tells you what the problem was with the chain and what certificate in the chain failed.
Certificate functions
mxr 3.2 and later cert_decodeprivkeyusageperiodextension mxr 3.10 and later cert_decodetruststring mxr 3.4 and later cert_decodeusernotice mxr 3.2 and later cert_dernametoascii mxr 3.4 and later cert_destroycertarray mxr 3.2 and later cert_destroycertificate mxr 3.2 and later cert_destroycertificatelist mxr 3.2 and later cert_destroycertificatepoliciesextension mxr 3.2 and later cert_destroycertificaterequest mxr 3.2 and later cert_destroycertlist mxr 3.2 and later cert_destroyname mxr 3.2 and later cert_destroyocspcertid mxr 3.6 and later cert_destroyocsprequest mxr 3.6 and later cert_des...
Cryptography functions
indslotbyname mxr 3.2 and later pk11_findslotsbynames mxr 3.9 and later pk11_fortezzahaskea mxr 3.2 and later pk11_fortezzamapsig mxr 3.2 and later pk11_freeslot mxr 3.2 and later pk11_freeslotlist mxr 3.2 and later pk11_freeslotlistelement mxr 3.11 and later pk11_freesymkey mxr 3.2 and later pk11_generatefortezzaiv mxr 3.2 and later pk11_generatekeypair mxr 3.2 and later pk11_generatekeypairwithflags mxr 3.10.2 and later pk11_generatekeypairwithopflags mxr 3.12 and later ...
NSS FAQ
MozillaProjectsNSSFAQ
nss source code and binaries (when they become available) are completely free.
Getting Started With NSS
(unfortunately the nss project doesn't have a technical writer at this time, so our documentation is not as organized as we would like it to be.
NSS Key Log Format
you can tell wireshark where to find the key file via edit→preferences→protocols→ssl→(pre)-master-secret log filename.
NSS Memory allocation
this makes it difficult to tell arenas that are truly leaked from those that are merely in the free list.
NSS_3.12.1_release_notes.html
place pkix_pl_memcpy with memcpy bug 433177: fix the gcc compiler warnings in lib/util and lib/freebl bug 433437: vfychain ignores the -a option bug 433594: crash destroying ocsp cert id [[@ cert_destroyocspcertid ] bug 434099: nss relies on unchecked pkcs#11 object attribute values bug 434187: fix the gcc compiler warnings in nss/lib bug 434398: libpkix cannot find issuer cert immediately after checking it with ocsp bug 434808: certutil -b deadlock when importing two or more roots bug 434860: coverity 1150 - dead code in ocsp_createcertid bug 436428: remove unneeded assert from sec_pkcs7encryptlength bug 436430: make nss public headers compilable with no_nspr_10_support defined bug 436577: uninitialized variable in sec_pkcs5createalgorithmid bug 438685: libpkix doesn'...
NSS_3.12.2_release_notes.html
bug 459248: support intel aes extensions.
NSS 3.12.9 release notes
bug 536485: crash during ssl handshake in [@ intel_aes_decrypt_cbc_256] bug 444367: nss 3.12 softoken returns the certificate type of a certificate object as ckc_x_509_attr_cert.
NSS 3.14.4 release notes
users are encouraged to upgrade immediately.
NSS 3.14.5 release notes
users are encouraged to upgrade immediately.
NSS 3.14 release notes
pkcs #11 pkcs #11 mechanisms: ckm_aes_cts ckm_aes_ctr ckm_aes_gcm (see warnings against using c_encryptupdate/c_decryptupdate above) ckm_sha224_key_derivation ckm_sha256_key_derivation ckm_sha384_key_derivation ckm_sha512_key_derivation changes in nss 3.14 bug 333601 - performance enhancements for intel macs when building for intel macs, nss will now take advantage of optimized assembly code for common operations.
NSS 3.15.2 release notes
users are encouraged to upgrade immediately.
NSS 3.15.3.1 release notes
users are encouraged to upgrade immediately.
NSS 3.15.3 release notes
users are encouraged to upgrade immediately.
NSS 3.15.4 release notes
users are encouraged to upgrade immediately.
NSS 3.16.2 release notes
new intel aes assembly code for 32-bit and 64-bit windows, contributed by shay gueron and vlad krasnov of intel.
NSS 3.19.1 release notes
notable changes in nss 3.19.1 nss reports the bit length of keys more accurately.
NSS 3.19.2.1 release notes
users are encouraged to upgrade immediately.
NSS 3.19.4 release notes
users are encouraged to upgrade immediately.
NSS 3.20.1 release notes
users are encouraged to upgrade immediately.
NSS 3.27.1 release notes
nss 3.27.1 once again requires nss_enable_tls_1_3 to be deliberately set to enable tls 1.3 (draft).
NSS 3.44.1 release notes
new in nss 3.44.1 new functionality 1546229 - add ipsec ike support to softoken many new fips test cases (note: this has increased the source archive by approximately 50 megabytes for this release.) bugs fixed in nss 3.44.1 1554336 - optimize away unneeded loop in mpi.c 1515342 - more thorough input checking (cve-2019-11729) 1540541 - don't unnecessarily strip leading 0's from key material during pkcs11 import (cve-2019-11719) 1515236 - add a sslkeylogfile enable/disable flag at build.sh 1473806 - fix seckey_converttopublicke...
NSS 3.46 release notes
removed: bug 1574670 - remove expired class 2 primary root certificate sha-256 fingerprint: 0f993c8aef97baaf5687140ed59ad1821bb4afacf0aa9a58b5d57a338a3afbcb bug 1574670 - remove expired utn-userfirst-client root certificate sha-256 fingerprint: 43f257412d440d627476974f877da8f1fc2444565a367ae60eddc27a412531ae bug 1574670 - remove expired deutsche telekom root ca 2 root certificate sha-256 fingerprint: b6191a50d0c3977f7da99bcdaac86a227daeb9679ec70ba3b0c9d92271c170d3 bug 1566569 - remove swisscom root ca 2 root certificate sha-256 fingerprint: f09b122c7114f4a09bd4ea4f4a99d558b46e4c25cd81140d29c05613914c3841 upcoming changes to default tls configuration the next nss team plans to make two changes ...
NSS 3.50 release notes
note that intel processors with sse4 but without avx are currently unable to use the improved chacha20/poly1305 due to a build issue; such platforms will fall-back to less optimized algorithms.
NSS 3.53 release notes
algorithms marked as deprecated will ultimately be removed.
NSS 3.56 release notes
bug 1654142 - add cpu feature detection for intel sha extension.
NSS Sample Code sample3
printdigest(unsigned char *digest, unsigned int len) { int i; cout << "length: " << len << endl; for(i = 0;i < len;i++) printf("%02x ", digest[i]); cout << endl; } /* * main */ int main(int argc, const char *argv[]) { int status = 0; pk11slotinfo *slot = 0; pk11symkey *key = 0; pk11context *context = 0; unsigned char data[80]; unsigned char digest[20]; /*is there a way to tell how large the output is?*/ unsigned int len; secstatus s; /* initialize nss * if your application code has already initialized nss, you can skip it * here.
NSS sources building testing
in other environments (for example in home networks), you could set the host and domsuf (for domain suffix) environment variables to tell the nss suite which hostname to use.
nss tech note3
it tells nss whether the cert is a ca cert, or not, and affects every other aspect of how the cert is interpreted by nss.
nss tech note6
for example, on 32-bit solaris sparc for nss 3.11, say shlibsign -v -i libsoftokn3.so shlibsign -v -i libfreebl_32int64_3.so shlibsign -v -i libfreebl_32fpu_3.soshlibsign -v -i libfreebl_32int_3.so (you need to set ld_library_path appropriately and specify the correct pathnames of the libraries.) option 1 is simpler and highly preferred.
nss tech note8
that is, the client session lifetime was not separately settable from the server session lifetime.
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
however, these are not the services nss calls to get to other pkcs #11 modules, which show up separately under cryptographic modules.
NSS PKCS11 Functions
optimizespace - allocate smaller hash tables and lock tables.when this flag is not specified, softoken will allocatelarge tables to prevent lock contention.
PKCS11 Implement
installation you can install your module in any convenient location on the user's hard disk, but you must tell the user to type the module name and location in the cryptographic modules portion of the communicator security info window.
PKCS 7 functions
3.3 and later sec_pkcs7encodeitem mxr 3.9.3 and later sec_pkcs7encoderabort mxr 3.9 and later sec_pkcs7encoderfinish mxr 3.2 and later sec_pkcs7encoderstart mxr 3.2 and later sec_pkcs7encoderupdate mxr 3.2 and later sec_pkcs7getcertificatelist mxr 3.2 and later sec_pkcs7getcontent mxr 3.2 and later sec_pkcs7getencryptionalgorithm mxr 3.2 and later sec_pkcs7getsignercommonname mxr 3.4 and later sec_pkcs7getsigneremailaddress mxr 3.4 and later sec_pkcs7getsigningtime mxr 3.4 and later ...
troubleshoot.html
the change is unfortunately rather drastic: to trick gmake, you rename the shell program.
TLS Cipher Suite Discovery
when a new version of a tls implementation is made available for use by applications, those applications may wish to immediately use the newly supported cipher suites found in the new version, without the application needing to be modified and re-released to know about these new cipher suites.
Utility functions
mxr 3.2 and later nssbase64_encodeitem mxr 3.4 and later nssbase64encoder_create mxr 3.2 and later nssbase64encoder_destroy mxr 3.2 and later nssbase64encoder_update mxr 3.2 and later nssrwlock_destroy mxr 3.2 and later nssrwlock_havewritelock mxr 3.2 and later nssrwlock_lockread mxr 3.2 and later nssrwlock_lockwrite mxr 3.2 and later nssrwlock_new mxr 3.2 and later nssrwlock_unlockread mxr 3.2 and later nssrwlock_unlockwrite mxr 3.2 and later nsssmime_versioncheck ...
NSS Tools certutil
-p phone specify a contact telephone number to include in new certificates or certificate requests.
Necko Architecture
once you have a url interface in hand (nsiurl), you have a completely parsed representation of the original url string, and you can query for the various parts of the url.
Pork Tools
then nuke the declaration // nsresult rv; // move outparam to lhs var = getter(); // detect ns_ensure_success immediately following // and change it to an equivalent ns_ensure_true ns_ensure_true(var, ns_error_failure); // case 2 var = getter(); // case 3, eliminate rv2 decl given that it's not used elsewhere var = getter(); ns_ensure_true(var, ns_error_failure) } outparamdel also support rewriting getters such that they return already_addrefed<nsifoo>.
Tutorial: Embedding Rhino
the null parameter tells initstandardobjects to create and return a scope object that we use in later calls.
Creating JavaScript tests
it is not generally even possible to tell if the speed of any particular feature is going to be important in the real world without running a real-world benchmark.
FOSS
http://javalikescript.free.fr/ - a general-purpose javascript platform that aims to provide an extensible tooling framework http://www.synchro.net/ - a telnet/ssh bulletin board system (bbs) and internet server (http/smtp/ftp) with extra internet services written in javascript (irc, imap, gopher, and many more) https://github.com/mindbit/libjssql/wiki - a library that aims to provide a generic sql api for javascript that is as similar as possible to jdbc miscellaneous serverjs, a standardization effort for the fragmented server-side jav...
GC Rooting Guide
these do not need to be wrapped in any of rooting classes, but they should be immediately used to initialize a js::rooted<t> if there is any code that could gc before the end of the containing function; a raw pointer must never be stored on the stack during a gc.
Statistics API
additionally, an incremental gc is divided into a series of slices (the division into slices is completely separate from the division into phases; neither one is a refinment of the other).
SpiderMonkey Internals
this bug doesn't affect spidermonkey, because it uses its own js_dtoa() call in jsnum.cpp to convert from double to string, but it's a bug that we'll fix later, and one you should be aware of if you intend to use a js_*printf() function with your own floating type arguments - various vendor sprintf's mishandle nan, +/-inf, and some even print normal floating values inaccurately.
Introduction to the JavaScript shell
-c, --compileonly tells the shell to compile the program but not run it.
JS::SetOutOfMemoryCallback
added in spidermonkey 38 description unlike the error reporter, which is only called if the exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called immediately at the oom site to allow the embedding to capture the current state of heap allocation before anything is freed.
JS::Value
the solution is to tell spidermonkey that you're using the object, then tell it again when you're done.
JSErrorReport
callers should set this flag for cross-origin scripts, and it will be propagated appropriately to child scripts and passed back in jserrorreports.
JSObjectOps.newObjectMap
it creates a jsobjectmap that completely controls the new object's behavior.
JS_AliasElement
see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement bug 576034 ...
JS_ConstructObject
the object should be made gc-reachable immediately.
JS_ConvertArguments
if an asterisk (*) is present in format, it tells the conversion routine to skip converting the current argument.
JS_DefineElement
see also mxr id search for js_defineelement js_defineconstdoubles js_definefunction js_definefunctions js_defineobject js_defineproperties js_defineproperty js_definepropertywithtinyid js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setelement bug 959787 - changed parameter types ...
JS_DoubleIsInt32
we should definitely fix this (bug 744965), but as apparently it "works" in practice, it's not a pressing concern now.
JS_EnterLocalRootScope
there is no need to tell the js engine about each variable that may point to such a value.
JS_ForgetLocalRoot
calling it successively on other than the most recently allocated gc-thing will tend to average the time inefficiency, and may risk o(n2) growth rate, but in any event, you shouldn't allocate too many local roots if you can root as you go (build a tree of objects from the top down, forgetting each latest-allocated gc-thing immediately upon linking it to its parent).
JS_ForwardGetPropertyTo
syntax bool js_forwardgetpropertyto(jscontext *cx, js::handleobject obj, js::handleid id, js::handleobject onbehalfof, js::mutablehandlevalue vp); bool js_forwardgetelementto(jscontext *cx, js::handleobject obj, uint32_t index, js::handleobject onbehalfof, js::mutablehandlevalue vp); name type description cx jscontext * a context.
JS_GetArrayLength
see also mxr id search for js_getarraylength js_getelement js_setarraylength ...
JS_GetFunctionId
examples the name returned by js_getfunctiondisplayid is the same as returned by js_getfunctionid if the function explicitly has a name listed in the source, or if not it is an intelligently guessed name for the function based on its context in the source.
JS_HasArrayLength
see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement bug 657298 ...
JS_HasElement
see also mxr id search for js_haselement js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_LookupElement
see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_newarrayobject js_setarraylength js_setelement bug 1094176 ...
JS_LookupProperty
there is no way to tell the difference between not finding any property and finding a property whose value is undefined.
JS_NewArrayObject
the new array has the specified length, but it doesn't have any elements.) it is often better to call js_newarrayobject(cx, 0, null), store the returned object in a gc root, and then populate its elements with js_setelement or js_defineelement.
JS_NewExternalString
(ultimately, the string will be garbage collected, and the javascript engine will call the string finalizer callback, allowing the application to free the array.) the array does not need to be zero-terminated.
JS_NewScriptObject
once you have created a script, you should immediately ensure that its script object is reachable (perhaps by using js_addroot or js_enterlocalrootscope).
JS_SetArrayLength
see also mxr id search for js_setarraylength js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setelement ...
JS_SetNativeStackQuota
this function may only be called immediately after the runtime is initialized and before any code is executed and/or interrupts requested.
JS_SetScriptStackQuota
either immediately after js_newcontext or from the jscontext_new context callback.
JS_THREADSAFE
we have now completely removed that feature.
Property attributes
it tells the engine to skip the resolve hook when performing the lookup at the beginning of property definition.
Profiling SpiderMonkey
we're working to add support for other profilers, such as oprofile, intel vtune, and callgrind.
Running Automated JavaScript Tests
there are two test suites, affectionately called "jstests" and "jit-tests".
Running Parsemark
a typical run can be done like so: cd js/src/tests python parsemark.py /path/to/baseline/js /path/to/parse-tests-dir/ -q > /tmp/baseline.json python parsemark.py /path/to/current/js /path/to/parse-tests-dir/ -q > /tmp/current.json python compare_bench.py /tmp/current.json /tmp/baseline.json note: unfortunately the comparisons done are very noisy and not reliable!
Setting up CDT to work on SpiderMonkey
unfortunately, there are also large parts that are not properly indexed, leading to errors and warnings being shown for perfectly valid code, but i find that the parts that do work do so nicely enough to make it totally worth it.
Shell global objects
functions available only if spidermonkey_promise is defined settlepromisenow(promise) 'settle' a promise immediately.
TPS Bookmark Lists
within each folder, the second item in the list is assumed to be immediately after the first item, and so forth.
TPS Tests
they tell tps what to do.
Thread Sanitizer
the default way of symbolizing the traces is much slower than using llvm-symbolizer for that purpose: llvm ships with a symbolizer binary that tsan will readily use to immediately output symbolized traces much faster.
WebReplayRoadmap
this requires scanning the recording and the console will not update immediately.
Zest usecase: Reporting Security Vulnerabilities to Developers
unfortunately in many cases developers may lack the security knowledge to understand or reproduce the problem.
Zest
it is completely free, open source and can be included in any tool whether open or closed, free or commercial.
compare-locales
oid/locales/l10n.toml ./l10n/ zh-tw to check mail, suite, calendar that lives on comm-central, you can either rely on the check-out of mozilla within comm-central repository that the regular comm-central build instructions generate: $ compare-locales ./comm-central/mail/locales/l10n.toml ./l10n/ zh-tw if you don't want to use a copy of mozilla-central in comm-central, you can run them separately: $ compare-locales -dmozilla=$pwd/mozilla-central comm-central/mail/locales/l10n.toml ./l10n/ zh-tw if you're working on multiple projects in parallel, you can also pass all the toml files to compare-locales at once.
Mozilla Projects
it is completely free, open source and can be included in any tool whether open or closed, free or commercial.
Using RAII classes in Mozilla
this involves just one addition to the class, and the inclusion of attributes.h: class moz_raii nsautoscriptblocker {...} this is much simpler and more thorough than the guardobject runtime assertions, but are unfortunately currently only run on mac os x and linux builds, which means that guardobject should still be used for raii guards which may be used in windows-only code.
Exploitable crashes
a crash report from your debugger, your os, or mozilla crash-stats can tell you a lot about whether or not a crash is potentially exploitable.
Handling Mozilla Security Bugs
to establish, for each bug, the amount of information a distributor can reveal immediately (before a fix is available) without putting other distributors and their customers at risk.
Setting up an update server
then run these commands, substituting <obj dir>, <mar output path>, <version> and <channel> appropriately: ./mach package touch "<obj dir>/dist/firefox/precomplete" mar="<obj dir>/dist/host/bin/mar.exe" moz_product_version=<version> mar_channel_id=<channel> ./tools/update-packaging/make_full_update.sh <mar output path> "<obj dir>/dist/firefox" for a local build, <channel> can be default, and <version> can be the value from browser/config/version.txt (or something arbitrarily large like 2000.0a1).
AT APIs Support
keyboard user interface and api fortunately, gecko uses the standard keyboard api's for each supported platform.
History Service Design
a locationbar intelligent algorithm (aka: the awesomebar) allows searchs through bookmarks, history, keywords (and much more) detaching the user from the old long searches through tree views.
Places Developer Guide
eating a livemark var ioservice = cc["@mozilla.org/network/io-service;1"] .getservice(ci.nsiioservice); var siteuri = ioservice.newuri("http://www.mozilla.com", null, null); var feeduri = ioservice.newuri("http://www.mozilla.org/news.rdf", null, null); var livemarks = cc["@mozilla.org/browser/livemark-service;2"] .getservice(ci.nsilivemarkservice); livemarks.createlivemark(bookmarks.toolbarfolder, // the id of the folder the livemark will be placed in "my livemark title", // the title of the livemark siteuri, // the uri of the site.
Places utilities for JavaScript
thus they persist the dialog dimensions separately from the showadd methods.
Querying Places
this type tells you what interface you can queryinterface the node to in order to get at more detailed information: nsinavhistoryresultnode: base class for all nodes.
Using the Places history service
stored separately is the information specific to each visit.
Creating a Python XPCOM component
if you wish to use pyxpcom from a normal python executable, you will need to tell python where it can find the pyxpcom library.
Avoiding leaks in JavaScript XPCOM components
if you implement nsiobserver in javascript and register that observer (without using weak references) with a service (for example, with the observer service bug 239833 or with the pref service bug 256822), the service will do exactly what you tell it to do: notify the observer you just created until you unregister the observer.
How to build an XPCOM component in JavaScript
if you need an intel version, you'll need to compile it yourself as described on that page.
Building the WebLock UI
in this tutorial, focusing as it is on the weblock functionality (rather than the ui), we'll assume the strings we get from the ui itself are urls we actually want to write to the white list: function addthissite() { var tf = document.getelementbyid("dialog.input"); // weblock is global and declared above weblock.addsite(tf.value); } this javascript function can be called directly from the xul widget, where the input string is retrieved as the value property of the textbox element.
Packaging WebLock
javascript apis from the xpinstall install object download the jar in which the installable files appear and call registration methods that tell mozilla about the new component and the ui it uses to access the weblock component.
Making cross-thread calls using runnables
manager: #include "nsxpcomcidinternal.h" void calculatepiasynchronously(int digits, picallback callback) { // to create a new thread, get the thread manager nscomptr<nsithreadmanager> tm = do_getservice(ns_threadmanager_contractid); nscomptr<nsithread> mythread; nsresult rv = tm->newthread(0, 0, getter_addrefs(mythread)); if (ns_failed(rv)) { // in case of failure, call back immediately with an empty string which indicates failure callback(emptycstring()); return; } nscomptr<nsirunnable> r = new picalculatetask(callback, digits); mythread->dispatch(r, nsieventtarget::dispatch_normal); // the result callback will shut down the worker thread, we can let it go here...
Components.Constructor
the component is then returned immediately, with only the base interface nsisupports available on it; you must call nsisupports.queryinterface() on it to call methods on the object.
Components.utils.Sandbox
in this case, components.utils.nukesandbox can be used to force the sandbox to be freed immediately.
Components.utils.evalInWindow
example suppose a page script defines a variable: // page-script.js var somelocalvariable = { name: "selection1", node: document.documentelement }; an add-on script or other privileged script can access the variable using evalinwindow(): // add-on-script.js var result = components.utils.evalinwindow("somelocalvariable", contentwindow); console.log(result); // {"name":"selection1","node":{}} the add-on code can modify the variable as well, of course: // add-on-script.js components.utils.evalinwindow("somelocalvariable.newprop = 42",...
Components.utils.forceGC
users should note that garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary.
HOWTO
however, when you start your script, it exits immediately, before the network request returns.
Profiling XPCShell
a profile will look like this: file:///users/michiel/mozilla/tree1/...js/calutils.js [2,25420] createdatetime() {60-62} 579 {min 0, max 3, avg 0, sum 427, self 427} [2,56810] cp_qi() {860-866} 835 {min 0, max 1, avg 0, sum 950, self 950} the first line tells which file was profiled.
xpcshell
to rectify this, run xpcshell with the -v 180 command-line option, which tells xpcshell to use javascript 1.8.
HeapMinimize
static nsresult heapminimize( prbool aimmediate ); parameters aimmediate [in] if true, heap minimization will occur immediately if the call was made on the main thread.
imgIEncoder
post-multiplied alpha us used (for example 50% transparent red is 0xff000080) input_format_hostargb 2 input is host-endian argb: on big-endian machines each pixel is therefore argb, and for little-endian machiens (intel) each pixel is bgra (this is used by canvas to match it's internal representation) pre-multiplied alpha is used (that is, 50% transparent red is 0x80800000, not 0x80ff0000) possible values for outputoptions.
nsIAppShell
native event starvation this hint tells the native dispatch code which to favor.
nsIAppStartup
if there are no windows open and no outstanding calls to enterlastwindowclosingsurvivalarea() this method will exit immediately.
nsIAsyncInputStream
if the stream is already readable or closed when asyncwait is called, then the nsiinputstreamcallback.oninputstreamready() event will be dispatched immediately.
nsIAsyncOutputStream
if the stream is already writable or closed when asyncwait is called, then the nsioutputstreamcallback.onoutputstreamready() event will be dispatched immediately.
nsIAuthPrompt2
this has largely the same semantics as nsiauthprompt.promptusernameandpassword(), but must return immediately after calling and return the entered data in a callback.
nsIBrowserSearchService
void init( [optional] in nsibrowsersearchinitobserver observer ); parameters observer if specified, a callback called once initialization is complete, or immediately, if the service has already been initialized.
nsIChannel
load_classify_uri 22 this flag tells the channel to use uri classifier service to check the uri when opening the channel.
nsIClipboardDragDropHooks
method overview boolean allowdrop(in nsidomevent event, in nsidragsession session); boolean allowstartdrag(in nsidomevent event); boolean oncopyordrag(in nsidomevent aevent, in nsitransferable trans); boolean onpasteordrop(in nsidomevent event, in nsitransferable trans); methods allowdrop() tells gecko whether a drop is allowed on this content area.
nsICommandLine
this may be the original command line of this instance or a command line provided remotely by another instance of the application.
nsICookieService
cvs blame will tell you why it is here.
nsICrashReporter
native code only!writeminidumpforexception write a minidump immediately, with the user-supplied exception information.
nsICryptoHash
= components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(components.interfaces.nsifileinputstream); // open for reading istream.init(f, 0x01, 0444, 0); var ch = components.classes["@mozilla.org/security/hash;1"] .createinstance(components.interfaces.nsicryptohash); // we want to use the sha256 algorithm ch.init(ch.sha256); // this tells updatefromstream to read the entire file const pr_uint32_max = 0xffffffff; ch.updatefromstream(istream, pr_uint32_max); // pass false here to get binary data back var hash = ch.finish(false); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0" + charcode.tostring(16)).slice(-2); } // convert the binary hash data to a hex string.
nsIDBChangeListener
there are a couple of ways to access the message database: if you have a nsimsgfolder, you can do this like so: somefolder.msgdatabase.addlistener(mylistener); alternately, you can access the message database through the nsimsgdbview like so: gfolderdisplay.view.dbview.db.addlistener(mylistener); method overview void onhdrflagschanged(in nsimsgdbhdr ahdrchanged, in unsigned long aoldflags, in unsigned long anewflags, in nsidbchangelistener ainstigator); void onhdrdeleted(in nsimsgdbhdr ahdrchanged, in nsmsgkey aparentkey, in long aflags, in ...
nsIDNSRequest
the listener will passed to asyncresolve will be notified immediately with a status code of ns_error_abort.
nsIDOMMozTouchEvent
in boolean shiftkeyarg, in boolean metakeyarg, in unsigned short buttonarg, in nsidomeventtarget relatedtargetarg, in unsigned long streamidarg); attributes attribute type description streamid unsigned long a unique identifier for each finger, so that each finger's movement can be tracked separately.
nsIDOMOfflineResourceList
this will check for a new cache manifest but will not tell the browser to use the updated cache.
nsIDOMWindowInternal
this interface no longer has any members; it exists solely to prevent add-ons that reference it from failing completely.
nsIDOMXPathEvaluator
to evaluate against a whole document, use the document.documentelement.
nsIDOMXPathExpression
to evaluate against a whole document, use the document.documentelement method to get the node to evaluate against.
nsIDeviceMotion
removelistener() tells the accelerometer to stop sending updates to the specified nsidevicemotionlistener.
nsIEditorDocShell
methods makeeditable() make this docshell editable, setting a flag that causes an editor to get created, either immediately, or after a url has been loaded.
nsIEventTarget
when this flag is specified, dispatch() returns immediately after the event is queued.
nsIExternalProtocolService
this parameter may be ultimately passed nsiuriloader.openuri() in the case of a web handler, and awindowcontext is null or not present, web handlers will fail.
nsIFileInputStream
(the file will only be reopened if it is closed for some reason.) defer_open 1<<4 if this is set, the file will be opened (i.e., a call to pr_open() done) only when we do an actual operation on the stream, or more specifically, when one of the following is called: seek() tell() available() read() readline() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well.
nsIFileOutputStream
the deferred open will be performed when one of the following is called: seek() tell() write() flush() defer_open is useful if we use the stream on a background thread, so that the opening and possible stating of the file happens there as well.
nsIFilePicker
if you would like to use another you must append it separately before the others you want to go into the drop down list.
nsIFileView
riate id is passed, nsifileview relies on the treecols section --> <treecol id="filenamecolumn" label="name" flex="1" primary="true"/> <treecol id="lastmodifiedcolumn" label="date" flex="1"/> <treecol id="size" label="size" flex="1"/> </treecols> <treechildren/> </tree> <script> var dir="/home/"; //the directory to be opened var ftree = document.getelementbyid("ftree"); //the xul tree element var lfile = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); lfile.initwithpath(dir); // open the directory var fview = components.classes["@mozilla.org/filepicker/fileview;1"] .createinstance(components.interfaces.nsifileview); //create an instance of the component tview = fv...
nsIHttpChannel
redirectto() instructs the channel to immediately redirect to a new destination.
nsILoginManagerStorage
a login must match completely (except for its nsiloginmetainfo data) to be removed.
nsIMarkupDocumentViewer
sizetocontent() tell the container to shrink-to-fit or grow-to-fit its contents.
nsIMemory
void heapminimize( in boolean immediate ); parameters immediate if true, heap minimization will occur immediately if the call was made on the main thread.
nsIMemoryReporter
when a reporter from a child process is copied into the main process, the copy's process field is set appropriately.
nsIMemoryReporterManager
this reporter is special-cased because it is interesting, and is moderately difficult to compute in javascript.
nsIMicrosummaryGenerator
it tells us where the generator comes from and where to go for updates.
nsIMicrosummaryService
if the caller passes a bookmark id, and one of the microsummaries is the current one for the bookmark, this method will retrieve content from the datastore for that microsummary, which is useful when callers want to display a list of microsummaries for a page that isn't loaded, and they want to display the actual content of the selected microsummary immediately (rather than after the content is asynchronously loaded).
nsIMsgDBViewCommandUpdater
updatenextmessageafterdelete() allows the backend to tell the front end to re-determine which message we should select after a delete or move void updatenextmessageafterdelete(); parameters none.
nsIMsgSearchTerm
possible values: * plugin filter imapflag user whitelist * @return true if matches */ boolean matchjunkscoreorigin(in string ajunkscoreorigin); matchbody /** * test if the body of the passed in message matches "this" search term.
nsIMsgSearchValue
rtime date; // see nsmsgmessageflags.idl and nsmsgfolderflags.idl attribute unsigned long status; attribute unsigned long size; attribute nsmsgkey msgkey; attribute long age; // in days attribute nsimsgfolder folder; attribute nsmsglabelvalue label; attribute nsmsgjunkstatus junkstatus; /* * junkpercent is set by the message filter plugin, and is approximately * proportional to the probability that a message is junk.
nsINavHistoryResult
the viewer then tells the actual view object what to do.
nsINavHistoryResultTreeViewer
obsolete since gecko 1.9 flatitemcount pruint32 this tells you how many items are in the flattened list of results, that is how many rows are in this tree right now.
nsIOutputStream
exceptions thrown ns_base_stream_would_block a non-blocking stream may throw this exception when written to if space for the data is not immediately available.
nsIPipe
for example, if you try to read from an empty pipe that has not yet been closed, then if that pipe's input end is non-blocking, then the read call will fail immediately with ns_base_stream_would_block as the error condition.
nsIPrefService
resetprefs() called to completely flush and re-initialize the preferences system.
nsIPrivateBrowsingService
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface is deprecated since firefox 20, and will probably be completely removed in firefox 21.
nsIProfileUnlocker
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void unlock(in unsigned long aseverity); constants constant value description attempt_quit 0 politely ask the process currently holding the profile's lock to quit.
nsIPropertyBag
services.appinfo.os simply tells us winnt only, this is not helpful to differentiate between windows xp, vista, 7, etc.
nsIRequest
note: some implementations are unable to immediately suspend, and may continue to deliver events already posted to an event queue.
nsIResumableChannel
in both of these cases, no ondataavailable will be called, and onstoprequest will immediately follow with the same status code.
nsIScriptableUnescapeHTML
this is equivalent to calling nsiparserutils::converttoplaintext(src, nsidocumentencoder::outputselectiononly | nsidocumentencoder::outputabsolutelinks, 0).
nsISmsService
send() void send( in domstring number, in domstring message, in long requestid, in unsigned long long processid optional ); parameters number a domstring with a telephone number to send to.
nsISpeculativeConnect
the code implementing this method may use this information to start a tcp and/or ssl level handshake for that resource immediately so that it is ready (or at least in the process of becoming ready) when the transaction is actually submitted.
nsITaskbarPreviewController
the specified context is attached to a surface with the controller's width and height, the values of which are obtained immediately prior to calling this method.
nsITextInputProcessorNotification
dom/interfaces/base/nsitextinputprocessorcallback.idlscriptable this interface of a request or notification to ime 1.0 66 introduced gecko 38 inherits from: nsisupports last changed in gecko 38.0 (firefox 38.0 / thunderbird 38.0 / seamonkey 2.35) this interface tells details of a request or notification to ime.
nsIThread
if false, this method returns immediately if the queue is empty.
nsITimer
if the callback takes a long time, then the next callback will be scheduled immediately afterward, but only once, unlike type_repeating_precise.
nsITransaction
if the transient state is true, the transaction manager returns immediately after the transaction's dotransaction() method is called, no references to the transaction are maintained.
nsITransactionManager
a value of zero means the transaction manager will execute each transaction, then immediately release all references it has to the transaction without pushing it on the undo stack.
nsIURIFixup
fixup_flags_make_alternate_uri 2 tell the fixup to make an alternate uri from the input uri, for example to turn foo into www.foo.com.
nsIURL
and hence don't rely on this for something to be a definitely be a file.
nsIUpdateChecker
this is used by any user interface that offers the user the opportunity to check for updates immediately.
nsIUpdatePrompt
showupdateerror() displays an error message telling the user about an update failure, such as a failure to successfully apply a patch.
nsIWebPageDescriptor
methods loadpage() tells the object to load the page specified by the page descriptor.
nsIWindowMediator
for that reason this interface requires only objects one step removed from the native window (nsiwidgets), and its implementation must be very understanding of what may be completely invalid pointers in those parameters.
nsIZipReader
neither of the patterns foo or bar may use the 'pat~pat2' syntax described immediately above.
nsIMsgSearchValue
rtime date; // see nsmsgmessageflags.idl and nsmsgfolderflags.idl attribute unsigned long status; attribute unsigned long size; attribute nsmsgkey msgkey; attribute long age; // in days attribute nsimsgfolder folder; attribute nsmsglabelvalue label; attribute nsmsgjunkstatus junkstatus; /* * junkpercent is set by the message filter plugin, and is approximately * proportional to the probability that a message is junk.
nsIAbCard/Thunderbird3
note: this interface has been overhauled completely for thunderbird 3.
nsMsgViewCommandCheckState
it is (as far as i can tell) not currently used anywhere in thunderbird.
XPCOM reference
it is (as far as i can tell) not currently used anywhere in thunderbird.nsmsgviewcommandtypethe nsmsgviewcommandtype interface contains constants used for commands in thunderbird.
Storage
in c++ code, there is a helper class defined in storage/public/mozstoragehelper.h, mozstoragetransaction, that will attempt to get a transaction for you, and handle it appropriately when it falls out of scope.
Using nsISimpleEnumerator
using nsisimpleenumerator <stringbundle>.strings var enumerator = document.getelementbyid('astringbundleid').strings; var s = ""; while (enumerator.hasmoreelements()) { var property = enumerator.getnext().queryinterface(components.interfaces.nsipropertyelement); s += property.key + ' = ' + property.value + ';\n'; } alert(s); example using javascript 1.7 features // creates a generator iterating over enum's values function generatorfromsimpleenumerator(enum, interface) { while (enum.hasmoreelements()) { yield enum.getnext().queryinterface(interface); } } var b = document.getelementbyid("stringbundleset").firstchild var props = generatorfromenumerator(b.strings, components.interfaces.nsipropertyelement); var s = ""; for (let property in props) { s += property.key +...
XPCOM ABI
is still considered x86) sparc - sparc series ia64 - itanium series {target_compiler_abi}[platforms] represents the compiler abi and may be either: msvc - microsoft visual c++ n32 - irix 6 c++ compiler gcc2 - gnu c++ compiler 2.x gcc3 - gnu c++ compiler 3.x or 4.x sunc - sun c++ compiler ibmc - ibm c++ compiler for example: firefox built with the gnu c++ compiler 4.0.0 for the intel pentium processor would have xpcom abi of x86-gcc3 the xpcom abi string can be retrieved programmatically by using the nsixulruntime interface.
XUL Overlays
MozillaTechXULOverlays
inserting the following processing instruction before the doctype declaration in a base file tells the layout engine to load the named overlay file: <?xul-overlay href="chrome://component/content/componentoverlay.xul"?> where component is the name of the package being overlayed (e.g., chrome://navigator/content/navigatoroverlay.xul).
Xray vision
instead of filtering out modifications made by content, the xray short-circuits the content completely.
Address book sync client design
ab sync logic mork ab database sync protocol encoding sync protocol decoding http "post" api mozilla networking client side sync logic the client synchronization logic defers to the server peforming some intelligence in handling duplicate entries for the sync process.
DB Views (message lists)
text nsitreeview.getcelltext (implementation) tells the nsitreeview what text to display for a particular row and text column.
nsIMsgCloudFileProvider
this should probably be called immediately after instantiation.
Filelink Providers
for example, the hightail implementation provides the following function: function extraargs() { var usernamevalue = document.getelementbyid("username").value; return { "username": {type: "char", value: usernamevalue}, }; } in this example, the username value is read from the input, and then the specially-crafted object is returned.
Mail and RDF
when a folder's contents or properties change, it tells the mail session to notify the folder listeners that the data has changed.
Mail composition back end
this will contain all of the relevant header information for message delivery nsfilespec *sendfilespec, - the file spec for the message being sent prbool deletesendfileoncompletion, - tell the back end if it should delete the file upon successful completion prbool digest_p, - this is a flag that says that most of the documents we are attaching are themselves messages, and so we should generate a multipart/digest container instead of multipart/mixed.
Mail event system
nsimsgmailsession also contains a number of other methods that are completely unrealted to folder notification.
Mailnews and Mail code review requirements
a bug is still required, even if it is immediately marked fixed.
Building a Thunderbird extension 6: Adding JavaScript
window.addeventlistener("load", function(e) { startup(); }, false); window.setinterval( function() { startup(); }, 60000); //update date every minute function startup() { var mypanel = document.getelementbyid("my-panel"); var date = new date(); var day = date.getday(); var datestring = date.getfullyear() + "." + (date.getmonth()+1) + "." + date.getdate(); mypanel.label = "date: " + datestring; } the first part registers a new event listener that will be executed automatically when thunderbird loads.
Creating a Custom Column
unfortunately the new column doesn't have any data in it and it doesn't react to sort clicks on it...
Access Window
check if the window is a tab or the root window window.addeventlistener("load", function(e) { alert("is root?: " + isroot()); }, false); function isroot() { if(window != window.top) return "false"; else return "true"; } the example above tells you if the window object is a reference of the application window or of one of it is a tabs.
Add New Tab
var aurl = "chrome://myext/mytab.xul"; let tabmail = getmail3pane().document.getelementbyid("tabmail"); tabmail.opentab("chrometab", { chromepage: aurl }); ...
Detect Opening Folder
to do this you need to capture the select event of the folder [[xul:tree|tree]] whose id is (conveniently) foldertree like so: window.document.getelementbyid('foldertree').addeventlistener("select", testcolumns, false); ...
Toolkit version format
a few examples of valid version parts: 0 (as in 1.0): <number-a>=0 5a (as in 1.5a): <number-a>=5, <string-b>=a 5pre4 (as in 3.5pre4): <number-a>=5, <string-b>=pre, <number-c>=4 * (as in 1.0.*): <string-b>=* a few special parsing rules are applied for backwards compatibility and readability: if the version part is a single asterisk, it is interpreted as an infinitely-large number: 1.5.0.* is the same as 1.5.0.(infinity) if string-b is a plus sign, number-a is incremented to be compatible with the firefox 1.0.x version format: 1.0+ is the same as 1.1pre the rationale behind splitting a version part into a sequence of strings and numbers is that when comparing version parts, the numeric parts are compared as numbers, e.g.
Using popup notifications
components.utils.import('resource://gre/modules/popupnotifications.jsm'); var notify = new popupnotifications(gbrowser, document.getelementbyid("notification-popup"), document.getelementbyid("notification-popup-box")); var notification = notify.show( // browser gbrowser.selectedbrowser, // popup id "pdes-popup", // message "hi, there!, i'm gonna show you something today!!", // anchor id null, // main action { label: "click here", accesskey: "d", callback: function() { // you can call you...
Virtualenv
> ls tmp/bin/ activate activate.fish easy_install pip python activate.csh activate_this.py easy_install-2.7 pip-2.7 using this python binary, or these scripts (which point to this python binary), you will correctly install python packages in the lib/python2.x/site-packages directory and they will be appropriately added to your import path (sys.path) via lib/python2.x/site.py.
Zombie compartments
this page tells you how to detect and avoid zombie compartments, which are a particular kind of memory leak.
Using COM from js-ctypes
0x9e', '0xe3', '0x00', '0xc0', '0x4f', '0x79', '0x73', '0x96']); let iid_ispvoice = iidfromarr(['0x6c44df74', '0x72b9', '0x4992', '0xa1', '0xec', '0xef', '0x99', '0x6e', '0x04', '0x22', '0xd4']); let spf_default = 0; function main() { let spvoice; let spvoiceptr; try { // msdn docs tell us ot use coinitex instead of coinit, and default is 0 // which is coinit_multithreaded but it wouldnt work so i used // coinit_apartmentthreaded and it worked checkhresult would throw a bad // hresult of rpc_e_changed_mode which is 0x80010106 which is // -2147417850.
Standard OS Libraries
although jni is done completely through js-ctypes, a jsm was created to abstract away the js-ctypes so developers can focus on the jni aspect.
Using js-ctypes
r('we just called the equivalent of the "standardalert carbon function" for 64bit osx from javascript!') }; var rez = cfusernotificationdisplaynotice(0, kcfusernotificationcautionalertlevel, null, null, null, mycfstrs.head, mycfstrs.body, null); console.info('rez:', rez, rez.tostring(), uneval(rez)); // cfusernotificationdisplaynotice does not block till user clicks dialog, it will return immediately if (rez.tostring() == '0') { console.log('notification was succesfully shown!!'); } else { console.error('failed to show notification...
ctypes
so we will figure that out and create the structure appropriately.
PKCS #11 Netscape Trust Objects - Network Security Services
conceptually a trust object contains the following: certificate reference purpose + level of trust (multiple) purpose + level of trust a trust object ultimately denotes a level of trust in a certificate.
Blocking By Domain - Plugins
subsequent updates to the list will be made using telemetry from firefox experiments.
Initialization and Destruction - Plugins
instance destruction: the plug-in instance is deleted when the user leaves the instance page or closes the instance window; the browser calls the function npp_destroy to tell the plug-in that the instance is being deleted.
Plug-in Development Overview - Plugins
consider the following example, where a media player plug-in can be controlled with an advancetonextsong() method called inside the script element: <object id="myplugin" type="audio/wav" data="music.wav"> </object> <script type="application/javascript"> var theplugin = document.getelementbyid('myplugin'); if (theplugin && theplugin.advancetonextsong) theplugin.advancetonextsong(); else alert("plugin not installed correctly"); </script> in the past, liveconnect and later xpconnect were used to make plug-ins scriptable.
Gecko Plugin API Reference - Plugins
dowed plug-ins mac os windows unix event handling for windowed plug-ins windowless plug-ins specifying that a plug-in is windowless invalidating the drawing area forcing a paint message making a plug-in opaque making a plug-in transparent creating pop-up menus and dialog boxes event handling for windowless plug-ins streams receiving a stream telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode sending a stream creating a stream pushing data into the stream deleting the stream example of sending a stream urls getting urls getti...
Plugin Roadmap for Firefox - Plugins
2020 in december 2020, flash support will be completely removed from consumer versions of firefox.
Preferences System
using this system it is possible to create preferences windows that display and operate appropriately on various platforms (windows, macos x and gnome).
Color vision simulation - Firefox Developer Tools
in the simulate menu, you can choose one option at a time from the following list: none — choose this to return to normal display protanomaly (low red) deuteranomaly (low green) tritanomaly (low blue) protanopia (no red) deuteranopia (no green) tritanopia (no blue) contrast loss these simulations are not completely medically accurate.
Debugging service workers - Firefox Developer Tools
this is very useful because, once registered, the service worker will not necessarily update to the new version immediately, which can make debugging a pain.
Browser Console - Firefox Developer Tools
on windows, the following code will add a new item to the browser's main menu: var parent = window.document.getelementbyid("appmenuprimarypane"); var makethetea = gbrowser.ownerdocument.defaultview.document.createelementns("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem"); makethetea.setattribute("label", "a nice cup of tea?"); parent.appendchild(makethetea); on macos, this similar code will add a new item to the "tools" menu: var parent = window.document.getelementbyid("menu_too...
Access debugging in add-ons - Firefox Developer Tools
window.addeventlistener("debugger:editorunloaded") relevant files: chrome://browser/content/devtools/debugger-controller.js chrome://browser/content/devtools/debugger-toolbar.js chrome://browser/content/devtools/debugger-view.js chrome://browser/content/devtools/debugger-panes.js unfortunately there is not yet any api to evaluate watches/expressions within the debugged scope, or highlight elements on the page that are referenced as variables in the debugged scope.
Debug eval sources - Firefox Developer Tools
in the video below, we load a page containing a source like this: var script = `function foo() { console.log('called foo'); } //# sourceurl=my-foo.js`; eval(script); var button = document.getelementbyid("foo"); button.addeventlistener("click", foo, false); the evaluated string is given the name "my-foo.js" using the //# sourceurl directive.
Ignore a source - Firefox Developer Tools
however, you can tell the debugger to ignore the details of selected sources.
Debugger.Script - Firefox Developer Tools
for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
Debugger.Source - Firefox Developer Tools
"scriptelement", for code belonging to <script> elements.
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
the saved stacks // are new, and firefox doesn't yet understand that they // are safe for chrome code to use, so we must tell it // so explicitly.
DevTools API - Firefox Developer Tools
unfortunately, their api's are a bit different and it's not always evident which one a certain component is using.
Basic operations - Firefox Developer Tools
recording call stacks the memory tool can tell you exactly where in your code you are allocating memory.
DOM allocation example - Firefox Developer Tools
rn toolbarbutton; } function createtoolbar() { var toolbar = document.createelement("div"); // stop spidermonkey from sharing instances toolbar[getrandomint(0,5000)] = "foo"; for (var i = 0; i < toolbarbuttoncount; i++) { var toolbarbutton = createtoolbarbutton(); toolbar.appendchild(toolbarbutton); } return toolbar; } function createtoolbars() { var container = document.getelementbyid("container"); for (var i = 0; i < toolbarcount; i++) { var toolbar = createtoolbar(); container.appendchild(toolbar); } } createtoolbars(); a simple pseudocode representation of how this code operates looks like this: createtoolbars() -> createtoolbar() // called 200 times, creates 1 div element each time -> createtoolbarbutton() // called 20 times per toolbar, ...
Monster example - Firefox Developer Tools
y": [], "fierce": [], "undecided": [] }; for (var i = 0; i &lt; monster_count; i++) { monsters.friendly.push(new monster()); } for (var i = 0; i &lt; monster_count; i++) { monsters.fierce.push(new monster()); } for (var i = 0; i &lt; monster_count; i++) { monsters.undecided.push(new monster()); } console.log(monsters); } var makemonstersbutton = document.getelementbyid("make-monsters"); makemonstersbutton.addeventlistener("click", makemonsters); the page contains a button: when you push the button, the code creates some monsters.
Page inspector 3-pane mode - Firefox Developer Tools
for example, you could edit a css grid property and observe the change immediately in the grid inspector.
Examine and edit CSS - Firefox Developer Tools
edit rules if you click on a declaration or a selector in the rules view you can edit it and see the results immediately.
Examine and edit the box model - Firefox Developer Tools
it's also shown overlaid if you hover over an element's markup in the html pane: if the element is inline and is split over multiple line boxes, the highlighter shows each individual line box that together make up the element: the box model view when an element's selected, you can get a detailed look at the box model in the box model view: if you hover over a value, you'll see a tooltip telling you which rule the value comes from: if you hover over part of the box model in the box model view, the corresponding part of the page is highlighted: editing the box model you can also edit the values in the box model view, and see the results immediately in the page: ...
Inspect and select colors - Firefox Developer Tools
if you click on the color sample, you'll see a color picker popup, enabling you to change the color: if the color is a foreground color, the color picker tells you whether its contrast with the background color meets accessibility guidelines.
Select an element - Firefox Developer Tools
the highlighted element is the element that's overlaid in the page with a graphic showing the box model, and a tooltip showing its tag and size: with the context menu to open the inspector and select an element immediately, activate the context menu over the element in the page and select "inspect element": with the html pane when the inspector is open, as you move the mouse around the elements listed in the html pane, the corresponding elements are highlighted in the page.
Select and highlight elements - Firefox Developer Tools
the highlighted element is the element that's overlaid in the page with a graphic showing the box model, and a tooltip showing its tag and size: with the context menu to open the inspector and select an element immediately, activate the context menu over the element in the page and select "inspect element": with the html pane when the inspector is open, as you move the mouse around the elements listed in the html pane, the corresponding elements are highlighted in the page.
Animation inspector example: CSS transitions - Firefox Developer Tools
{ opacity: 1; width: 300px; } javascript content function toggleselection(e) { if (e.button != 0) { return; } if (e.target.classlist.contains("icon")) { var wasselected = (e.target.getattribute("id") == "selected"); clearselection(); if (!wasselected) { e.target.setattribute("id", "selected"); } } } function clearselection() { var selected = document.getelementbyid("selected"); if (selected) { selected.removeattribute("id"); } } document.addeventlistener("click", toggleselection); ...
Animation inspector example: Web Animations API - Firefox Developer Tools
, offset: 0.666 }, { transform: 'scale(1.5)', filter: 'grayscale(0%)'} ]; var notekeyframeset = [ { opacity: '0', width: '0'}, { opacity: '1', width: '300px'} ]; var iconkeyframeoptions = { duration: 750, fill: 'forwards', easing: 'ease-in', enddelay: 100 } var notekeyframeoptions = { duration: 500, fill: 'forwards', easing: 'ease-out', delay: 150 } var icon = document.getelementbyid("icon"); var note = document.getelementbyid("note"); var iconanimation = icon.animate(iconkeyframeset, iconkeyframeoptions); var noteanimation = note.animate(notekeyframeset, notekeyframeoptions); iconanimation.pause(); noteanimation.pause(); var firsttime = true; function animatechannel(e) { if (e.button != 0) { return; } if (e.target.id != "icon") { return; } if (...
UI Tour - Firefox Developer Tools
the select element button is one way you can select an element for inspection: note that it's actually part of the main toolbox toolbar, so it's immediately accessible from any tool, not just the inspector.
Flame Chart - Firefox Developer Tools
if you counted them all, the call tree view tells us that you'd see 253 of them.
UI Tour - Firefox Developer Tools
flame chart if the call tree tells you, statistically, which functions your site is spending most time executing across the whole recording, the flame chart tells you the call stack at any given point during the recording: to learn much more about the flame chart, see the separate flame chart page.
Settings - Firefox Developer Tools
to change the threshold at which attributes are truncated, you can edit the about:config preference "devtools.markup.collapseattributelength".
Validators - Firefox Developer Tools
tune-up wizard links back to devedge if you're writing new code that isn't validating immediately, see the available standards-compliant authoring and development tools.
Web Audio Editor - Firefox Developer Tools
if you click on a value in the node inspector you can modify it: press enter or tab and the new value takes effect immediately.
about:debugging (before Firefox 68) - Firefox Developer Tools
note that this feature isn't that immediately useful to debugging desktop tabs — you can open up a toolbox to debug a tab easily enough already — but this will become far more useful when about:debugging starts to support remote debugging, and this page can begin to list tabs available for debugging on mobile device browsers, simulators, etc.
AbsoluteOrientationSensor - Web APIs
examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second.
AddressErrors - Web APIs
window.addeventlistener("load", function(ev) { document.getelementbyid("pay").addeventlistener("click", process, false); }, false); see addeventlistener() for information about event handlers and how they work.
AnalyserNode - Web APIs
analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // get a canvas defined with id "oscilloscope" var canvas = document.getelementbyid("oscilloscope"); var canvasctx = canvas.getcontext("2d"); // draw an oscilloscope of the current audio source function draw() { requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = "rgb(200, 200, 200)"; canvasctx.fillrect(0, 0, canvas.width, canvas.height); canvasctx.linewidth = 2; canvasctx.strokestyle = "rgb(0, 0, 0)"; canva...
Animation.pause() - Web APIs
WebAPIAnimationpause
example animation.pause() is used many times in the alice in web animations api land growing/shrinking alice game, largely because animations created with the element.animate() method immediately start playing and must be paused manually if you want to avoid that: // animation of the cupcake slowly getting eaten up var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ { transform: 'translatey(0)' }, { transform: 'translatey(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: alicechange.effect.timing.duration / 2 }); // doesn't actually need ...
Animation.play() - Web APIs
WebAPIAnimationplay
two animation.play()s, one eventlistener: // the cake has its own animation: var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ { transform: 'translatey(0)' }, { transform: 'translatey(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: alicechange.effect.timing.duration / 2 }); // pause the cake's animation so it doesn't play immediately.
Animation.startTime - Web APIs
examples in the running on web animations api example, the we can sync all new animated cats by giving them all the same starttime as the original running cat: var catrunning = document.getelementbyid ("withwaapi").animate(keyframes, timing); /* a function that makes new cats.
Animation.updatePlaybackRate() - Web APIs
after calling updateplaybackrate() the animation's playbackrate is not immediately updated.
AudioBufferSourceNode.start() - Web APIs
the start() method of the audiobuffersourcenode interface is used to schedule playback of the audio data contained in the buffer, or to begin playback immediately.
AudioNode.connect() - Web APIs
WebAPIAudioNodeconnect
notsupportederror the specified connection would create a cycle (in which the audio loops back through the same nodes repeatedly) and there are no delaynodes in the cycle to prevent the resulting waveform from getting stuck constructing the same audio frame indefinitely.
AudioNode - Web APIs
WebAPIAudioNode
the exact processing done varies from one audionode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the analysernode, where the result of the processing is accessed separately).
AudioParam.value - Web APIs
WebAPIAudioParamvalue
thus, the value of a parameter is maintained to accurately reflect the state of the parameter over time.
AudioScheduledSourceNode: ended event - Web APIs
examples in this simple example, an event listener for the ended event is set up to enable a "start" button in the user interface when the node stops playing: node.addeventlistener('ended', () => { document.getelementbyid("startbutton").disabled = false; }) you can also set up the event handler using the audioscheduledsourcenode.onended property: node.onended = function() { document.getelementbyid("startbutton").disabled = false; } for an example of the ended event in use, see our audio-buffer example on github.
AudioScheduledSourceNode.onended - Web APIs
node.onended = function(event) { document.getelementbyid("startbutton").disabled = false; } specifications specification status comment web audio apithe definition of 'onended' in that specification.
AudioScheduledSourceNode - Web APIs
if no time is specified, the node begins playing immediately.
AudioTrack.enabled - Web APIs
function swapcommentarymain() { var videoelem = document.getelementbyid("main-video"); var audiotrackmain; var audiotrackcommentary; videoelem.audiotracks.foreach(track) { if (track.kind === "main") { audiotrackmain = track; } else if (track.kind === "commentary") { audiotrackcommentary = track; } } if (audiotrackmain && audiotrackcommentary) { var commentaryenabled = audiotrackcommentary.enabled; audiotrackcomment...
BaseAudioContext.createDelay() - Web APIs
if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time.
BaseAudioContext - Web APIs
baseaudiocontext.createchannelsplitter() creates a channelsplitternode, which is used to access the individual channels of an audio stream and process them separately.
BatteryManager - Web APIs
batterymanager.dischargingtime read only a number representing the remaining time in seconds until the battery is completely discharged and the system will suspend.
Blob.size - Web APIs
WebAPIBlobsize
// fileinput is a htmlinputelement: <input type="file" multiple id="myfileinput"> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (simliar to nodelist) var files = fileinput.files; for (var i = 0; i < files.length; i++) { console.log(files[i].name + " has a size of " + files[i].size + " bytes"); } specifications specification status comment file apithe defini...
Blob.type - Web APIs
WebAPIBlobtype
var i, fileinput, files, allowedfiletypes; // fileinput is a htmlinputelement: <input type="file" multiple id="myfileinput"> fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (simliar to nodelist) files = fileinput.files; // our application only allows gif, png, and jpeg images allowedfiletypes = ["image/png", "image/jpeg", "image/gif"]; for (i = 0; i < files.length; i++) { // test if file.type is an allowed file type.
BluetoothCharacteristicProperties - Web APIs
examples the following example shows how tell if a gatt characteristic supports value change notifications.
Body.body - Web APIs
WebAPIBodybody
const image = document.getelementbyid('target'); // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); return new readablestream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // when no more data needs to be co...
CSS.registerProperty() - Web APIs
registering a custom property allows you to tell the 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.
CSSKeywordValue.CSSKeywordValue() - Web APIs
#myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let keyword = new csskeywordvalue('initial'); let myelement = document.getelementbyid('myelement').attributestylemap; myelement.set('display', keyword); console.log( myelement.get('display').value); // 'initial' console.dir( keyword ); specifications specification status comment css typed om level 1the definition of 'csskeywordvalue' in that specification.
CSSKeywordValue.value - Web APIs
let indicator = document.getelementbyid('indicator'); indicator.attributestylemap.set('display', new csskeywordvalue('initial')); indicator.attributestylemap.get('display').value // 'initial' specifications specification status comment css typed om level 1the definition of 'undefined' in that specification.
CSSKeywordValue - Web APIs
#myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let myelement = document.getelementbyid('myelement').attributestylemap; myelement.set('display', new csskeywordvalue('initial')); console.log( myelement.get('display').value); // 'initial' specifications specification status comment css typed om level 1the definition of 'csskeywordvalue' in that specification.
CSSPositionValue.CSSPositionValue() - Web APIs
let somediv = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); // 5 10 ...
CSSPositionValue.x - Web APIs
let somediv = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); ...
CSSPositionValue.y - Web APIs
let replaceel = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); ...
CSSPositionValue - Web APIs
let replacedel = document.getelementbyid( 'image' ); let position = new csspositionvalue( css.px(35), css.px(40) ); replacedel.attributestylemap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedel.computedstylemap().get('object-position') ); we set the object-position property, then check the values returned.
CSSPrimitiveValue.getRectValue() - Web APIs
example var cs = window.getcomputedstyle(document.getelementbyid("clippeddiv")); var cssvalue = cs.getpropertycssvalue("clip"); console.log(cssvalue.getrectvalue()); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.getrectvalue' in that specification.
CSSPseudoElement.element - Web APIs
examples the example below demonstrates the relationship between csspseudoelement.element and element.pseudo(): const myelement = document.queryselector('q'); const csspseudoelement = myelement.pseudo('::after'); const originatingelement = csspseudoelement.element; console.log(myelement === originatingelement); // outputs true console.log(myelement.parentelement === originatingelement); // outputs false console.log(myelement.lastelementchild === csspseudoelement); // outputs false console.log(myelement.lastchild === csspseudoelement); // outputs false console.log(myelement.nextelementsibling === csspseudoelement); // outputs false console.log(myelement.nextsibling === csspseudoelement); // outputs false specifications ...
CSSRule.cssText - Web APIs
WebAPICSSRulecssText
in other words, attempting to set it does absolutely nothing, and doesn't even omit a warning or error.
CSSRuleList - Web APIs
if however, for some reason the list does need to be modified but has no parent stylesheet (perhaps being a livecopy of a list that does), it cannot just be assigned one (as it has no such property), and neither can it be assigned to one (as stylesheet.cssrules is read-only), but it must unfortunately be inserted into one, rule by rule, and unless combining lists, after any existing list therein is deleted, rule by rule.
CSSStyleDeclaration.cssText - Web APIs
example <span id="s1" style="color: red;"> some text </span> <script> var elem = document.getelementbyid("s1"); alert(elem.style.csstext); // "color: red;" </script> specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration: csstext' in that specification.
CSSStyleDeclaration.item() - Web APIs
javascript has a special simpler syntax for obtaining an item from a nodelist by index: var propertyname = style[index]; example var style = document.getelementbyid('div1').style; var propertyname = style.item(1); // or simply style[1] - returns the second style listed specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.item()' in that specification.
CSSStyleDeclaration.length - Web APIs
example the following gets the number of explicitly set styles on the following html element: <div id="div1" style="margin: 0 10px; background-color: #ca1; font-family: monospace"></div> javascript code: var mydiv = document.getelementbyid('div1'); var divstyle = mydiv.style; var len = divstyle.length; // 6 specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.length' in that specification.
CSS Painting API - Web APIs
examples to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function.
Using the CSS properties and values API - Web APIs
registering a custom property registering a custom property allows you to tell the 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.
Cache.delete() - Web APIs
WebAPICachedelete
ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching.
Cache.keys() - Web APIs
WebAPICachekeys
ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching.
Cache.match() - Web APIs
WebAPICachematch
ignorevary: a boolean that when set to true tells the matching operation not to perform vary header matching — i.e.
Cache.matchAll() - Web APIs
WebAPICachematchAll
ignorevary: a boolean that when set to true tells the matching operation not to perform vary header matching — i.e.
CacheStorage.match() - Web APIs
ignorevary: a boolean that, when set to true, tells the matching operation not to perform vary header matching.
CanvasCaptureMediaStreamTrack.canvas - Web APIs
example // find the canvas element to capture var canvaselt = document.getelementsbytagname("canvas")[0]; // get the stream var stream = canvaselt.capturestream(25); // 25 fps // do things to the stream ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
example // find the canvas element to capture var canvaselt = document.getelementsbytagname("canvas")[0]; // get the stream var stream = canvaselt.capturestream(25); // 25 fps // send the current state of the canvas as a frame to the stream stream.getvideotracks()[0].requestframe(); specifications specification status comment media capture from dom elementsthe definition of 'canvascapturemediastream.requestframe()' in that specification.
CanvasGradient.addColorStop() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let gradient = ctx.createlineargradient(0, 0, 200, 0); gradient.addcolorstop(0, 'green'); gradient.addcolorstop(.7, 'white'); gradient.addcolorstop(1, 'pink'); ctx.fillstyle = gradient; ctx.fillrect(10, 10, 200, 100); result specifications specification status comment html living standardthe definition of 'can...
CanvasGradient - Web APIs
it is returned by the methods canvasrenderingcontext2d.createlineargradient() or canvasrenderingcontext2d.createradialgradient().
CanvasRenderingContext2D.beginPath() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // first path ctx.beginpath(); ctx.strokestyle = 'blue'; ctx.moveto(20, 20); ctx.lineto(200, 20); ctx.stroke(); // second path ctx.beginpath(); ctx.strokestyle = 'green'; ctx.moveto(20, 20); ctx.lineto(120, 120); ctx.stroke(); result specifications specification status comment html living standardthe definiti...
CanvasRenderingContext2D.canvas - Web APIs
you can get a reference to the canvas element within the canvasrenderingcontext2d by using the canvas property: var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.canvas // htmlcanvaselement specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.canvas' in that specification.
CanvasRenderingContext2D.clearHitRegions() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // set some hit regions ctx.addhitregion({id: 'eyes'}); ctx.addhitregion({id: 'nose'}); ctx.addhitregion({id: 'mouth'}); // remove them altogether from the canvas ctx.clearhitregions(); specifications canvas hit regions have been removed from the whatwg living standard, although discussions about future standardization are ongoing.
CanvasRenderingContext2D.createPattern() - Web APIs
the original image looks like this: html <canvas id="canvas" width="300" height="300"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var img = new image(); img.src = 'https://udn.realityripple.com/samples/04/aaeaf9aac4.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 300, 300); }; creating a pattern from a canvas in this example we create a pattern from the contents of an offscreen canva...
CanvasRenderingContext2D.createRadialGradient() - Web APIs
html <canvas id="canvas" width="200" height="200"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); // create a radial gradient // the inner circle is at x=110, y=90, with radius=30 // the outer circle is at x=100, y=100, with radius=70 var gradient = ctx.createradialgradient(110,90,30, 100,100,70); // add three color stops gradient.addcolorstop(0, 'pink'); gradient.addcolorstop(.9, 'white'); gradient.addcolorstop(1, 'green'); // set the...
CanvasRenderingContext2D.currentTransform - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let matrix = ctx.currenttransform; matrix.a = 1; matrix.b = 1; matrix.c = 0; matrix.d = 1; matrix.e = 0; matrix.f = 0; ctx.currenttransform = matrix; ctx.fillrect(0, 0, 100, 100); result ...
CanvasRenderingContext2D.direction - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.font = '48px serif'; ctx.filltext('hi!', 150, 50); ctx.direction = 'rtl'; ctx.filltext('hi!', 150, 130); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.direction' in that specification.
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
html <canvas id="canvas"> <button id="button1">continue</button> <button id="button2">quit</button> </canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const button1 = document.getelementbyid('button1'); const button2 = document.getelementbyid('button2'); document.addeventlistener('focus', redraw, true); document.addeventlistener('blur', redraw, true); canvas.addeventlistener('click', handleclick, false); redraw(); function redraw() { ctx.clearrect(0, 0, canvas.width, canvas.height); ...
CanvasRenderingContext2D.drawWindow() - Web APIs
it will, however, more accurately reflect the pixels rendered to the screen.
CanvasRenderingContext2D.font - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = 'bold 48px serif'; ctx.stroketext('hello world', 50, 100); result loading fonts with the css font loading api with the help of the fontface api, you can explicitly load fonts before using them in a canvas.
CanvasRenderingContext2D.getImageData() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 100, 100); ctx.fill(); let imagedata = ctx.getimagedata(60, 60, 200, 100); ctx.putimagedata(imagedata, 150, 10); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.getimagedata' in that specification.
CanvasRenderingContext2D.globalCompositeOperation - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.globalcompositeoperation = 'xor'; ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); ctx.fillstyle = 'red'; ctx.fillrect(50, 50, 100, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.globalcompositeoperation' in that specificati...
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
html <canvas id="canvas" width="460" height="210"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '16px sans-serif'; ctx.textalign = 'center'; const img = new image(); img.src = 'https://interactive-examples.mdn.mozilla.net/media/examples/star.png'; img.onload = function() { const w = img.width, h = img.height; ctx.filltext('source', w * .5, 20); ctx.drawimage(img, 0, 24, w, h); ctx.filltext('smoothing = t...
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { ctx.imagesmoothingquality = 'low'; ctx.drawimage(img, 0, 0, 300, 150); }; result specifications specification status comment html living standardthe definition of 'imagesmoothingqua...
CanvasRenderingContext2D.lineWidth - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 15; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(130, 130); ctx.rect(40, 40, 70, 70); ctx.stroke(); result more examples for more examples and explanation about this property, see applying styles and color in the canvas tutorial.
CanvasRenderingContext2D.measureText() - Web APIs
you can get a textmetrics object using the following code: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let text = ctx.measuretext('hello world'); console.log(text.width); // 56; specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.measuretext' in that specification.
CanvasRenderingContext2D.miterLimit - Web APIs
ayable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginpath(); ctx.moveto(0,0); ctx.linewidth = 15; ctx.lineto(100, 100); ctx.stroke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; dra...
CanvasRenderingContext2D.moveTo() - Web APIs
var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(50, 50); // begin first sub-path ctx.lineto(200, 50); ctx.moveto(50, 90); // begin second sub-path ctx.lineto(280, 120); ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.moveto' in that specification.
CanvasRenderingContext2D.putImageData() - Web APIs
html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); function putimagedata(ctx, imagedata, dx, dy, dirtyx, dirtyy, dirtywidth, dirtyheight) { var data = imagedata.data; var height = imagedata.height; var width = imagedata.width; dirtyx = dirtyx || 0; dirtyy = dirtyy || 0; dirtywidth = dirtywidth !== undefined?
CanvasRenderingContext2D.rect() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 20, 150, 100); ctx.fill(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.rect' in that specification.
CanvasRenderingContext2D.removeHitRegion() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // set a hit region ctx.addhitregion({id: 'eyes'}); // remove it from the canvas ctx.removehitregion('eyes'); specifications canvas hit regions have been removed from the whatwg living standard, although discussions about future standardization are ongoing.
CanvasRenderingContext2D.restore() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // save the default state ctx.save(); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); // restore the default state ctx.restore(); ctx.fillrect(150, 40, 100, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.restore' in that spec...
CanvasRenderingContext2D.save() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // save the default state ctx.save(); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); // restore the default state ctx.restore(); ctx.fillrect(150, 40, 100, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.save' in that specifi...
CanvasRenderingContext2D.setTransform() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.settransform(1, .2, .8, 1, 0, 0); ctx.fillrect(0, 0, 100, 100); result retrieving and passing a dommatrix object in the following example, we have two <canvas> elements.
CanvasRenderingContext2D.shadowBlur - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowblur = 15; // rectangle ctx.fillstyle = 'blue'; ctx.fillrect(20, 20, 150, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowblur' in that specification.
CanvasRenderingContext2D.shadowOffsetX - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowoffsetx = 25; ctx.shadowblur = 10; // rectangle ctx.fillstyle = 'blue'; ctx.fillrect(20, 20, 150, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowoffsetx' in that specification.
CanvasRenderingContext2D.shadowOffsetY - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowoffsety = 25; ctx.shadowblur = 10; // rectangle ctx.fillstyle = 'blue'; ctx.fillrect(20, 20, 150, 80); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowoffsety' in that specification.
CanvasRenderingContext2D.textBaseline - Web APIs
html <canvas id="canvas" width="550" height="500"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const baselines = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom']; ctx.font = '36px serif'; ctx.strokestyle = 'red'; baselines.foreach(function (baseline, index) { ctx.textbaseline = baseline; const y = 75 + index * 75; ctx.beginpath(); ctx.moveto(0, y + 0.5); ctx.lineto(550, y + 0.5); ctx.stroke(); ctx.f...
CanvasRenderingContext2D.transform() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.transform(1, .2, .8, 1, 0, 0); ctx.fillrect(0, 0, 100, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.transform' in that specification.
CanvasRenderingContext2D.translate() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // moved square ctx.translate(110, 30); ctx.fillstyle = 'red'; ctx.fillrect(0, 0, 80, 80); // reset current transformation matrix to the identity matrix ctx.settransform(1, 0, 0, 1, 0, 0); // unmoved square ctx.fillstyle = 'gray'; ctx.fillrect(0, 0, 80, 80); result the moved square is red, and the unmoved square is gray.
Compositing example - Web APIs
tyle = "#f00"; ctx.fillrect(0,0,30,30) ctx.fill(); }; var colorsphere = function(element) { var ctx = canvas1.getcontext("2d"); var width = 360; var halfwidth = width / 2; var rotate = (1 / 360) * math.pi * 2; // per degree var offset = 0; // scrollbar offset var oleft = -20; var otop = -20; for (var n = 0; n <= 359; n ++) { var gradient = ctx.createlineargradient(oleft + halfwidth, otop, oleft + halfwidth, otop + halfwidth); var color = color.hsv_rgb({ h: (n + 300) % 360, s: 100, v: 100 }); gradient.addcolorstop(0, "rgba(0,0,0,0)"); gradient.addcolorstop(0.7, "rgba("+color.r+","+color.g+","+color.b+",1)"); gradient.addcolorstop(1, "rgba(255,255,255,1)"); ctx.beginpath(); ctx.moveto(oleft + halfw...
Compositing and clipping - Web APIs
function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.fillrect(0, 0, 150, 150); ctx.translate(75, 75); // create a circular clipping path ctx.beginpath(); ctx.arc(0, 0, 60, 0, math.pi * 2, true); ctx.clip(); // draw background var lingrad = ctx.createlineargradient(0, -75, 0, 75); lingrad.addcolorstop(0, '#232256'); lingrad.addcolorstop(1, '#143778'); ctx.fillstyle = lingrad; ctx.fi...
Hit regions and accessibility - Web APIs
<canvas id="canvas"></canvas> <script> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: 'circle'}); canvas.addeventlistener('mousemove', function(event) { if (event.region) { alert('hit region: ' + event.region); } }); </script> the addhitregion() method also takes a control option to route events to an element (that is a de...
Using channel messaging - Web APIs
var input = document.getelementbyid('message-input'); var output = document.getelementbyid('message-output'); var button = document.queryselector('button'); var iframe = document.queryselector('iframe'); var channel = new messagechannel(); var port1 = channel.port1; // wait for the iframe to load iframe.addeventlistener("load", onload); function onload() { // listen for button clicks button.addeventlistener('click',...
ChildNode.remove() - Web APIs
WebAPIChildNoderemove
syntax node.remove(); example using remove() <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <div id="div-03">here is div-03</div> var el = document.getelementbyid('div-02'); el.remove(); // removes the div with the 'div-02' id childnode.remove() is unscopable the remove() method is not scoped into the with statement.
ChildNode - Web APIs
WebAPIChildNode
previouselementsibling and nextelementsibling are now defined on the latter.
Clients.claim() - Web APIs
WebAPIClientsclaim
the claim() method causes those pages to be controlled immediately.
Clipboard.readText() - Web APIs
navigator.clipboard.readtext().then( cliptext => document.getelementbyid("outbox").innertext = cliptext); specifications specification status comment clipboard api and eventsthe definition of 'readtext()' in that specification.
Console.profileEnd() - Web APIs
calling this api immediately after console.profile() can cause it to not work.
CustomElementRegistry.get() - Web APIs
examples customelements.define('my-paragraph', class extends htmlelement { constructor() { super(); let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(templatecontent.clonenode(true)); } }) // return a reference to the my-paragraph constructor let ctor = customelements.get('my-paragraph'); specifications specification status comment html living standardthe definiti...
CustomElementRegistry - Web APIs
if such a custom element is already defined, the returned promise is immediately fulfilled.
DOMImplementation.createDocument() - Web APIs
example var doc = document.implementation.createdocument ('http://www.w3.org/1999/xhtml', 'html', null); var body = document.createelementns('http://www.w3.org/1999/xhtml', 'body'); body.setattribute('id', 'abc'); doc.documentelement.appendchild(body); alert(doc.getelementbyid('abc')); // [object htmlbodyelement] specifications specification status comment domthe definition of 'domimplementation.createdocument' in that specification.
DOMMatrixReadOnly.flipX() - Web APIs
const flipped = document.getelementbyid('flipped'); const matrix = new dommatrixreadonly(); const flippedmatrix = matrix.flipx(); flipped.setattribute('transform', flippedmatrix.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.flipx()' in that specification.
DOMParser - Web APIs
WebAPIDOMParser
s null on unsupported types if ((new domparser()).parsefromstring("", "text/html")) { // text/html parsing is natively supported return; } } catch (ex) {} proto.parsefromstring = function(markup, type) { if (/^\s*text\/html\s*(?:;|$)/i.test(type)) { var doc = document.implementation.createhtmldocument(""); if (markup.tolowercase().indexof('<!doctype') > -1) { doc.documentelement.innerhtml = markup; } else { doc.body.innerhtml = markup; } return doc; } else { return nativeparse.apply(this, arguments); } }; }(domparser)); specifications specification status comment html living standardthe definition of 'dom parsing' in that specification.
DOMTokenList.remove() - Web APIs
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.textcontent = classes; specifications specification status comment domthe definition of 'remove()' in that specification.
DOMTokenList.replace() - Web APIs
if the first token doesn't exist, replace() returns false immediately, without adding the new token to the token list.
DOMTokenList.supports() - Web APIs
example let iframe = document.getelementbyid('display'); if (iframe.sandbox.supports('an-upcoming-feature')) { // support code for mystery future feature } else { // fallback code } if (iframe.sandbox.supports('allow-scripts')) { // instruct frame to run javascript // // (note: this feature is well-supported; this is just an example!) // } specifications specification status comment crede...
DOMTokenList - Web APIs
such a set is returned by element.classlist, htmllinkelement.rellist, htmlanchorelement.rellist, htmlareaelement.rellist, htmliframeelement.sandbox, or htmloutputelement.htmlfor.
DataTransfer.dropEffect - Web APIs
"text", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } specifications specification status comment html living standardthe definition of 'dropeffect' i...
DataTransfer.effectAllowed - Web APIs
etdata("text", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } function dragover_handler(ev) { console.log("dragover: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>examples <code>datatransfer</code>.{<code>dropeffect</code>, <code>effectallowed</code>} properties</h1> <d...
DataTransfer.getData() - Web APIs
owdropevent) { allowdropevent.target.style.color = 'blue'; allowdropevent.preventdefault(); } function drag(dragevent) { dragevent.datatransfer.setdata("text", dragevent.target.id); dragevent.target.style.color = 'green'; } function drop(dropevent) { dropevent.preventdefault(); var data = dropevent.datatransfer.getdata("text"); dropevent.target.appendchild(document.getelementbyid(data)); document.getelementbyid("drag").style.color = 'black'; } result specifications specification status comment html living standardthe definition of 'getdata()' in that specification.
DataTransfer.items - Web APIs
will // know which element to add to its tree ev.datatransfer.setdata("text/plain", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: target.id = " + ev.target.id); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); // print each format type if (ev.datatransfer.types != null) { for (var i=0; i < ev.datatransfer.types.length; i++) { console.log("...
DataTransfer.setData() - Web APIs
use the event target's id for the data ev.datatransfer.setdata("text/plain", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); // get the data, which is the id of the drop target var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); // clear the drag data cache (for all formats/types) ev.datatransfer.cleardata(); } </script> <body> <h1>examples of <code>datatransfer</code>: <code>setdata()</code>, <code>getdata()</code>, <code>cleardata()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the sel...
DataTransfer.setDragImage() - Web APIs
var img = new image(); img.src = 'example.gif'; ev.datatransfer.setdragimage(img, 10, 10); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); // get the data, which is the id of the drop target var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } </script> <body> <h1>example of <code>datatransfer.setdragimage()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </...
DataTransfer.types - Web APIs
will // know which element to add to its tree ev.datatransfer.setdata("text/plain", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: target.id = " + ev.target.id); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); // print each format type if (ev.datatransfer.types != null) { for (var i=0; i < ev.datatransfer.types.length; i++) { console.log("...
DataTransferItem.getAsFile() - Web APIs
function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html console.log("...
DataTransferItem.getAsString() - Web APIs
function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html console.log("...
DataTransferItem.kind - Web APIs
function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html console.log("...
DataTransferItem.type - Web APIs
function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; for (var i = 0; i < data.length; i += 1) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html console.log("...
DataTransferItem.webkitGetAsEntry() - Web APIs
let dropzone = document.getelementbyid("dropzone"); let listing = document.getelementbyid("listing"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = document.createelement("ul"); container.appendchild(directorycontainer); d...
DataTransferItemList.DataTransferItem() - Web APIs
ction drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html data[i].getasstring(function (s){ console.log("...
DataTransferItemList.add() - Web APIs
on drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html data[i].getasstring(function (s){ console.log("...
DataTransferItemList.clear() - Web APIs
on drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html data[i].getasstring(function (s){ console.log("...
DataTransferItemList.length - Web APIs
ction drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html data[i].getasstring(function (s){ console.log("...
DataTransferItemList.remove() - Web APIs
on drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.target.appendchild(document.getelementbyid(s)); }); } else if ((data[i].kind == 'string') && (data[i].type.match('^text/html'))) { // drag data item is html data[i].getasstring(function (s){ console.log("...
DelayNode.delayTime - Web APIs
if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time.
DelayNode - Web APIs
WebAPIDelayNode
if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time.
DeviceOrientationEvent.DeviceOrientationEvent() - Web APIs
absolute: a boolean that indicates whether or not the device is providing orientation data absolutely.
DeviceOrientationEvent.absolute - Web APIs
indicates whether or not the device is providing orientation data absolutely (that is, in reference to the earth's coordinate frame) or using some arbitrary frame determined by the device.
DeviceOrientationEvent - Web APIs
properties deviceorientationevent.absolute read only a boolean that indicates whether or not the device is providing orientation data absolutely.
Document: DOMContentLoaded event - Web APIs
the domcontentloaded event fires when the initial html document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
Document.URL - Web APIs
WebAPIDocumentURL
syntax const url = document.url example javascript document.getelementbyid("url").textcontent = document.url; html <p id="urltext"> url:<br/> <span id="url">url goes here</span> </p> result specifications specification status comment domthe definition of 'document.url' in that specification.
Document.adoptNode() - Web APIs
example const iframe = document.queryselector('iframe'); const iframeimages = iframe.contentdocument.queryselectorall('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().
Document.anchors - Web APIs
WebAPIDocumentanchors
example if (document.anchors.length >= 5) { dump("found too many anchors"); } the following is an example that auto populates a table of contents with every anchor on the page: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>test</title> <script> function init() { var toc = document.getelementbyid("toc"); var i, li, newanchor; for (i = 0; i < document.anchors.length; i++) { li = document.createelement("li"); newanchor = document.createelement('a'); newanchor.href = "#" + document.anchors[i].name; newanchor.innerhtml = document.anchors[i].text; li.appendchild(newanchor); toc.appendchild(li); } } </script> </head> <body onload="init()"> <h1>title</h1> ...
Document.caretRangeFromPoint() - Web APIs
point) { range = document.caretrangefrompoint(e.clientx, e.clienty); textnode = range.startcontainer; offset = range.startoffset; } // only split text_nodes if (textnode && textnode.nodetype == 3) { let replacement = textnode.splittext(offset); let br = document.createelement('br'); textnode.parentnode.insertbefore(br, replacement); } } let paragraphs = document.getelementsbytagname("p"); for (let i = 0; i < paragraphs.length; i++) { paragraphs[i].addeventlistener('click', insertbreakatpoint, false); } result ...
Document.cookie - Web APIs
WebAPIDocumentcookie
the reason for the syntax of the document.cookie accessor property is due to the client-server nature of cookies, which differs from other client-client storage methods (like, for instance, localstorage): the server tells the client to store a cookie http/1.0 200 ok content-type: text/html set-cookie: cookie_name1=cookie_value1 set-cookie: cookie_name2=cookie_value2; expires=sun, 16 jul 3567 06:23:41 gmt [content of the page here] the client sends back to the server its cookies previously stored get /sample_page.html http/1.1 host: www.example.org cookie: cookie_name1=cookie_value1; cookie_name2=cookie_value...
Document.createAttribute() - Web APIs
example var node = document.getelementbyid("div1"); var a = document.createattribute("my_attrib"); a.value = "newval"; node.setattributenode(a); console.log(node.getattribute("my_attrib")); // "newval" specifications specification status comment domthe definition of 'document.createattribute()' in that specification.
Document.createCDATASection() - Web APIs
example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml') var cdata = docu.createcdatasection('some <cdata> data & then some'); docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err.
Document.createComment() - Web APIs
example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml'); var comment = docu.createcomment('this is a not-so-secret comment in your document'); docu.getelementsbytagname('xml')[0].appendchild(comment); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><!--this is a not-so-secret comment in your document--></xml> specifications specification status comment domthe definition of 'document.createcomment' in that specification.
Document.createDocumentFragment() - Web APIs
html <ul id="ul"> </ul> javascript var element = document.getelementbyid('ul'); // assuming ul exists var fragment = document.createdocumentfragment(); var browsers = ['firefox', 'chrome', 'opera', 'safari', 'internet explorer']; browsers.foreach(function(browser) { var li = document.createelement('li'); li.textcontent = browser; fragment.appendchild(li); }); element.appendchild(fragment); result specifications specification ...
Document.createElementNS() - Web APIs
m two different namespaces within a single document: <?xml version="1.0"?> <page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml" title="||working with elements||" onload="init()"> <script type="application/javascript"><![cdata[ let container; let newdiv; let txtnode; function init(){ container = document.getelementbyid("containerbox"); newdiv = document.createelementns("http://www.w3.org/1999/xhtml", "div"); txtnode = document.createtextnode("this is text that was constructed dynamically with createelementns and createtextnode then inserted into the document using appendchild."); newdiv.appendchild(txtnode); container.appendchild(newdiv); } ]]></script> <vbox id="containerbox" flex="1">...
Document.createTextNode() - Web APIs
example <!doctype html> <html lang="en"> <head> <title>createtextnode example</title> <script> function addtextnode(text) { var newtext = document.createtextnode(text), p1 = document.getelementbyid("p1"); p1.appendchild(newtext); } </script> </head> <body> <button onclick="addtextnode('yes!
Document.createTouch() - Web APIs
var target = document.getelementbyid("target"); var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createtouch(window, target, 2, 25, 30, 45, 50); specifications specification status comment touch eventsthe definition of 'document.createtouch()' in that specification.
Document.createTouchList() - Web APIs
var target = document.getelementbyid("target"); // create some touch points var touch1 = document.createtouch(window, target, 1, 15, 20, 35, 40); var touch2 = document.createtouch(window, target, 2, 25, 30, 45, 50); // create an empty touchlist objects var list0 = document.createtouchlist(); // create a touchlist with only one touch object var list1 = document.createtouchlist(touch1); // create a list with two touch obj...
Document.currentScript - Web APIs
syntax var curscriptelement = document.currentscript; example this example checks to see if the script is being executed asynchronously: if (document.currentscript.async) { console.log("executing asynchronously"); } else { console.log("executing synchronously"); } view live examples specifications specification status comment html living standardthe definition of 'document.current...
Document.documentURI - Web APIs
syntax const uri = document.documenturi example javascript document.getelementbyid("url").textcontent = document.documenturi; html <p id="urltext"> url:<br/> <span id="url">url goes here</span> </p> result specifications specification status comment domthe definition of 'documenturi' in that specification.
Document.exitFullscreen() - Web APIs
document.onclick = function (event) { if (document.fullscreenelement) { document.exitfullscreen() .then(() => console.log("document exited form full screen mode")) .catch((err) => console.error(err)) } else { document.documentelement.requestfullscreen(); } } note: for a more complete example, see the example in element.requestfullscreen().
Document: fullscreenchange event - Web APIs
the fullscreenchange event is fired immediately after the browser switches into or out of full-screen mode.
Document.getBoxObjectFor() - Web APIs
example var mydiv = document.getelementbyid("mydiv"), boxobj = document.getboxobjectfor (mydiv); alert ( "x:" + boxobj.x + ", y:" + boxobj.y + ", width:" + boxobj.width + ", height:" + boxobj.height ); notes specified in nsixuldocument.idl ...
Document.hasFocus() - Web APIs
WebAPIDocumenthasFocus
html <p id="log">awaiting focus check.</p> <button onclick="openwindow()">open a new window</button> javascript function checkpagefocus() { let body = document.queryselector('body'); let log = document.getelementbyid('log'); if (document.hasfocus()) { log.textcontent = 'this document has the focus.'; body.style.background = '#fff'; } else { log.textcontent = 'this document does not have the focus.'; body.style.background = '#ccc'; } } function openwindow() { window.open('https://developer.mozilla.org/', 'mdn', 'width=640,height=320,left=150,top=150'); } // check page focu...
Document.height - Web APIs
WebAPIDocumentheight
syntax pixels = document.height example // alert document height alert(document.height); alternatives document.body.clientheight document.documentelement.clientheight document.documentelement.scrollheight specification html5 ...
Document.importNode() - Web APIs
example const iframe = document.queryselector("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().
Document: keypress event - Web APIs
<p>press inside this iframe first to focus it, then try pressing keys on the keyboard.</p> <p id="log"></p> const log = document.getelementbyid('log'); document.addeventlistener('keypress', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeypress equivalent document.onkeypress = logkey; specifications specification status ui events working draft ...
Document: keyup event - Web APIs
by clicking in it), then try pressing some keys.</p> <p id="log"></p> const log = document.getelementbyid('log'); document.addeventlistener('keyup', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeyup equivalent document.onkeyup = logkey; specifications specification status ui events working draft ...
Document.onfullscreenerror - Web APIs
document.documentelement.requestfullscreen(); specifications specification status comment fullscreen apithe definition of 'onfullscreenerror' in that specification.
Document.ononline - Web APIs
WebAPIDocumentononline
window.navigator.online returns boolean true if the browser is online and false if it is definitely offline (disconnected from the network).
Document.queryCommandState() - Web APIs
the querycommandstate() method will tell you if the current selection has a certain document.execcommand() command applied.
Document.querySelector() - Web APIs
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 ("\").
Document.registerElement() - Web APIs
here is one way to add content to the new tag: var mytag = document.getelementsbytagname("my-tag")[0]; mytag.textcontent = "i am a my-tag element."; ...
Document.scrollingElement - Web APIs
in standards mode, this is the root element of the document, document.documentelement.
Document.styleSheetSets - Web APIs
example given an <ul> (list) element with the id "sheetlist", you can populate it with the names of all the available style sheet sets with code like this: let list = document.getelementbyid('sheetlist'); let sheets = document.stylesheetsets; list.innerhtml = ''; for (let i = 0; i < sheets.length; i++) { let item = document.createelement('li'); item.innerhtml = sheets[i]; list.appendchild(item); } notes the list of available style sheet sets is constructed by enumerating all the style sheets available for the document, in the order in which they're listed in the d...
Document.width - Web APIs
WebAPIDocumentwidth
syntax pixels = document.width; example function init() { alert("the width of the document is " + document.width + " pixels."); } alternatives document.body.clientwidth /* width of <body> */ document.documentelement.clientwidth /* width of <html> */ window.innerwidth /* window's width */ specification html5 ...
DocumentFragment.querySelector() - Web APIs
to match id or selectors that do not follow the css syntax (by using semicolon or space inappropriately for example), it's mandatory to escape the wrong character with a double back slash: <div id="foo\bar"></div> <div id="foo:bar"></div> <script> document.queryselector('#foo\bar') // does not match anything document.queryselector('#foo\\\\bar') // match the first div document.queryselector('#foo:bar') // does not match anything document.queryselector('#foo\\:bar') // match the second d...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
document.caretrangefrompoint(e.clientx, e.clienty); textnode = range.startcontainer; offset = range.startoffset; } // only split text_nodes if (textnode.nodetype == 3) { var replacement = textnode.splittext(offset); var br = document.createelement('br'); textnode.parentnode.insertbefore(br, replacement); } } window.onload = function (){ var paragraphs = document.getelementsbytagname("p"); for (i=0 ; i < paragraphs.length; i++) { paragraphs[i].addeventlistener("click", insertbreakatpoint, false); } }; specifications specification status comment css object model (cssom) view modulethe definition of 'caretpositionfrompoint()' in that specification.
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
example html <div> <p>some text</p> </div> <p>elements at point 30, 20:</p> <div id="output"></div> javascript let output = document.getelementbyid("output"); if (document.elementsfrompoint) { let elements = document.elementsfrompoint(30, 20); for (var i = 0; i < elements.length; i++) { output.textcontent += elements[i].localname; if (i < elements.length - 1) { output.textcontent += " < "; } } } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not support <code>document.elements...
DocumentOrShadowRoot.getSelection() - Web APIs
htmlinputelement.setselectionrange()) could be used to work around this.
DocumentOrShadowRoot.msElementsFromRect() - Web APIs
var nodelist = document.mselementsfromrect(x,y,width,height) var nodelist = document.mselementsfrompoint(x,y) the returned nodelist is sorted by z-index so that you can tell the relative stacking order of the elements.
DocumentOrShadowRoot.nodeFromPoint() - Web APIs
examples html content <div> <p>some text</p> </div> <p>top node at point 30, 20:</p> <div id="output"></div> javascript content var output = document.getelementbyid("output"); if (document.nodefrompoint) { var node = document.nodefrompoint(30, 20); output.textcontent += node.localname; } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not support <code>document.nodefrompoint()</code>" + "</span>"; } specifications not part of any specification at present.
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
example html content <div> <p>some text</p> </div> <p>nodes at point 30, 20:</p> <div id="output"></div> javascript content var output = document.getelementbyid("output"); if (document.nodesfrompoint) { var nodes = document.nodesfrompoint(30, 20); for(var i = 0; i < nodes.length; i++) { output.textcontent += nodes[i].localname; if (i < nodes.length - 1) { output.textcontent += " < "; } } } else { output.innerhtml = "<span style=\"color: red;\">" + "browser does not support <code>document.nodesfrompoint()</code>" + ...
DragEvent - Web APIs
WebAPIDragEvent
dragover this event is fired continuously when an element or text selection is being dragged and the mouse pointer is over a valid drop target (every 50 ms when mouse is not moving else much faster between 5 ms (slow movement) and 1ms (fast movement) approximately.
EffectTiming.direction - Web APIs
examples in the forgotten key example, alice waves her arm up and down by passing her an alternate value for her direction property: // get alice's arm, and wave it up and down document.getelementbyid("alice_arm").animate([ { transform: 'rotate(10deg)' }, { transform: 'rotate(-40deg)' } ], { easing: 'steps(2, end)', iterations: infinity, direction: 'alternate', duration: 600 }); specifications specification status comment web animationsthe definition of 'direction' in that specification.
EffectTiming.easing - Web APIs
examples in the red queen's race example, we animate alice and the red queen by passing an easing of steps(7, end) to animate(): // define the key frames var spriteframes = [ { transform: 'translatey(0)' }, { transform: 'translatey(-100%)' } ]; // get the element that represents alice and the red queen var redqueen_alice_sprite = document.getelementbyid('red-queen_and_alice_sprite'); // animate alice and the red queen using steps() var redqueen_alice = redqueen_alice_sprite.animate( spriteframes, { easing: 'steps(7, end)', direction: "reverse", duration: 600, playbackrate: 1, iterations: infinity }); specifications specification status comment web animationsthe definition of 'easing' in that specific...
Element: blur event - Web APIs
html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.addeventlistener('blur', (event) => { event.target.style.background = ''; }, true); result specifications specification status comment ui events working draft added info that this event is composed.
Element.className - Web APIs
WebAPIElementclassName
example let el = document.getelementbyid('item'); if (el.classname === 'active'){ el.classname = 'inactive'; } else { el.classname = 'active'; } notes the name classname is used for this property instead of class because of conflicts with the "class" keyword in many languages which are used to manipulate the dom.
Element.clientHeight - Web APIs
syntax var intelemclientheight = element.clientheight; intelemclientheight is an integer corresponding to the clientheight of element in pixels.
Element.clientTop - Web APIs
WebAPIElementclientTop
this is because the offsettop indicates the location of the top of the border (not the margin) while the client area starts immediately below the border, (client area includes padding.) therefore, the clienttop value will always equal the integer portion of the .getcomputedstyle() value for "border-top-width".
Element.clientWidth - Web APIs
syntax var intelemclientwidth = element.clientwidth; intelemclientwidth is an integer corresponding to the clientwidth of element in pixels.
Element: contextmenu event - Web APIs
html <p id="nocontextmenu">the context menu has been disabled on this paragraph.</p> <p>but it has not been disabled on this one.</p> javascript nocontext = document.getelementbyid('nocontextmenu'); nocontext.addeventlistener('contextmenu', e => { e.preventdefault(); }); result specifications specification status comment html living standardthe definition of 'contextmenu' in that specification.
Element: focus event - Web APIs
html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.addeventlistener('blur', (event) => { event.target.style.background = ''; }, true); result specifications specification status comment ui events working draft added info that this event is composed.
Element: focusin event - Web APIs
bubbles yes cancelable no interface focusevent event handler property onfocusin sync / async sync composed yes examples live example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addeventlistener('focusout', (event) => { event.target.style.background = ''; }); result specifications specification status comment ui events working draft added info that this event is composed.
Element: focusout event - Web APIs
bubbles yes cancelable no interface focusevent event handler property onfocusout sync / async sync composed yes examples live example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const form = document.getelementbyid('form'); form.addeventlistener('focusin', (event) => { event.target.style.background = 'pink'; }); form.addeventlistener('focusout', (event) => { event.target.style.background = ''; }); result specifications specification status comment ui events working draft added info that this event is composed.
Element.getAttribute() - Web APIs
examples const div1 = document.getelementbyid('div1'); const align = div1.getattribute('align'); alert(align); // shows the value of align for the element with id="div1" description lower casing when called on an html element in a dom flagged as an html document, getattribute() lower-cases its argument before proceeding.
Element.getAttributeNode() - Web APIs
example // html: <div id="top" /> let t = document.getelementbyid("top"); let idattr = t.getattributenode("id"); alert(idattr.value == "top") notes when called on an html element in a dom flagged as an html document, getattributenode lower-cases its argument before proceeding.
Element.getAttributeNodeNS() - Web APIs
== example == tbd the example needs to be fixed pre> // html: <div id="top" /> t = document.getelementbyid("top"); specialnode = t.getattributenodens( "http://www.mozilla.org/ns/specialspace", "id"); // inode.value = "full-top" </pre notes getattributenodens is more specific than getattributenode in that it allows you to specify attributes that are part of a particular namespace.
Element.hasAttribute() - Web APIs
example var foo = document.getelementbyid("foo"); if (foo.hasattribute("bar")) { // do something } polyfill ;(function(prototype) { prototype.hasattribute = prototype.hasattribute || function(name) { return !!(this.attributes[name] && this.attributes[name].specified); } })(element.prototype); notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for ...
Element.hasAttributeNS() - Web APIs
example // check that the attribute exists before you set a value var d = document.getelementbyid("div1"); if (d.hasattributens( "http://www.mozilla.org/ns/specialspace/", "special-align")) { d.setattribute("align", "center"); } notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namespace-awar...
Element.hasAttributes() - Web APIs
examples let foo = document.getelementbyid('foo'); if (foo.hasattributes()) { // do something with 'foo.attributes' } polyfill ;(function(prototype) { prototype.hasattributes = prototype.hasattributes || function() { return (this.attributes.length > 0); } })(element.prototype); specifications specification status comment domthe definition of 'element.hasattributes()' in that specification.
Element.id - Web APIs
WebAPIElementid
the id is often used with getelementbyid() to retrieve a particular element.
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
document.documentelement.innerhtml = "<pre>" + document.documentelement.innerhtml.replace(/</g,"&lt;") + "</pre>"; operational details what exactly happens when you set value of innerhtml?
Element.insertAdjacentHTML() - Web APIs
example // <div id="one">one</div> var d1 = document.getelementbyid('one'); d1.insertadjacenthtml('afterend', '<div id="two">two</div>'); // at this point, the new structure is: // <div id="one">one</div><div id="two">two</div> notes security considerations when inserting html into a page by using insertadjacenthtml(), be careful not to use user input that hasn't been escaped.
Element: keydown event - Web APIs
<input placeholder="click here, then press down a key." size="40"> <p id="log"></p> const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('keydown', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeydown equivalent input.onkeydown = logkey; specifications specification status ui events working draft ...
Element: keypress event - Web APIs
<div> <label for="sample">focus the input and type something:</label> <input type="text" name="text" id="sample"> </div> <p id="log"></p> const log = document.getelementbyid('log'); const input = document.queryselector('input'); input.addeventlistener('keypress', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeypress equivalent input.onkeypress = logkey; specifications specification status ui events working draft ...
Element: keyup event - Web APIs
<input placeholder="click here, then press and release a key." size="40"> <p id="log"></p> const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('keyup', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeyup equivalent input.onkeyup = logkey; specifications specification status ui events working draft ...
Element.localName - Web APIs
WebAPIElementlocalName
example (must be served with xml content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![cdata[ function test() { var text = document.getelementbyid('text'); var circle = document.getelementbyid('circle'); text.value = "<svg:circle> has:\n" + "localname = '" + circle.localname + "'\n" + "namespaceuri = '" + circle.namespaceuri + "'"; } ]]></script> </head> <body onload="test()"> <svg:svg version="1.1" width="100px" height="100px" viewbox="0 0 100 100"> <svg:circle cx="50" c...
Element.matches() - Web APIs
WebAPIElementmatches
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 will log "the philippine eagle is endangered!" to the console, since the element has indeed a class attribute with value endangered.
Element: mousedown event - Web APIs
html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
Element: mouseenter event - Web APIs
#mousetarget { box-sizing: border-box; width:15rem; border:1px solid #333; } javascript var entereventcount = 0; var leaveeventcount = 0; const mousetarget = document.getelementbyid('mousetarget'); const unorderedlist = document.getelementbyid('unorderedlist'); mousetarget.addeventlistener('mouseenter', e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener('mouseleave', e => { mousetarget.style.border = '1px solid #333'; leaveeventcount+...
Element: mouseleave event - Web APIs
#mousetarget { box-sizing: border-box; width:15rem; border:1px solid #333; } javascript var entereventcount = 0; var leaveeventcount = 0; const mousetarget = document.getelementbyid('mousetarget'); const unorderedlist = document.getelementbyid('unorderedlist'); mousetarget.addeventlistener('mouseenter', e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener('mouseleave', e => { mousetarget.style.border = '1px solid #333'; leaveeventcount+...
Element: mousemove event - Web APIs
html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
Element: mouseout event - Web APIs
html <ul id="test"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> javascript let test = document.getelementbyid("test"); // briefly make the list purple when the mouse moves off the // <ul> element test.addeventlistener("mouseleave", function( event ) { // highlight the mouseleave target event.target.style.color = "purple"; // reset the color after a short delay settimeout(function() { event.target.style.color = ""; }, 1000); }, false); // briefly make an <li> orange when the mous...
Element: mouseover event - Web APIs
html <ul id="test"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> javascript let test = document.getelementbyid("test"); // this handler will be executed only once when the cursor // moves over the unordered list test.addeventlistener("mouseenter", function( event ) { // highlight the mouseenter target event.target.style.color = "purple"; // reset the color after a short delay settimeout(function() { event.target.style.color = ""; }, 500); }, false); // this handler will be execut...
Element: mouseup event - Web APIs
html <h1>drawing with mouse events</h1> <canvas id="mypics" width="560" height="360"></canvas> css canvas { border: 1px solid black; width: 560px; height: 360px; } javascript // when true, moving the mouse draws on the canvas let isdrawing = false; let x = 0; let y = 0; const mypics = document.getelementbyid('mypics'); const context = mypics.getcontext('2d'); // event.offsetx, event.offsety gives the (x,y) offset from the edge of the canvas.
Element.name - Web APIs
WebAPIElementname
name can be used in the document.getelementsbyname() method, a form and with the form elements collection.
Element.onfullscreenerror - Web APIs
syntax targetelement.onfullscreenerror = fullscreenerrorhandler; value an error handler for the fullscreenerror event.
Element: overflow event - Web APIs
s <div id="wrapper"> <div id="child"></div> </div> <br/> <label><input type="checkbox" id="toggle" checked/> overflow</label> <style> #wrapper { width: 20px; height: 20px; background: #000; padding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getelementbyid("wrapper"), child = document.getelementbyid("child"), toggle = document.getelementbyid("toggle"); wrapper.addeventlistener("overflow", function( event ) { console.log( event ); }, false); wrapper.addeventlistener("underflow", function( event ) { console.log( event ); }, false); toggle.addeventlistener("change", function( event ) { if ( event.tar...
Element.querySelector() - Web APIs
html <div> <h5>original content</h5> <p> inside paragraph <span>inside span</span> inside paragraph </p> </div> <div> <h5>output</h5> <div id="output"></div> </div> javascript var baseelement = document.queryselector("p"); document.getelementbyid("output").innerhtml = (baseelement.queryselector("div span").innerhtml); result the result looks like this: notice how the "div span" selector still successfully matches the <span> element, even though the baseelement's child nodes do not include the div element (it is still part of the specified selector).
Element.removeAttribute() - Web APIs
aware methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) getattributens getattributenode getattributenodens hasattribute (dom 2) hasattributens - - removeattribute (dom 1) removeattributens removeattributenode - example // given: <div id="div1" align="left" width="200px"> document.getelementbyid("div1").removeattribute("align"); // now: <div id="div1" width="200px"> specifications specification status comment domthe definition of 'element" removeattribute' in that specification.
Element.removeAttributeNS() - Web APIs
example // given: // <div id="div1" xmlns:special="http://www.mozilla.org/ns/specialspace" // special:specialalign="utterleft" width="200px" /> d = document.getelementbyid("div1"); d.removeattributens("http://www.mozilla.org/ns/specialspace", "specialalign"); // now: <div id="div1" width="200px" /> notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namespace-aware methods for deali...
Element.removeAttributeNode() - Web APIs
example // given: <div id="top" align="center" /> var d = document.getelementbyid("top"); var d_align = d.getattributenode("align"); d.removeattributenode(d_align); // align is now removed: <div id="top" /> notes if the removed attribute has a default value, it is immediately replaced.
Element.scrollIntoView() - Web APIs
example var element = document.getelementbyid("box"); element.scrollintoview(); element.scrollintoview(false); element.scrollintoview({block: "end"}); element.scrollintoview({behavior: "smooth", block: "end", inline: "nearest"}); notes the element may not be scrolled completely to the top or bottom depending on the layout of other elements.
Element.scrollIntoViewIfNeeded() - Web APIs
example var element = document.getelementbyid("my-el"); element.scrollintoviewifneeded(); element.scrollintoviewifneeded(true); // centers the element in the visible area specifications not part of any specification.
Element.scrollLeft - Web APIs
example html <div id="container"> <div id="content">click the button to slide right!</div> </div> <button id="slide" type="button">slide right</button> css #container { width: 100px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; } #content { width: 250px; background-color: #ccc; } javascript const button = document.getelementbyid('slide'); button.onclick = function () { document.getelementbyid('container').scrollleft += 20; }; result specifications specification status comment css object model (cssom) view modulethe definition of 'scrollleft' in that specification.
Element.scrollTop - Web APIs
WebAPIElementscrollTop
var intelemscrolltop = someelement.scrolltop; after running this code, intelemscrolltop is an integer corresponding to the number of pixels that the element's content has been scrolled upwards.
Element.scrollWidth - Web APIs
margin-bottom: 2em; } </style> </head> <body> <div id="adiv"> foobar-foobar-foobar-foobar </div> <button id="abutton"> check for overflow </button> <div id="anotherdiv"> foobar-foobar-foobar-foobar </div> <button id="anotherbutton"> check for overflow </button> </body> <script> var buttonone = document.getelementbyid('abutton'), buttontwo = document.getelementbyid('anotherbutton'), divone = document.getelementbyid('adiv'), divtwo = document.getelementbyid('anotherdiv'); //check to determine if an overflow is happening function isoverflowing(element) { return (element.scrollwidth > element.offsetwidth); } function alertoverflow(element) { if (isoverflowing...
Element: select event - Web APIs
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.queryselector('input'); input.addeventlistener('select', logselection); onselect equivalent you can also set up the event handler using the onselect property: input.onselect = logselection; spec...
Element.setAttributeNS() - Web APIs
example let d = document.getelementbyid('d1'); d.setattributens('http://www.mozilla.org/ns/specialspace', 'spec:align', 'center'); notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namespace-aware methods for dealing with attr nodes directly (seldom u...
Element.setAttributeNode() - Web APIs
html <div id="one" align="left">one</div> <div id="two">two</div> javascript let d1 = document.getelementbyid('one'); let d2 = document.getelementbyid('two'); let a = d1.getattributenode('align'); d2.setattributenode(a.clonenode(true)); // returns: 'left' alert(d2.attributes[1].value); notes if the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned.
Element.setAttributeNodeNS() - Web APIs
example // <div id="one" xmlns:myns="http://www.mozilla.org/ns/specialspace" // myns:special-align="utterleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.getelementbyid("one"); var d2 = document.getelementbyid("two"); var a = d1.getattributenodens(myns, "special-align"); d2.setattributenodens(a.clonenode(true)); alert(d2.attributes[1].value) // returns: `utterleft' notes if the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is returned.
Element: show event - Web APIs
bubbles no cancelable no interface event event handler property onshow examples <div contextmenu="test"></div> <menu type="context" id="test"> <menuitem label="alert" onclick="alert('the alert label has been clicked')" /> </menu> <script> document.getelementbyid("test").addeventlistener("show", function(e){ alert("the context menu will be displayed"); }, false); </script> specifications specification status html5the definition of 'show event' in that specification.
Element.tagName - Web APIs
WebAPIElementtagName
example html <span id="born">when i was born...</span> javascript var span = document.getelementbyid("born"); console.log(span.tagname); in xhtml (or any other xml format), the original case will be maintained, so "span" would be output in case the original tag name was created lowercase.
Element: underflow event - Web APIs
s <div id="wrapper"> <div id="child"></div> </div> <br/> <label><input type="checkbox" id="toggle" checked/> overflow</label> <style> #wrapper { width: 20px; height: 20px; background: #000; padding: 5px; overflow: hidden; } #child { width: 40px; height: 40px; border: 2px solid grey; background: #ccc; } </style> <script> var wrapper = document.getelementbyid("wrapper"), child = document.getelementbyid("child"), toggle = document.getelementbyid("toggle"); wrapper.addeventlistener("overflow", function( event ) { console.log( event ); }, false); wrapper.addeventlistener("underflow", function( event ) { console.log( event ); }, false); toggle.addeventlistener("change", function( event ) { if ( event.tar...
Element: webkitmouseforcewillbegin event - Web APIs
this offers the opportunity to tell the system not to trigger any default force touch actions if and when the click turns into a force touch event.
Event.currentTarget - Web APIs
function hide(e){ e.currenttarget.style.visibility = 'hidden'; console.log(e.currenttarget); // when this function is used as an event handler: this === e.currenttarget } var ps = document.getelementsbytagname('p'); for(var i = 0; i < ps.length; i++){ // console: print the clicked <p> element ps[i].addeventlistener('click', hide, false); } // console: print <body> document.body.addeventlistener('click', hide, false); // click around and make paragraphs disappear note: the value of event.currenttarget is only available while the event is being handled.
Event.defaultPrevented - Web APIs
html <p><a id="link1" href="#link1">visit link 1</a></p> <p><a id="link2" href="#link2">try to visit link 2</a> (you can't)</p> <p id="log"></p> javascript function stoplink(event) { event.preventdefault(); } function logclick(event) { const log = document.getelementbyid('log'); if (event.target.tagname === 'a') { if (event.defaultprevented) { log.innertext = 'sorry, but you cannot visit this link!\n' + log.innertext; } else { log.innertext = 'visiting link...\n' + log.innertext; } } } const a = document.getelementbyid('link2'); a.addeventlistener('click', stoplink); document.addeventlistener('click', logclick); result ...
Event.eventPhase - Web APIs
WebAPIEventeventPhase
<div id="d4">d4</div> </div> </div> </div> <div id="divinfo"></div> css div { margin: 20px; padding: 4px; border: thin black solid; } #divinfo { margin: 18px; padding: 8px; background-color:white; font-size:80%; } javascript let clear = false, divinfo = null, divs = null, usecapture = false; window.onload = function () { divinfo = document.getelementbyid('divinfo') divs = document.getelementsbytagname('div') chcapture = document.getelementbyid('chcapture') chcapture.onclick = function () { removelisteners() addlisteners() } clear() addlisteners() } function removelisteners() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divinfo") { d.removeeventlistener("click", ondivclick, tr...
Event.msConvertURL() - Web APIs
example var bloblist = []; document.getelementbyid("pastezone").addeventlistener('paste', handlepaste, false); function handlepaste(evt) { var filelist = window.clipboarddata.files; // note that window.datatransfer.files is not applicable.
Event.timeStamp - Web APIs
WebAPIEventtimeStamp
</p> <p>timestamp: <span id="time">-</span></p> javascript function gettime(event) { var time = document.getelementbyid("time"); time.firstchild.nodevalue = event.timestamp; } document.body.addeventlistener("keypress", gettime); result reduced time precision to offer protection against timing attacks and fingerprinting, the precision of event.timestamp might get rounded depending on browser settings.
Event.type - Web APIs
WebAPIEventtype
html <p>press any key or click the mouse to get the event type.</p> <p id="log"></p> javascript function geteventtype(event) { const log = document.getelementbyid('log'); log.innertext = event.type + '\n' + log.innertext; } // keyboard events document.addeventlistener('keydown', geteventtype, false); // first document.addeventlistener('keypress', geteventtype, false); // second document.addeventlistener('keyup', geteventtype, false); // third // mouse events document.addeventlistener('mousedown', geteventtype, false); // first document.add...
EventListener - Web APIs
example html <button id="btn">click here!</button> javascript const buttonelement = document.getelementbyid('btn'); // add a handler for the 'click' event by providing a callback function.
Fetch basic concepts - Web APIs
the api is completely promise-based.
File.getAsBinary() - Web APIs
WebAPIFilegetAsBinary
example // fileinput is an htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // object for allowed media types var accept = { binary : ["image/png", "image/jpeg"], text : ["text/plain", "text/css", "application/xml", "text/html"] }; var file; for (var i = 0; i < files.length; ...
File.getAsDataURL() - Web APIs
WebAPIFilegetAsDataURL
syntax var url = instanceoffile.getasdataurl(); returns a string representing a data: url example // fileinput is a htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // array with acceptable file types var accept = ["image/png"]; // img is a htmlimgelement: <img id="myimg"> var img = document.getelementbyid("myimg"); // if we accept the first selected file type if (accept.indexof(files[0].mediatype) > -1) { // display the image //...
File.getAsText() - Web APIs
WebAPIFilegetAsText
example // fileinput is a htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // object for allowed media types var accept = { binary : ["image/png", "image/jpeg"], text : ["text/plain", "text/css", "application/xml", "text/html"] }; var file; for (var i = 0; i < files.length; ...
File.lastModifiedDate - Web APIs
example // fileinput is a htmlinputelement: <input type="file" multiple id="myfileinput"> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (simliar to nodelist) var files = fileinput.files; for (var i = 0; i < files.length; i++) { alert(files[i].name + " has a last modified date of " + files[i].lastmodifieddate); } reduced time precision to offer protection against timing attacks and fingerprinting, the precision of somefile.lastmodifieddate.gettime() mi...
File.webkitRelativePath - Web APIs
html content <input type="file" id="filepicker" name="filelist" webkitdirectory multiple /> <ul id="listing"></ul> javascript content document.getelementbyid("filepicker").addeventlistener("change", function(event) { let output = document.getelementbyid("listing"); let files = event.target.files; for (let i=0; i<files.length; i++) { let item = document.createelement("li"); item.innerhtml = files[i].webkitrelativepath; output.appendchild(item); }; }, false); result specifications specification status c...
FileSystem - Web APIs
it's not available for use in file or folder picker panels (such as when you use an <input> element with the htmlinputelement.webkitdirectory attribute.firefox full support 50ie no support noopera full support 15prefixed full support 15prefixed prefixed implemented with the vendor prefix: webkitsafari full support ...
FileSystemDirectoryReader.readEntries() - Web APIs
let dropzone = document.getelementbyid("dropzone"); let listing = document.getelementbyid("listing"); function scanfiles(item, container) { let elem = document.createelement("li"); elem.innerhtml = item.name; container.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = document.createelement("ul"); container.appendchild(directorycontainer); d...
FileHandle API - Web APIs
such a file object is completely desynchronized from the original file, which means any change made to that object will never be reflected to the handled file as well as any change made to the handled file will never be pushed to the file object.
File and Directory Entries API support in Firefox - Web APIs
there are only two ways to get access to file system entries at this time: the <input> element, using the htmlinputelement.webkitentries property to access an array of filesystementry objects describing file system entries you can then read.
FormData() - Web APIs
WebAPIFormDataFormData
let myform = document.getelementbyid('myform'); let formdata = new formdata(myform); specifications specification status comment xmlhttprequestthe definition of 'formdata()' in that specification.
GeolocationCoordinates.longitude - Web APIs
let button = document.getelementbyid("get-location"); let lattext = document.getelementbyid("latitude"); let longtext = document.getelementbyid("longitude"); button.addeventlistener("click", function() { navigator.geolocation.getcurrentposition(function(position) { let lat = position.coords.latitude; let long = position.coords.longitude; lattext.innertext = lat.tofixed(2); longtext.innertext = long.tofix...
GlobalEventHandlers.onchange - Web APIs
html <input type="text" placeholder="type something here, then click outside of the field." size="50"> <p id="log"></p> javascript let input = document.queryselector('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.
GlobalEventHandlers.ondblclick - Web APIs
html <p>double click anywhere in this example.</p> <p id="log"></p> javascript let log = document.getelementbyid('log'); document.ondblclick = logdoubleclick; function logdoubleclick(e) { log.textcontent = `position: (${e.clientx}, ${e.clienty})`; } result specifications specification status comment html living standardthe definition of 'ondblclick' in that specification.
GlobalEventHandlers.ongotpointercapture - Web APIs
example function overhandler(event) { // determine the target event's gotpointercapture handler let gotcapturehandler = event.target.ongotpointercapture; } function init() { let el = document.getelementbyid('target'); el.ongotpointercapture = overhandler; } specifications specification status comment pointer events – level 2the definition of 'ongotpointercapture' in that specification.
GlobalEventHandlers.oninput - Web APIs
html <input type="text" placeholder="type something here to see its length." size="50"> <p id="log"></p> javascript let input = document.queryselector('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.
GlobalEventHandlers.oninvalid - Web APIs
thanks!</p> javascript const form = document.getelementbyid('form'); const error = document.getelementbyid('error'); const city = document.getelementbyid('city'); const thanks = document.getelementbyid('thanks'); city.oninvalid = invalid; form.onsubmit = submit; function invalid(event) { error.removeattribute('hidden'); } function submit(event) { form.setattribute('hidden', ''); thanks.removeattribute('hidden'); // for this example, d...
GlobalEventHandlers.onkeydown - Web APIs
html <input> <p id="log"></p> javascript const input = document.queryselector('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.
GlobalEventHandlers.onkeypress - Web APIs
html <input> <p id="log"></p> javascript const input = document.queryselector('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.
GlobalEventHandlers.onkeyup - Web APIs
html <input> <p id="log"></p> javascript const input = document.queryselector('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.
GlobalEventHandlers.onlostpointercapture - Web APIs
example function overhandler(event) { // determine the target event's lostpointercapture handler let lostcapturehandler = event.target.onlostpointercapture; } function init() { let el = document.getelementbyid('target'); el.onlostpointercapture = overhandler; } specifications specification status comment pointer events – level 2the definition of 'onlostpointercapture' in that specification.
GlobalEventHandlers.onpointerdown - Web APIs
var targetbox = document.getelementbyid("target"); targetbox.onpointerdown = handledown; function handledown(evt) { var action; switch(evt.pointertype) { case "mouse": action = "clicking"; break; case "pen": action = "tapping"; break; case "touch": action = "touching"; break; default: action = "interacting with"; break; } targetbox.innerhtml = "<strong...
GlobalEventHandlers.onpointerleave - Web APIs
<html> <script> function leavehandler(ev) { // process the pointerleave event } function init() { var el=document.getelementbyid("target1"); el.onpointerleave = leavehandler; } </script> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.onreset - Web APIs
time stamp: ${event.timestamp}`; } const form = document.getelementbyid('form'); const log = document.getelementbyid('log'); form.onreset = logreset; result specification specification status comment html living standardthe definition of 'onreset' in that specification.
GlobalEventHandlers.onscroll - Web APIs
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.queryselector('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.
GlobalEventHandlers.onselect - Web APIs
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.queryselector('textarea'); textarea.onselect = logselection; result specification specification status comment html living standardthe definition of 'onselect' in that ...
GlobalEventHandlers.onsubmit - Web APIs
thanks!</p> javascript const form = document.getelementbyid('form'); const error = document.getelementbyid('error'); const city = document.getelementbyid('city'); const thanks = document.getelementbyid('thanks'); city.oninvalid = invalid; form.onsubmit = submit; function invalid(event) { error.removeattribute('hidden'); } function submit(event) { form.setattribute('hidden', ''); thanks.removeattribute('hidden'); // for this example, d...
GlobalEventHandlers.ontouchcancel - Web APIs
<html> <script> function canceltouch(ev) { // process the event } function init() { let el = document.getelementbyid('target1'); el.ontouchcancel = canceltouch; } </script> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.ontouchmove - Web APIs
<html> <head> <script> function movetouch(ev) { // process the event } function init() { var el=document.getelementbyid("target1"); el.ontouchmove = movetouch; } </script> </head> <body onload="init();"> <div id="target1"> touch me ...
GlobalEventHandlers.ontouchstart - Web APIs
<html> <script> function starttouch(ev) { // process the event } function init() { let el = document.getelementbyid('target1'); el.ontouchstart = starttouch; } </script> <body onload="init();"> <div id="target1"> touch me ...
HTMLAnchorElement.referrerPolicy - Web APIs
examples var elt = document.createelement("a"); var linktext = document.createtextnode("my link"); elt.appendchild(linktext); elt.href = "https://developer.mozilla.org/"; elt.referrerpolicy = "no-referrer"; var div = document.getelementbyid("divaround"); div.appendchild(elt); // when clicked, the link will not send a referrer header.
HTMLAnchorElement.rel - Web APIs
syntax var relstr = anchorelt.rel; anchorelt.rel = relstr; example var anchors = document.getelementsbytagname("a"); var length = anchors.length; for (var i = 0; i < length; i++) { alert("rel: " + anchors[i].rel); } specifications specification status comment html living standardthe definition of 'rel' in that specification.
HTMLAnchorElement.relList - Web APIs
syntax var relstr = anchorelt.rellist; example var anchors = document.getelementsbytagname("a"); var length = anchors.length; for (var i = 0; i < length; i++) { var list = anchors[i].rellist; var listlength = list.length; console.log("new anchor node found with", listlength, "link types in rellist."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standa...
HTMLAreaElement.referrerPolicy - Web APIs
examples <img usemap="#maparound" width="100" height="100" src="/img/logo@2x.png" /> <map id="mymap" name="maparound" />> var elt = document.createelement("area"); elt.href = "/img2.png"; elt.shape = "rect"; elt.referrerpolicy = "no-referrer"; elt.coords = "0,0,100,100"; var map = document.getelementbyid("mymap"); map.appendchild(elt); // when clicked, the area's link will not send a referrer header.
HTMLAreaElement.rel - Web APIs
syntax var relstr = areaelt.rel; areaelt.rel = relstr; example var areas = document.getelementsbytagname("area"); var length = areas.length; for (var i = 0; i < length; i++) { alert("rel: " + areas[i].rel); } specifications specification status comment html living standardthe definition of 'rel' in that specification.
HTMLAreaElement.relList - Web APIs
syntax var relstr = areaelt.rellist; example var areas = document.getelementsbytagname("area"); var length = areas.length; for (var i = 0; i < length; i++) { var list = areas[i].rellist; var listlength = list.length; console.log("new area found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'rellist' in that specificati...
Audio() - Web APIs
determining when playback can begin there are three ways you can tell when enough of the audio file has loaded to allow playback to begin: check the value of the readystate property.
HTMLAudioElement - Web APIs
examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement = new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load.
HTMLButtonElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <button id="test">button</button> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const button = document.getelementbyid("test"); for(var i = 0; i < button.labels.length; i++) { console.log(button.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLCanvasElement.getContext() - Web APIs
examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get a 2d context of the canvas with the following code: var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); console.log(ctx); // canvasrenderingcontext2d { ...
HTMLCanvasElement.height - Web APIs
syntax var pxl = canvas.height; canvas.height = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the height of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.height); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.height' in that specification.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
also uses netutil.jsm var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); var netutilcallback = function() { return function(result) { if (!components.issuccesscode(result)) { alert('failed to create icon'); } else { alert('succes...
HTMLCanvasElement.mozGetAsFile() - Web APIs
function draw() { var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(200, 0, 0)'; ctx.fillrect(10, 10, 55, 50); ctx.fillstyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillrect(30, 30, 55, 50); var link = document.getelementbyid('link'); link.addeventlistener('click', copy); } function copy() { var canvas = document.getelementbyid('canvas'); var f = canvas.mozgetasfile('test.png'...
HTMLCanvasElement.mozOpaque - Web APIs
var canvas = document.getelementbyid('canvas'); console.log(canvas.mozopaque); // true // deactivate it canvas.mozopaque = false; specifications not part of any standard.
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
bubbles yes cancelable yes interface webglcontextevent event handler property none example var canvas = document.getelementbyid('canvas'); canvas.addeventlistener('webglcontextcreationerror', function(e) { console.log(e.statusmessage || 'unknown error'); }, false); var gl = canvas.getcontext('webgl'); // logs statusmessage or "unknown error" if unable to create webgl context specifications specification status comment webgl 1.0the definition of 'webglcontextcreationerror' in that sp...
HTMLCanvasElement: webglcontextlost event - Web APIs
bubbles yes cancelable yes interface webglcontextevent event handler property none example with the help of the webgl_lose_context extension, you can simulate the webglcontextlost event: const canvas = document.getelementbyid('canvas'); const gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', (event) => { console.log(event); }); gl.getextension('webgl_lose_context').losecontext(); // "webglcontextlost" event is logged.
HTMLCanvasElement: webglcontextrestored event - Web APIs
bubbles yes cancelable yes interface webglcontextevent event handler property none example with the help of the webgl_lose_context extension, you can simulate the webglcontextrestored event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').restorecontext(); // "webglcontextrestored" event is logged.
HTMLCanvasElement.width - Web APIs
syntax var pxl = canvas.width; canvas.width = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the width of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.width); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.width' in that specification.
HTMLDialogElement.close() - Web APIs
tion>red panda</option> <option>spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">cancel</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.returnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal di...
HTMLDialogElement.open - Web APIs
tion>red panda</option> <option>spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">cancel</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.returnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal di...
HTMLDialogElement.returnValue - Web APIs
ption>brine shrimp</option> <option>red panda</option> <option>spider monkey</option> </select> </label></p> <menu> <button>cancel</button> <button>confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var dialog = document.getelementbyid('favdialog'); dialog.returnvalue = 'favanimal'; function opencheck(dialog) { if (dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } function handleuserinput(returnvalue) { if (returnvalue === 'cancel' || returnvalue ...
HTMLDialogElement.show() - Web APIs
tion>red panda</option> <option>spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">cancel</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.returnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal di...
HTMLDialogElement.showModal() - Web APIs
tion>red panda</option> <option>spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">cancel</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.returnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal di...
HTMLDialogElement - Web APIs
tion>red panda</option> <option>spider monkey</option> </select></p> </section> <menu> <button id="cancel" type="reset">cancel</button> <button type="submit">confirm</button> </menu> </form> </dialog> <menu> <button id="updatedetails">update details</button> </menu> <script> (function() { var updatebutton = document.getelementbyid('updatedetails'); var cancelbutton = document.getelementbyid('cancel'); var dialog = document.getelementbyid('favdialog'); dialog.returnvalue = 'favanimal'; function opencheck(dialog) { if(dialog.open) { console.log('dialog open'); } else { console.log('dialog closed'); } } // update button opens a modal di...
accessKeyLabel - Web APIs
syntax label = element.accesskeylabel example javascript var node = document.getelementbyid('btn1'); if (node.accesskeylabel) { node.title += ' [' + node.accesskeylabel + ']'; } else { node.title += ' [' + node.accesskey + ']'; } node.onclick = function () { var p = document.createelement('p'); p.textcontent = 'clicked!'; node.parentnode.appendchild(p); }; html <button accesskey="h" title="caption" id="btn1">hover me</button> result specifications specification status comment html living standardthe definition of 'htmlelement.accesskeylabel' in that specification.
HTMLElement.click() - Web APIs
WebAPIHTMLElementclick
syntax element.click() example simulate a mouse-click when moving the mouse pointer over a checkbox: html <form> <input type="checkbox" id="mycheck" onmouseover="myfunction()" onclick="alert('click event occured')"> </form> javascript // on mouse-over, execute myfunction function myfunction() { document.getelementbyid("mycheck").click(); } specification specification status comment html living standard living standard document object model (dom) level 2 html specification obsolete initial definition.
HTMLElement.contextMenu - Web APIs
syntax var elementcontextmenu = element.contextmenu; example var contextmenu = document.getelementbyid("element").contextmenu; // change the label of the first menu entry contextmenu.firstelementchild.label = "new label"; ...
HTMLElement.dir - Web APIs
WebAPIHTMLElementdir
example var parg = document.getelementbyid("para1"); parg.dir = "rtl"; // change the text direction on a paragraph identified as "para1" specifications specification status comment html living standardthe definition of 'dir' in that specification.
HTMLElement.innerText - Web APIs
}</style> <span id=text>take a look at<br>how this text<br>is interpreted below.</span> <span style="display:none">hidden text</span> </p> <h3>result of textcontent:</h3> <textarea id="textcontentoutput" rows="6" cols="30" readonly>...</textarea> <h3>result of innertext:</h3> <textarea id="innertextoutput" rows="6" cols="30" readonly>...</textarea> javascript const source = document.getelementbyid("source"); const textcontentoutput = document.getelementbyid("textcontentoutput"); const innertextoutput = document.getelementbyid("innertextoutput"); textcontentoutput.value = source.textcontent; innertextoutput.value = source.innertext; result specification specification status comment html living standardthe definition of 'innertext' in that specifica...
HTMLElement: input event - Web APIs
html <input placeholder="enter some text" name="name"/> <p id="values"></p> javascript const input = document.queryselector('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.
HTMLElement.isContentEditable - Web APIs
</p> javascript document.getelementbyid('infotext1').innerhtml += document.getelementbyid('mytext1').iscontenteditable; document.getelementbyid('infotext2').innerhtml += document.getelementbyid('mytext2').iscontenteditable; result specifications specification status comment html living standardthe definition of 'htmlelement.contenteditable' in that specification.
HTMLElement.lang - Web APIs
WebAPIHTMLElementlang
example // this snippet compares the base language and // redirects to another url based on language if (document.documentelement.lang === "en") { window.location.href = "some_document.html.en"; } else if (document.documentelement.lang === "ru") { window.location.href = "some_document.html.ru"; } specification specification status comment document object model (dom) level 2 html specificationthe definition of 'lang' in that specification.
HTMLElement.offsetTop - Web APIs
example var d = document.getelementbyid("div1"); var toppos = d.offsettop; if (toppos > 10) { // object is offset more // than 10 pixels from its parent } specification specification status comment css object model (cssom) view modulethe definition of 'offsettop' in that specification.
HTMLElement.offsetWidth - Web APIs
syntax var intelemoffsetwidth = element.offsetwidth; intelemoffsetwidth is a variable storing an integer corresponding to the offsetwidth pixel value of the element.
HTMLElement.oncopy - Web APIs
html <h3>play with this text area:</h3> <textarea id="editor" rows="3">try copying and pasting text into this field!</textarea> <h3>log:</h3> <p id="log"></p> javascript const log = document.getelementbyid('log'); function logcopy(event) { log.innertext = 'copy blocked!\n' + log.innertext; event.preventdefault(); } function logpaste(event) { log.innertext = 'paste blocked!\n' + log.innertext; event.preventdefault(); } const editor = document.getelementbyid('editor'); editor.oncopy = logcopy; editor.onpaste = logpaste; result specification whatwg standard ...
HTMLElement.oncut - Web APIs
WebAPIHTMLElementoncut
html <h3>play with this text area:</h3> <textarea id="editor" rows="3">try copying and cutting the text in this field!</textarea> <h3>log:</h3> <p id="log"></p> javascript function logcopy(event) { log.innertext = 'copied!\n' + log.innertext; } function preventcut(event) { event.preventdefault(); log.innertext = 'cut blocked!\n' + log.innertext; } const editor = document.getelementbyid('editor'); const log = document.getelementbyid('log'); editor.oncopy = logcopy; editor.oncut = preventcut; result specification whatwg standard ...
HTMLElement.onpaste - Web APIs
html <h3>play with this text area:</h3> <textarea id="editor" rows="3">try copying and pasting text into this field!</textarea> <h3>log:</h3> <p id="log"></p> javascript function logcopy(event) { log.innertext = 'copied!\n' + log.innertext; } function logpaste(event) { log.innertext = 'pasted!\n' + log.innertext; } const editor = document.getelementbyid('editor'); const log = document.getelementbyid('log'); editor.oncopy = logcopy; editor.onpaste = logpaste; result specification whatwg standard ...
HTMLFormControlsCollection.namedItem() - Web APIs
example html <form> <input id="my-form-control" type="textarea"> </form> javascript // returns the htmlinputelement representing #my-form-control elem1 = document.forms[0]['my-form-control']; specifications specification status comment html living standardthe definition of 'htmlformcontrolscollection.nameditem()' in that specification.
HTMLFormControlsCollection - Web APIs
it represents the lists returned by the htmlformelement interface's elements property and the htmlfieldsetelement interface's elements property.
HTMLFormElement.length - Web APIs
example if (document.getelementbyid('form1').length > 1) { // more than one form control here } specifications specification status comment html living standardthe definition of 'htmlformelement: length' in that specification.
HTMLFormElement.name - Web APIs
syntax var string = form.name; form.name = string; example var form1name = document.getelementbyid('form1').name; if (form1name != document.form.form1) { // browser doesn't support this form of reference } specifications specification status comment html living standardthe definition of 'htmlformelement: name' in that specification.
HTMLFormElement.reset() - Web APIs
syntax htmlformelement.reset() example document.getelementbyid('myform').reset(); specifications specification status comment html living standardthe definition of 'htmlformelement: reset' in that specification.
HTMLFormElement: reset event - Web APIs
time stamp: ${event.timestamp}`; } const form = document.getelementbyid('form'); const log = document.getelementbyid('log'); form.addeventlistener('reset', logreset); result specifications specification status comment html living standardthe definition of 'reset' in that specification.
HTMLFormElement: submit event - Web APIs
time stamp: ${event.timestamp}`; event.preventdefault(); } const form = document.getelementbyid('form'); const log = document.getelementbyid('log'); form.addeventlistener('submit', logsubmit); result specifications specification status comment html living standardthe definition of 'submit' in that specification.
HTMLHtmlElement - Web APIs
you can retrieve the htmlhtmlelement object for a given document by reading the value of the document.documentelement property.
HTMLHyperlinkElementUtils.hash - Web APIs
syntax string = object.hash; object.hash = string; examples <a id="myanchor" href="/docs/htmlhyperlinkelementutils.href#examples">examples</a> <script> var anchor = document.getelementbyid("myanchor"); console.log(anchor.hash); // returns '#examples' </script> specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.hash' in that specification.
HTMLHyperlinkElementUtils.hostname - Web APIs
syntax string = object.hostname; object.hostname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.hostname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.hostname; // returns:'developer.mozilla.org' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.hostname' in that specification.
HTMLHyperlinkElementUtils.href - Web APIs
syntax string = object.href; object.href = string; examples // lets imagine an <a id="myanchor" href="https://developer.mozilla.org/htmlhyperlinkelementutils/href"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.href; // returns: 'https://developer.mozilla.org/htmlhyperlinkelementutils/href' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.href' in that specification.
HTMLHyperlinkElementUtils.origin - Web APIs
the htmlhyperlinkelementutils.origin read-only property is a usvstring containing the unicode serialization of the origin of the represented url; that is: for url using the http or https, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified); for url using file: scheme, the value is browser dependant; for url using the blob: scheme, the origin of the url following blob:.
HTMLHyperlinkElementUtils.password - Web APIs
syntax string = object.password; object.password = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/htmlhyperlinkelementutils.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.password; // returns:'flabada' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.password' in that specification.
HTMLHyperlinkElementUtils.pathname - Web APIs
syntax string = object.pathname; object.pathname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.pathname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.pathname; // returns:'/docs/htmlhyperlinkelementutils.pathname' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.pathname' in that specification.
HTMLHyperlinkElementUtils.port - Web APIs
syntax string = object.port; object.port = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org:443/docs/htmlhyperlinkelementutils.port"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.port; // returns:'443' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.port' in that specification.
HTMLHyperlinkElementUtils.protocol - Web APIs
syntax string = object.protocol; object.protocol = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/htmlhyperlinkelementutils.protocol"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.protocol; // returns:'https:' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.protocol' in that specification.
HTMLHyperlinkElementUtils.search - Web APIs
syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // returns:'?q=123' // further parsing: let params = new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.search' in that specification.
HTMLHyperlinkElementUtils.toString() - Web APIs
syntax string = object.tostring(); examples // let's imagine an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils/tostring"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.tostring(); // returns: 'https://developer.mozilla.org/docs/htmlhyperlinkelementutils/tostring' specifications specification status comment html living standard living standard ...
HTMLHyperlinkElementUtils.username - Web APIs
syntax string = object.username; object.username = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/htmlhyperlinkelementutils.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.username; // returns:'anonymous' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.username' in that specification.
contentDocument - Web APIs
example of contentdocument var iframedocument = document.getelementsbytagname("iframe")[0].contentdocument; iframedocument.body.style.backgroundcolor = "blue"; // this would turn the iframe blue.
HTMLIFrameElement.contentWindow - Web APIs
example of contentwindow var x = document.getelementsbytagname("iframe")[0].contentwindow; //x = window.frames[0]; x.document.getelementsbytagname("body")[0].style.backgroundcolor = "blue"; // this would turn the 1st iframe in document blue.
HTMLIFrameElement.referrerPolicy - Web APIs
examples var iframe = document.createelement("iframe"); iframe.src = "/"; iframe.referrerpolicy = "unsafe-url"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLIFrameElement.src - Web APIs
syntax refstr = iframeelt.src; iframeelt.src= refstr; example var iframe = document.createelement("iframe"); iframe.src = "/"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment html living standardthe definition of 'htmliframeelement: src' in that specification.
HTMLImageElement.alt - Web APIs
examples beyond that, there are additional guidelines for using alt appropriately which vary depending on what the image is being used for.
HTMLImageElement.decode() - Web APIs
this can be used to initiate loading of the image prior to attaching it to an element in the dom (or adding it to the dom as a new element), so that the image can be rendered immediately upon being added to the dom.
HTMLImageElement.referrerPolicy - Web APIs
examples var img = new image(); img.src = 'img/logo.png'; img.referrerpolicy = 'origin'; var div = document.getelementbyid('divaround'); div.appendchild(img); // fetch the image using the origin as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLImageElement.sizes - Web APIs
let image = document.queryselector("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.
HTMLImageElement.srcset - Web APIs
also provided is the word-break attribute, using the break-all value to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur.
HTMLImageElement.x - Web APIs
let logbox = document.queryselector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.queryselector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <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 ...
HTMLImageElement.y - Web APIs
let logbox = document.queryselector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.queryselector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <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 ...
HTMLLinkElement.referrerPolicy - Web APIs
syntax domstring htmllinkelement.referrerpolicy example var links = document.getelementsbytagname("link"); links[0].referrerpolicy; // "no-referrer" specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLLinkElement.rel - Web APIs
syntax var relstr = linkelt.rel; linkelt.rel = relstr; example var links = document.getelementsbytagname('link'); var length = links.length; for (var i = 0; i < length; i++) { alert(links[i]); } specifications specification status comment html living standardthe definition of 'rel' in that specification.
HTMLLinkElement.relList - Web APIs
syntax var relstr = linkelt.rellist; example var links = document.getelementsbytagname("link"); var length = links.length; for (var i = 0; i < length; i++) { var list = links[i].rellist; var listlength = list.length; console.log("new link found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'rellist' in that specificatio...
HTMLMediaElement.audioTracks - Web APIs
var video = document.getelementbyid("video"); for (var i = 0; i < video.audiotracks.length; i += 1) { video.audiotracks[i].enabled = false; } specifications specification status comment html living standardthe definition of 'htmlmediaelement.audiotracks' in that specification.
HTMLMediaElement.canPlayType() - Web APIs
"" (empty string) media of the given type definitely can't be played on the current device.
HTMLMediaElement.captureStream() - Web APIs
document.queryselector('.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.
HTMLMediaElement.fastSeek() - Web APIs
let myvideo = document.getelementbyid("myvideoelement"); myvideo.fastseek(20); specifications specification status comment html living standardthe definition of 'fastseek()' in that specification.
HTMLMediaElement.networkState - Web APIs
<audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getelementbyid('example'); obj.addeventlistener('playing', function() { if (obj.networkstate === 2) { // still loading...
HTMLMediaElement.paused - Web APIs
the read-only htmlmediaelement.paused property tells whether the media element is paused.
HTMLMediaElement.readyState - Web APIs
<audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getelementbyid('example'); obj.addeventlistener('loadeddata', function() { if(obj.readystate >= 2) { obj.play(); } }); specifications specification status comment html living standardthe definition of 'htmlmediaelement.readystate' in that specification.
HTMLMeterElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <meter id="test" min="0" max="100" value="70">70</meter> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const meter = document.getelementbyid("test"); for(var i = 0; i < meter.labels.length; i++) { console.log(meter.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
Option() - Web APIs
examples just add new options /* assuming we have the following html <select id='s'> </select> */ var s = document.getelementbyid('s'); var options = [four, five, six]; options.foreach(function(element,key) { s[key] = new option(element,key); }); append options with different parameters /* assuming we have the following html <select id="s"> <option>first</option> <option>second</option> <option>third</option> </select> */ var s = document.getelementbyid('s'); var options = [ 'zero', 'one', 'two...
HTMLElement.blur() - Web APIs
syntax element.blur(); examples remove focus from a text input html <input type="text" id="mytext" value="sample text"> <br><br> <button type="button" onclick="focusinput()">click me to gain focus</button> <button type="button" onclick="blurinput()">click me to lose focus</button> javascript function focusinput() { document.getelementbyid('mytext').focus(); } function blurinput() { document.getelementbyid('mytext').blur(); } result specification specification status comment html living standardthe definition of 'blur' in that specification.
HTMLOrForeignElement.dataset - Web APIs
camelcase to dash-style conversion the opposite transformation, which maps a key to an attribute name, uses the following rules: restriction: before the transformation, a dash must not be immediately followed by an ascii lowercase letter a to z; the prefix data- is added; any ascii uppercase letter a to z is transformed into a dash, followed by its lowercase counterpart; other characters are left unchanged.
HTMLOrForeignElement.tabIndex - Web APIs
syntax element.tabindex = index; var index = element.tabindex; value index is an integer example const b1 = document.getelementbyid('button1'); b1.tabindex = 1; specifications specification status comment html living standardthe definition of 'tabindex' in that specification.
HTMLProgressElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <progress id="test" value="70" max="100">70%</progress> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const progress = document.getelementbyid("test"); for(var i = 0; i < progress.labels.length; i++) { console.log(progress.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLStyleElement.media - Web APIs
example <!doctype html> <html> <head> <link id="linkedstyle" rel="stylesheet" href="document.css" type="text/css" media="screen" /> <style id="inlinestyle" rel="stylesheet" type="text/css" media="screen, print"> p { color: blue; } </style> </head> <body> <script> alert('linkedstyle: ' + document.getelementbyid('linkedstyle').media); // 'screen' alert('inlinestyle: ' + document.getelementbyid('inlinestyle').media); // 'screen, print' </script> </body> </html> specifications specification status comment html living standardthe definition of 'htmlstyleelement' in that specification.
HTMLTableElement.align - Web APIs
syntax htmltableelement.align = alignment; var alignment = htmltableelement.align; parameters alignment domstring with one of the following values: left center right example // set the alignmnet of a table var t = document.getelementbyid('tablea'); t.align = 'center'; specification w3c dom 2 html specification htmltableelement .align.
HTMLTableElement.bgColor - Web APIs
example // set table background colour to lightblue var t = document.getelementbyid('tablea'); t.bgcolor = 'lightblue'; specification dom level 2 html:htmltableelement .bgcolor ...
HTMLTableElement.border - Web APIs
example // set the width of a table border to 2 pixels var t = document.getelementbyid('tablea'); t.border = '2'; specification w3c dom 2 html specification htmltableelement .border.
HTMLTableElement.cellPadding - Web APIs
example // set cell padding to 10 pixels let t = document.getelementbyid('tablea'); t.cellpadding = '10'; specification w3c dom 2 html specification htmltableelement .cellpadding.
HTMLTableElement.cellSpacing - Web APIs
var t = document.getelementbyid('tablea'); t.cellspacing = "10"; specification w3c dom 2 html specification htmltableelement .cellspacing.
HTMLTableElement.createCaption() - Web APIs
the caption does not need to be added separately as would be the case if document.createelement() had been used to create the new <caption> element.
HTMLTableElement.createTFoot() - Web APIs
the footer does not need to be added separately as would be the case if document.createelement() had been used to create the new <tfoot> element.
HTMLTableElement.createTHead() - Web APIs
the header does not need to be added separately as would be the case if document.createelement() had been used to create the new <thead> element.
HTMLTableElement.frame - Web APIs
"above" top side "below" bottom side "hsides" top and bottom only "vsides" right and left sides only "lhs" left-hand side only "rhs" right-hand side only "box" all four sides "border" all four sides example // set the frame of tablea to 'border' var t = document.getelementbyid('tablea'); t.frame = "border"; t.border = "2px"; specification w3c dom 2 html specification ...
HTMLTableElement.rules - Web APIs
syntax htmltableelement.rules = rules; var rules = htmltableelement.rules; parameters rules is a string with one of the following values: none no rules groups lines between groups only rows lines between rows cols lines between cols all lines between all cells example // turn on all the internal borders of a table var t = document.getelementbyid("tableid"); t.rules = "all"; specification w3c dom 2 html specification ...
HTMLTextAreaElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <textarea id="test">some text</textarea> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const textarea = document.getelementbyid("test"); for(var i = 0; i < textarea.labels.length; i++) { console.log(textarea.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLTextAreaElement - Web APIs
sed ac tellus eros.
HTMLTimeElement.dateTime - Web APIs
pthhmms.xs pthhmms.xxs pthhmms.xxxs ww dd hh mm ss p12dt7h12m13s p12dt7h12m13.3s p12dt7h12m13.45s p12dt7h12m13.455s pt7h12m13s pt7h12m13.2s pt7h12m13.56s pt7h12m13.999s 7d 5h 24m 13s syntax datetimestring = timeelt.datetime; timeelt.datetime = datetimestring example // assumes there is <time id="t"> element in the html var t = document.getelementbyid("t"); t.datetime = "6w 5h 34m 5s"; specifications specification status comment html living standardthe definition of 'htmltimeelement' in that specification.
HTMLTrackElement: cuechange event - Web APIs
let texttrackelem = document.getelementbyid("texttrack"); texttrackelem.addeventlistener("cuechange", (event) => { let cues = event.target.track.activecues; }); in addition, you can use the oncuechange event handler: let texttrackelem = document.getelementbyid("texttrack"); texttrackelem.oncuechange = (event) => { let cues = event.target.track.activecues; }); specifications specification status html...
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
this value includes any dropped or corrupted frames, so it's not the same as "total number of frames played." var videoelem = document.getelementbyid("my_vid"); var counterelem = document.getelementbyid("counter"); var quality = videoelem.getvideoplaybackquality(); counterelem.innertext = quality.totalvideoframes; specifications specification status comment media playback qualitythe definition of 'htmlvideoelement.getvideoplaybackquality()' in that specification.
HTMLVideoElement.msHorizontalMirror - Web APIs
example var myvideo = document.getelementbyid("videotag1"); myvideo.mshorizontalmirror = true; myvideo.play(); example #2: var flip = document.queryselector('#flip'); flip.addeventlistener('click', function() { video.mshorizontalmirror = true; }); see also htmlvideoelement microsoft api extensions ...
HTMLVideoElement.msInsertVideoEffect() - Web APIs
example var ovideo1 = document.getelementbyid("video1"); ovideo1.msinsertvideoeffect("windows.media.videoeffects.videostabilization", true, null); see also htmlvideoelement microsoft api extensions ...
HTMLVideoElement.msZoom - Web APIs
var myvideo = document.getelementbyid("videotag1"); myvideo.mszoom = true; myvideo.play(); see also htmlvideoelement microsoft api extensions ...
HTMLVideoElement.videoHeight - Web APIs
let v = document.getelementbyid("myvideo"); v.addeventlistener("resize", ev => { let w = v.videowidth; let h = v.videoheight; if (w && h) { v.style.width = w; v.style.height = h; } }, false); note that this only applies the change if both the videowidth and the videoheight are non-zero.
HTMLVideoElement.videoWidth - Web APIs
let v = document.getelementbyid("myvideo"); v.addeventlistener("resize", ev => { let w = v.videowidth; let h = v.videoheight; if (w && h) { v.style.width = w; v.style.height = h; } }, false); note that this only applies the change if both the videowidth and the videoheight are non-zero.
Drag Operations - Web APIs
within the drop and dragend events, you can check the dropeffect property to determine which effect was ultimately chosen.
History.back() - Web APIs
WebAPIHistoryback
html <button id="go-back">go back!</button> javascript document.getelementbyid('go-back').addeventlistener('click', () => { history.back(); }); specifications specification status comment html living standardthe definition of 'history.back()' in that specification.
History.forward() - Web APIs
WebAPIHistoryforward
html <button id='go-forward'>go forward!</button> javascript document.getelementbyid('go-forward').addeventlistener('click', e => { window.history.forward(); }) specifications specification status comment html living standardthe definition of 'history' in that specification.
Ajax navigation example - Web APIs
isloading) { return; } oreq.abort(); closereq(); } function ajaxerror () { alert("unknown error."); } function ajaxload () { var vmsg, nstatus = this.status; switch (nstatus) { case 200: vmsg = json.parse(this.responsetext); document.title = opageinfo.title = vmsg.page; document.getelementbyid(stargetid).innerhtml = vmsg.content; if (bupdateurl) { history.pushstate(opageinfo, opageinfo.title, opageinfo.url); bupdateurl = false; } break; default: vmsg = nstatus + ": " + (ohttpstatus[nstatus] || "unknown"); switch (math.floor(nstatus / 100)) { ...
IDBCursor.request - Web APIs
WebAPIIDBCursorrequest
examples when you open a cursor, the request property is then available on that cursor object, to tell you what request object the cursor originated from.
IDBDatabase.close() - Web APIs
WebAPIIDBDatabaseclose
the close() method of the idbdatabase interface returns immediately and closes the connection in a separate thread.
IDBDatabase.transaction() - Web APIs
the transaction method of the idbdatabase interface immediately returns a transaction object (idbtransaction) containing the idbtransaction.objectstore method, which you can use to access your object store.
IDBFactory.deleteDatabase() - Web APIs
the method returns an idbopendbrequest object immediately, and performs the deletion operation asynchronously.
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
the method returns an idbopendbrequest object immediately, and performs the open operation asynchronously.
IDBObjectStore.clear() - Web APIs
the clear() method of the idbobjectstore interface creates and immediately returns an idbrequest object, and clears this object store in a separate thread.
IDBObjectStore.get() - Web APIs
to tell these situations apart, call the opencursor() method with the same key.
IDBObjectStore.getAll() - Web APIs
this method produces the same result for: a record that doesn't exist in the database a record that has an undefined value to tell these situations apart, you either call the opencursor() method with the same key.
IDBObjectStore.getAllKeys() - Web APIs
this method produces the same result for: a record that doesn't exist in the database a record that has an undefined value to tell these situations apart, you need to call the opencursor() method with the same key.
IDBObjectStore.getKey() - Web APIs
example let openrequest = indexeddb.open("telemetry"); openrequest.onsuccess = (event) => { let db = event.target.result; let store = db.transaction("netlogs").objectstore("netlogs"); let today = new date(); let yesterday = new date(today); yesterday.setdate(today.getdate() - 1); let request = store.getkey(idbkeyrange(yesterday, today)); request.onsuccess = (event) => { let when = event.target.result; alert("the 1st ac...
IDBObjectStore.openCursor() - Web APIs
direction optional an idbcursordirection telling the cursor what direction to travel.
IDBObjectStore.openKeyCursor() - Web APIs
direction optional an idbcursordirection telling the cursor what direction to travel.
IDBObjectStore - Web APIs
idbobjectstore.clear() creates and immediately returns an idbrequest object, and clears this object store in a separate thread.
IDBRequest - Web APIs
all asynchronous operations immediately return an idbrequest instance.
IDBVersionChangeRequest.setVersion() - Web APIs
the idbversionchangerequest.setversion method updates the version of the database, returning immediately and running a versionchange transaction on the connected database in a separate thread.
IDBVersionChangeRequest - Web APIs
returns immediately and runs a versionchange transaction on the connected database in a separate thread.
IdleDeadline.didTimeout - Web APIs
if didtimeout is true, the idledeadline object's timeremaining() method will return approximately 0.
IdleDeadline.timeRemaining() - Web APIs
if there isn't, the callback can just return immediately, or look for other work to do with the remaining time.
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
examples html <canvas id="htmlcanvas"></canvas> javascript var htmlcanvas = document.getelementbyid("htmlcanvas").getcontext("bitmaprenderer"); // draw a webgl scene offscreen var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
ImageData() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const arr = new uint8clampedarray(40000); // iterate through every pixel for (let i = 0; i < arr.length; i += 4) { arr[i + 0] = 0; // r value arr[i + 1] = 190; // g value arr[i + 2] = 0; // b value arr[i + 3] = 255; // a value } // initialize a new imagedata object let imagedata = new imagedata(arr, 200); // draw image da...
ImageData.data - Web APIs
WebAPIImageDatadata
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 100); // iterate through every pixel for (let i = 0; i < imagedata.data.length; i += 4) { // percentage in the x direction, times 255 let x = (i % 400) / 400 * 255; // percentage in the y direction, times 255 let y = math.ceil(i / 400) / 100 * 255; // modify pixel data imagedata.data[...
Browser storage limits and eviction criteria - Web APIs
for example: mozilla.org — group1, origin1 www.mozilla.org — group1, origin2 joe.blogs.mozilla.org — group1, origin3 firefox.com — group2, origin4 in this group, mozilla.org, www.mozilla.org, and joe.blogs.mozilla.org can aggregately use a maximum of 20% of the global limit.
IndexedDB API - Web APIs
examples elibri: a powerful library and ebook reader application, written by marco castelluccio, winner of the indexeddb mozilla devderby.
InputEvent.inputType - Web APIs
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.queryselector('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.
install - Web APIs
firefox 3 note in firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted.
IntersectionObserver.IntersectionObserver() - Web APIs
the syntax is approximately the same as that for the css margin property; see the root element and root margin in intersection observer api for more information on how the margin works and the syntax.
IntersectionObserver.observe() - Web APIs
syntax intersectionobserver.observe(targetelement); parameters targetelement an element whose visibility within the root is to be monitored.
IntersectionObserverEntry.intersectionRatio - Web APIs
the intersectionobserverentry interface's read-only intersectionratio property tells you how much of the target element is currently visible within the root's intersection ratio, as a value between 0.0 and 1.0.
KeyboardEvent.initKeyEvent() - Web APIs
false, // ctrlkeyarg, false, // altkeyarg, false, // shiftkeyarg, false, // metakeyarg, 9, // keycodearg, 0); // charcodearg); document.getelementbyid('blah').dispatchevent(event); specification this implementation of keyboard events is based on the key events spec in the early versions of dom 2 events, later removed from that spec.
KeyboardEvent.keyCode - Web APIs
unfortunately, some browsers still don't have it, so you'll have to be careful to make sure you use one which is supported on all target browsers.
KeyboardEvent - Web APIs
on those platforms, then, an auto-repeat key will generate the following sequence of events: keydown keypress keyup keydown keypress keyup <<repeating until the user releases the key>> keyup in these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.
KeyframeEffect.KeyframeEffect() - Web APIs
syntax var keyframes = new keyframeeffect(element, keyframeset, keyframeoptions); var keyframes = new keyframeeffect(sourcekeyframes); parameters the first type of constructor (see above) creates a completely new keyframeeffect object instance.
Location: hash - Web APIs
WebAPILocationhash
syntax string = object.hash; object.hash = string; examples <a id="myanchor" href="/docs/location.href#examples">examples</a> <script> var anchor = document.getelementbyid("myanchor"); console.log(anchor.hash); // returns '#examples' </script> specifications specification status comment html living standardthe definition of 'hash' in that specification.
Location: hostname - Web APIs
WebAPILocationhostname
syntax string = object.hostname; object.hostname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/location.hostname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.hostname; // returns:'developer.mozilla.org' specifications specification status comment html living standardthe definition of 'hostname' in that specification.
Location: href - Web APIs
WebAPILocationhref
syntax string = object.href; object.href = string; examples // lets imagine an <a id="myanchor" href="https://developer.mozilla.org/location/href"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.href; // returns: 'https://developer.mozilla.org/location/href' specifications specification status comment html living standardthe definition of 'href' in that specification.
Location: origin - Web APIs
WebAPILocationorigin
the origin read-only property of the location interface is a usvstring containing the unicode serialization of the origin of the represented url; that is: for url using the http or https, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified); for url using file: scheme, the value is browser dependant; for url using the blob: scheme, the origin of the url following blob:.
Location: password - Web APIs
WebAPILocationpassword
syntax string = object.password; object.password = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.password; // returns:'flabada' ...
Location: pathname - Web APIs
WebAPILocationpathname
syntax string = object.pathname; object.pathname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/location.pathname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.pathname; // returns:'/docs/location.pathname' specifications specification status comment html living standardthe definition of 'pathname' in that specification.
Location: port - Web APIs
WebAPILocationport
syntax string = object.port; object.port = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org:443/docs/location.port"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.port; // returns:'443' specifications specification status comment html living standardthe definition of 'location.port' in that specification.
Location: protocol - Web APIs
WebAPILocationprotocol
syntax string = object.protocol; object.protocol = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/location.protocol"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.protocol; // returns:'https:' specifications specification status comment html living standardthe definition of 'protocol' in that specification.
Location: search - Web APIs
WebAPILocationsearch
syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/location.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // returns:'?q=123' // further parsing: let params = new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardthe definition of 'search' in that specification.
Location: toString() - Web APIs
WebAPILocationtoString
syntax string = object.tostring(); examples // let's imagine an <a id="myanchor" href="https://developer.mozilla.org/docs/location/tostring"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.tostring(); // returns: 'https://developer.mozilla.org/docs/location/tostring' specifications specification status comment html living standard living standard ...
Location: username - Web APIs
WebAPILocationusername
syntax string = object.username; object.username = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.username; // returns:'anonymous' ...
MediaDevices.getSupportedConstraints() - Web APIs
html <p>the following media constraints are supported by your browser:</p> <ul id="constraintlist"> </ul> css body { font: 15px arial, sans-serif; } javascript let constraintlist = document.getelementbyid("constraintlist"); let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); for (let constraint in supportedconstraints) { if (supportedconstraints.hasownproperty(constraint)) { let elem = document.createelement("li"); elem.innerhtml = "<code>" + constraint + "</code>"; constraintlist.appendchild(elem); } } result specifications specifi...
MediaDevices.getUserMedia() - Web APIs
var front = false; document.getelementbyid('flip-button').onclick = function() { front = !front; }; var constraints = { video: { facingmode: (front?
msExtendedCode - Web APIs
example var video1 = object.getelementbyid("video1"); video1.addeventlistener('error', function () { var error = video1.error.msextendedcode; //...
MediaList.mediaText - Web APIs
note that the medialist is a live list; updating the list via mediatext will immediately update the behavior of the document.
MediaList - Web APIs
WebAPIMediaList
note: medialist is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document.
MediaPositionState.playbackRate - Web APIs
the mediapositionstate dictionary's playbackrate property is used when calling the mediasession method setpositionstate() to tell the user agent the rate at which media is currently being played.
MediaRecorder.start() - Web APIs
exceptions errors that can be detected immediately are thrown as dom exceptions.
MediaSource.endOfStream() - Web APIs
when you make an xmlhttprequest call for a media chunk, and onabort or onerror triggers, you might want to call endofstream('network'), display a descriptive message in the ui, and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.) decode: terminates playback and signals that a decoding error has occured.
MediaSource.isTypeSupported() - Web APIs
this is because media files are complex, intricate constructs with far too many subtle variations to be absolutely certain of anything until you actually use the contents of the media.
MediaStream.ended - Web APIs
WebAPIMediaStreamended
the ended read-only property of the mediastream interface returns a boolean value which is true if the stream has been completely read, or false if the end of the stream has not been reached.
MediaStream.onaddtrack - Web APIs
stream.onaddtrack = function(event) { let tracklist = document.getelementbyid("tracks"); let label = document.createelement("li"); label.innerhtml = event.track.kind + ": " + event.track.label; tracklist.appendchild(label); }; specifications specification status comment media capture and streamsthe definition of 'mediastream.onaddtrack' in that specification.
MediaStream.onremovetrack - Web APIs
stream.onremovetrack = function(event) { let tracklist = document.getelementbyid("tracks"); let label = document.createelement("li"); label.innerhtml = "removed: " + event.track.kind + ": " + event.track.label; tracklist.appendchild(label); }; specifications specification status comment media capture and streamsthe definition of 'mediastream.onremovetrack' in that specification.
MediaStreamTrack: ended event - Web APIs
track.addeventlistener('ended', () => { let statuselem = document.getelementbyid("status-icon"); statuselem.src = "/images/stopped-icon.png"; }) you can also set up the event handler using the mediastreamtrack.onended property: track.onended = function() { let statuselem = document.getelementbyid("status-icon"); statuselem.src = "/images/stopped-icon.png"; } specifications specification status comment media capture and streamsth...
MediaStreamTrack.onended - Web APIs
track.onended = function(event) { let statuselem = document.getelementbyid("status-icon"); statuselem.src = "/images/stopped-icon.png"; } specifications specification status comment media capture and streamsthe definition of 'mediastreamtrack.onended' in that specification.
MediaStreamTrack.remote - Web APIs
it returns a boolean with a value of true if the track is sourced remotely (that is, sourced by an rtcpeerconnection), or false if it is sourced locally.
Using the MediaStream Recording API - Web APIs
both audio and video may be recorded, separately or together.
MediaStream Recording API - Web APIs
navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { let menu = document.getelementbyid("inputdevices"); if (device.kind == "audioinput") { let item = document.createelement("option"); item.innerhtml = device.label; item.value = device.deviceid; menu.appendchild(item); } }); }); code similar to this can be used to let the user restrict the set of devices they wish to use.
MediaTrackSettings - Web APIs
common values include 1.3333333333 (for the classic television 4:3 "standard" aspect ratio, also used on tablets such as apple's ipad), 1.7777777778 (for the 16:9 high-definition widescreen aspect ratio), and 1.6 (for the 16:10 aspect ratio common among widescreen computers and tablets).
MediaTrackSupportedConstraints.aspectRatio - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().aspectratio) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'aspectratio' in that specification.
MediaTrackSupportedConstraints.autoGainControl - Web APIs
html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().autogaincontrol) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'autogaincontrol' in that specification.
MediaTrackSupportedConstraints.channelCount - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().channelcount) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'channelcount' in that specification.
MediaTrackSupportedConstraints.deviceId - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().deviceid) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'deviceid' in that specification.
MediaTrackSupportedConstraints.echoCancellation - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().echocancellation) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'echocancellation' in that specification.
MediaTrackSupportedConstraints.facingMode - Web APIs
example html <div id="result"> </div> css #result { font: 14px "arial", sans-serif; } javascript let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().facingmode) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'facingmode' in that specification.
MediaTrackSupportedConstraints.frameRate - Web APIs
javascript let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().framerate) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } html <div id="result"> </div> css #result { font: 14px "arial", sans-serif; } result the output, showing if your browser supports the framerate constraint, is: while this example is trivial, you can replace...
MediaTrackSupportedConstraints.groupId - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().groupid) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'groupid' in that specification.
MediaTrackSupportedConstraints.height - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().height) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'height' in that specification.
MediaTrackSupportedConstraints.latency - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().latency) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'latency' in that specification.
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().noisesuppression) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'noisesuppression' in that specification.
MediaTrackSupportedConstraints.sampleRate - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().samplerate) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'samplerate' in that specification.
MediaTrackSupportedConstraints.sampleSize - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().samplesize) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'samplesize' in that specification.
MediaTrackSupportedConstraints.volume - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().volume) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result ...
MediaTrackSupportedConstraints.width - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().width) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'width' in that specification.
Transcoding assets for Media Source Extensions - Web APIs
this article takes you through the requirements and shows you a toolchain you can use to encode your assets appropriately.
MouseEvent.initMouseEvent() - Web APIs
example html <div style="background:red; width:180px; padding:10px;"> <div id="out"></div> <input type="text"> </div> javascript document.body.onclick = function(){ e = arguments[0]; var dt = e.target,stag = dt.tagname.tolowercase(); document.getelementbyid("out").innerhtml = stag; }; var simulateclick = function(){ var evt = document.createevent("mouseevents"); evt.initmouseevent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); document.body.dispatchevent(evt); } simulateclick(); result specifications specification status comment document object model (dom) level 3 ev...
MouseEvent.movementX - Web APIs
html <p id="log">move your mouse around.</p> javascript function logmovement(event) { log.insertadjacenthtml('afterbegin', `movement: ${event.movementx}, ${event.movementy}<br>`); while (log.childnodes.length > 128) log.lastchild.remove() } const log = document.getelementbyid('log'); document.addeventlistener('mousemove', logmovement); result specifications specification status comment pointer lockthe definition of 'mouseevent.movementx' in that specification.
MouseEvent.movementY - Web APIs
html <p id="log">move your mouse around.</p> javascript function logmovement(event) { log.innertext = `movement: ${event.movementx}, ${event.movementy}\n${log.innertext}`; } const log = document.getelementbyid('log'); document.addeventlistener('mousemove', logmovement); result specifications specification status comment pointer lockthe definition of 'mouseevent.movementy' in that specification.
MouseEvent.pageX - Web APIs
WebAPIMouseEventpageX
javascript var box = document.queryselector(".box"); var pagex = document.getelementbyid("x"); var pagey = document.getelementbyid("y"); function updatedisplay(event) { pagex.innertext = event.pagex; pagey.innertext = event.pagey; } box.addeventlistener("mousemove", updatedisplay, false); box.addeventlistener("mouseenter", updatedisplay, false); box.addeventlistener("mouseleave", updatedisplay, false); the javascript code uses addeventlistener() to register the functi...
MouseEvent.region - Web APIs
WebAPIMouseEventregion
<canvas id="canvas"></canvas> <script> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: "circle"}); canvas.addeventlistener("mousemove", function(event){ if(event.region) { console.log("hit region: " + event.region); } }); </script> ...
MouseEvent.relatedTarget - Web APIs
html <body id="body"> <div id="outer"> <div id="red"></div> <div id="blue"></div> </div> <p id="log"></p> </body> css #outer { width: 250px; height: 125px; display: flex; } #red { flex-grow: 1; background: red; } #blue { flex-grow: 1; background: blue; } #log { max-height: 120px; overflow-y: scroll; } javascript const mouseoutlog = document.getelementbyid('log'), red = document.getelementbyid('red'), blue = document.getelementbyid('blue'); red.addeventlistener('mouseover', overlistener); red.addeventlistener('mouseout', outlistener); blue.addeventlistener('mouseover', overlistener); blue.addeventlistener('mouseout', outlistener); function outlistener(event) { let related = event.relatedtarget ?
MouseEvent - Web APIs
html <p><label><input type="checkbox" id="checkbox"> checked</label> <p><button id="button">click me</button> javascript function simulateclick() { var evt = new mouseevent("click", { bubbles: true, cancelable: true, view: window }); var cb = document.getelementbyid("checkbox"); //element to click on var canceled = !cb.dispatchevent(evt); if(canceled) { // a handler called preventdefault alert("canceled"); } else { // none of the handlers called preventdefault alert("not canceled"); } } document.getelementbyid("button").addeventlistener('click', simulateclick); result specifications specification status co...
msPlayToSource - Web APIs
e.sourcerequest.setsource(document.getelementbyid("videoplayer").msplaytosource); // the media will then be streamed to the device chosen by the user in the ui.
MutationObserver.MutationObserver() - Web APIs
dom observation does not begin immediately; the observe() method must be called first to establish which portion of the dom to watch and what kinds of changes to watch for.
MutationObserver.disconnect() - Web APIs
the mutationobserver method disconnect() tells the observer to stop watching for mutations.
MutationObserver.observe() - Web APIs
// identify an element to observe const elementtoobserve = document.queryselector("#targetelementid"); // create a new instance of `mutationobserver` named `observer`, // passing it a callback function const observer = new mutationobserver(function() { console.log('callback that runs when observer is triggered'); }); // call `observe()` on that mutationobserver instance, // passing it the element to observe, and the options object observer.observe(elementtoobserve, {subtree: true, ...
MutationObserver - Web APIs
// select the node that will be observed for mutations const targetnode = document.getelementbyid('some-id'); // options for the observer (which mutations to observe) const config = { attributes: true, childlist: true, subtree: true }; // callback function to execute when mutations are observed const callback = function(mutationslist, observer) { // use traditional 'for loops' for ie 11 for(let mutation of mutationslist) { if (mutation.type === 'childlist') { ...
MutationObserverInit.attributeFilter - Web APIs
tation) { switch(mutation.type) { case "attributes": switch(mutation.attributename) { case "status": userstatuschanged(mutation.target.username, mutation.target.status); break; case "username": usernamechanged(mutation.oldvalue, mutation.target.username); break; } break; } }); } var userlistelement = document.queryselector("#userlist"); var observer = new mutationobserver(callback); observer.observe(userlistelement, { attributefilter: [ "status", "username" ], attributeoldvalue: true, subtree: 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.
MutationObserverInit.attributeOldValue - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a function called notifyuser() is used to tell the user the name of the attribute that changed as well as the attribute's new value (mutation.target[mutation.attributename]) and its old value (mutation.oldvalue).
MutationObserverInit.attributes - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a function called notifyuser() is used to tell the user the name of the attribute that changed as well as the attribute's new value (mutation.target[mutation.attributename]) and its old value (mutation.oldvalue).
NDEFReader.scan() - Web APIs
WebAPINDEFReaderscan
return value a promise that resolves with undefined immediatelly after scheduling read operations for the nfc adapter.
Navigator.oscpu - Web APIs
WebAPINavigatoroscpu
system oscpuinfo string format os/2 os/2 warp x (either 3, 4 or 4.5) windows ce windowsce x.y1 windows 64-bit (64-bit build) windows nt x.y; win64; x64 windows 64-bit (32-bit build) windows nt x.y; wow64 windows 32-bit windows nt x.y mac os x (ppc build) powerpc mac os x version x.y mac os x (i386/x64 build) intel mac os x or macos version x.y linux 64-bit (32-bit build) output of uname -s plus "i686 on x86_64" linux output of uname -sm x.y refers to the version of the operating system example function osinfo() { alert(window.navigator.oscpu); } osinfo(); // alerts "windows nt 6.0" for example usage notes unless your code is privileged (chrome or at least has the u...
Navigator.productSub - Web APIs
example <script> function prodsub() { var dt = document.getelementbyid("d").childnodes[0]; dt.data = window.navigator.productsub; } </script> <button onclick="prodsub();">productsub</button> // returns: 20010725 notes on ie, this property returns undefined.
Navigator.share() - Web APIs
WebAPINavigatorshare
it will reject immediately if the data parameter is not correctly specified, and will also reject if the user cancels sharing.
Navigator.vibrate() - Web APIs
WebAPINavigatorvibrate
you may provide either a single value (to vibrate once for that many milliseconds) or an array of values to alternately vibrate, pause, then vibrate again.
Navigator.wakeLock - Web APIs
while a screen wake lock is active, the user agent will try to prevent the device from dimming the screen, turning it off completely, or showing a screensaver.
navigator.hardwareConcurrency - Web APIs
the browser may, however, choose to report a lower number of logical cores in order to represent more accurately the number of workers that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system.
NavigatorConcurrentHardware - Web APIs
the browser may, however, choose to reduce the number in order to represent more accurately the number of workers that can run at once properties navigatorconcurrenthardware.hardwareconcurrency read only returns the number of logical processors which may be available to the user agent.
NavigatorID.platform - Web APIs
for example: "macintel", "win32", "freebsd i386", "webtv os" example console.log(navigator.platform); usage notes most browsers, including chrome, edge, and firefox 63 and later, return "win32" even if running on a 64-bit version of windows.
NavigatorPlugins.plugins - Web APIs
var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i = 0; i < pluginslength; i++) { let newrow = table.insertrow(); newrow.insertcell().textcontent = navigator.plugins[i].name; newrow.insertcell().textcontent = navigator.plugins[i].filename; newrow.insertcell().textcontent = navigator.plugins[i].description; newrow.insertcell().textcontent = navigator.plugins[i].version?navigator.plugins[i].version:""; ...
NavigatorStorage.storage - Web APIs
the returned object lets you examine and configure persistence of data stores and learn approximately how much more space your browser has available for local storage use.
Node.childNodes - Web APIs
WebAPINodechildNodes
(for example, to get the name of the first childnode: elementnodereference.childnodes[1].nodename.) the document object itself has 2 children: the doctype declaration and the root element, typically referred to as documentelement.
Node.cloneNode() - Web APIs
WebAPINodecloneNode
example let p = document.getelementbyid("para1") let p_prime = p.clonenode(true) notes cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners.
Node.hasChildNodes() - Web APIs
example let foo = document.getelementbyid('foo'); if (foo.haschildnodes()) { // do something with 'foo.childnodes' } polyfill here is one possible polyfill: ;(function(prototype) { prototype.haschildnodes = prototype.haschildnodes || function() { return !!this.firstchild; } })(node.prototype); there are various ways to determine whether the node has a child node: node.haschildnodes() node.firstchild != null (or just node.firstchild) node.childnodes && node.childnodes.length (or node.childnodes.length > 0) specifications ...
Node.isDefaultNamespace() - Web APIs
example var xulns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var el = document.getelementsbytagnamens(xulns, 'textbox')[0]; alert(el.isdefaultnamespace(xulns)); // true specifications specification status comment domthe definition of 'node: isdefaultnamespace' in that specification.
Node.isEqualNode() - Web APIs
WebAPINodeisEqualNode
html <div>this is the first element.</div> <div>this is the second element.</div> <div>this is the first element.</div> <p id="output"></p> css #output { width: 440px; border: 2px solid black; border-radius: 5px; padding: 10px; margin-top: 20px; display: block; } javascript let output = document.getelementbyid("output"); let divlist = document.getelementsbytagname("div"); output.innerhtml += "div 0 equals div 0: " + divlist[0].isequalnode(divlist[0]) + "<br/>"; output.innerhtml += "div 0 equals div 1: " + divlist[0].isequalnode(divlist[1]) + "<br/>"; output.innerhtml += "div 0 equals div 2: " + divlist[0].isequalnode(divlist[2]) + "<br/>"; results specifications specification ...
Node.isSameNode() - Web APIs
WebAPINodeisSameNode
html <div>this is the first element.</div> <div>this is the second element.</div> <div>this is the first element.</div> <p id="output"></p> css #output { width: 440px; border: 2px solid black; border-radius: 5px; padding: 10px; margin-top: 20px; display: block; } javascript let output = document.getelementbyid("output"); let divlist = document.getelementsbytagname("div"); output.innerhtml += "div 0 same as div 0: " + divlist[0].issamenode(divlist[0]) + "<br/>"; output.innerhtml += "div 0 same as div 1: " + divlist[0].issamenode(divlist[1]) + "<br/>"; output.innerhtml += "div 0 same as div 2: " + divlist[0].issamenode(divlist[2]) + "<br/>"; results specifications specification ...
Node.isSupported() - Web APIs
WebAPINodeisSupported
var main = document.getelementbyid('doc'); var output = main.issupported('html', '2.0'); </script> specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'node.issupported()' in that specification.
Node.lastChild - Web APIs
WebAPINodelastChild
syntax var childnode = node.lastchild; example var tr = document.getelementbyid("row1"); var corner_td = tr.lastchild; specifications specification status comment domthe definition of 'node.lastchild' in that specification.
Node.localName - Web APIs
WebAPINodelocalName
syntax name = element.localname name is the local name as a string (see notes below for details) example (must be served with xml content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![cdata[ function test() { var text = document.getelementbyid('text'); var circle = document.getelementbyid('circle'); text.value = "<svg:circle> has:\n" + "localname = '" + circle.localname + "'\n" + "namespaceuri = '" + circle.namespaceuri + "'"; } ]]></script> </head> <body onload="test()"> <svg:svg version="1.1" width="100px" height="100px" viewbox="0 0 100 100"> <svg:circle cx="50" c...
Node.nodeName - Web APIs
WebAPINodenodeName
ement.tagname entity the entity name entityreference the name of entity reference notation the notation name processinginstruction the value of processinginstruction.target text "#text" example given the following markup: <div id="d1">hello world</div> <input type="text" id="t"> and the following script: var div1 = document.getelementbyid("d1"); var text_field = document.getelementbyid("t"); text_field.value = div1.nodename; in xhtml (or any other xml format), text_field's value would read "div".
Node.nodeType - Web APIs
WebAPINodenodeType
var node = document.documentelement.firstchild; if (node.nodetype !== node.comment_node) { console.warn("you should comment your code!"); } specifications specification status comment domthe definition of 'node.nodetype' in that specification.
Node.ownerDocument - Web APIs
example // given a node "p", get the top-level html // child of the document object var d = p.ownerdocument; var html = d.documentelement; specifications specification status comment domthe definition of 'node: ownerdocument' in that specification.
Node.replaceChild() - Web APIs
WebAPINodereplaceChild
var sp1_content = document.createtextnode("new replacement span element."); // apply that content to the new element sp1.appendchild(sp1_content); // build a reference to the existing node to be replaced var sp2 = document.getelementbyid("childspan"); var parentdiv = sp2.parentnode; // replace existing node sp2 with the new span element sp1 parentdiv.replacechild(sp1, sp2); // result: // <div> // <span id="newspan">new replacement span element.</span> // </div> specifications specification status comment domthe definition of 'node: replacechild' in that specification.
Node.setUserData() - Web APIs
WebAPINodesetUserData
example var d = document.implementation.createdocument('', 'test', null); d.documentelement.setuserdata('key', 15, {handle:function (o, k, d, s, ds) {console.log(o+'::'+k+'::'+d+'::'+s+'::'+ds)}}); // 2::key::15::[object element]::[object element] console.log(d.documentelement.getuserdata('key')); // 15 var e = document.importnode(d.documentelement, true); // causes handler to be called console.log(e.getuserdata('key')); // null since user data is not copied specifications ...
NodeIterator - Web APIs
previously it was telling the engine that the nodeiterator was no more used, but this is now useless.
NodeList.item() - Web APIs
WebAPINodeListitem
alternate syntax javascript also offers an array-like bracketed syntax for obtaining an item from a nodelist by index: nodeitem = nodelist[index] example var tables = document.getelementsbytagname("table"); var firsttable = tables.item(1); // or simply tables[1] - returns the second table in the dom specifications specification status comment domthe definition of 'nodelist: item' in that specification.
NodeList.length - Web APIs
WebAPINodeListlength
// all the paragraphs in the document var items = document.getelementsbytagname("p"); // for each item in the list, // append the entire element as a string of html var gross = ""; for (var i = 0; i < items.length; i++) { gross += items[i].innerhtml; } // gross is now all the html for the paragraphs specifications specification status comment domthe definition of 'nodelist: length' in that specification.
NodeList - Web APIs
WebAPINodeList
for example, node.childnodes is live: const 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.
Notification.actions - Web APIs
this is a list of the application-defined actions the user can choose to take immediately within the context of a notification.
NotificationEvent - Web APIs
tells the browser that work is ongoing.
Using the Notifications API - Web APIs
ow.addeventlistener('load', function () { // at first, let's check if we have permission for notification // if not, let's ask for it if (window.notification && notification.permission !== "granted") { notification.requestpermission(function (status) { if (notification.permission !== status) { notification.permission = status; } }); } var button = document.getelementsbytagname('button')[0]; button.addeventlistener('click', function () { // if the user agreed to get notified // let's try to send ten notifications if (window.notification && notification.permission === "granted") { var i = 0; // using an interval cause some browsers (including firefox) are blocking notifications if there are too much in a certain time.
OfflineAudioContext.resume() - Web APIs
the promise resolves immediately because the offlineaudiocontext does not require the audio hardware.
OrientationSensor - Web APIs
examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second.
OscillatorNode.start() - Web APIs
if a value is not included or is less than currenttime, the oscillator starts playing immediately.
OscillatorNode.stop() - Web APIs
if the time is equal to or before the current audio context time, the oscillator will stop playing immediately.
PannerNode.coneInnerAngle - Web APIs
effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currenttime); panner.orientationy.setvalueattime(y1, context.currenttime); panner.orientationz.setvalueattime(z1, context.currenttime); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [...
PannerNode.coneOuterAngle - Web APIs
effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currenttime); panner.orientationy.setvalueattime(y1, context.currenttime); panner.orientationz.setvalueattime(z1, context.currenttime); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [...
PannerNode.coneOuterGain - Web APIs
effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currenttime); panner.orientationy.setvalueattime(y1, context.currenttime); panner.orientationz.setvalueattime(z1, context.currenttime); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [...
PannerNode.orientationX - Web APIs
effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currenttime); panner.orientationy.setvalueattime(y1, context.currenttime); panner.orientationz.setvalueattime(z1, context.currenttime); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [...
PannerNode.orientationY - Web APIs
effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currenttime); panner.orientationy.setvalueattime(y1, context.currenttime); panner.orientationz.setvalueattime(z1, context.currenttime); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [...
PannerNode.orientationZ - Web APIs
effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currenttime); panner.orientationy.setvalueattime(y1, context.currenttime); panner.orientationz.setvalueattime(z1, context.currenttime); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [...
PannerNode.refDistance - Web APIs
nnernode(context); panner.refdistance = refdistance; // set the initial z position, then schedule the ramp panner.positionz.setvalueattime(0, starttime); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(starttime); osc.stop(starttime + note_length); }; // this tone should decay immediately and fairly quickly scheduletesttone(1, context.currenttime); // this tone should decay slower and later than the previous one scheduletesttone(4, context.currenttime + note_length); // this tone should decay only slightly, and only start decaying fairly late scheduletesttone(7, context.currenttime + note_length * 2); after running this code, the resulting waveforms should look something like th...
ParentNode.childElementCount - Web APIs
example var foo = document.getelementbyid('foo'); if (foo.childelementcount > 0) { // do something } polyfill for ie8 & ie9 & safari this property is completely unsupported prior to ie9.
ParentNode.children - Web APIs
example const foo = document.getelementbyid('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagname); } polyfill // overwrites native 'children' prototype.
ParentNode.replaceChildren() - Web APIs
const noselect = document.getelementbyid('no'); const yesselect = document.getelementbyid('yes'); const nobtn = document.getelementbyid('to-no'); const yesbtn = document.getelementbyid('to-yes'); yesbtn.addeventlistener('click', () => { const selectedtransferoptions = document.queryselectorall('#no option:checked'); const existingyesoptions = document.queryselectorall('#yes option'); yesselect.replacechildren(...selected...
Path2D.addPath() - Web APIs
WebAPIPath2DaddPath
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create first path and add a rectangle let p1 = new path2d(); p1.rect(0, 0, 100, 150); // create second path and add a rectangle let p2 = new path2d(); p2.rect(0, 0, 100, 75); // create transformation matrix that moves 200 points to the right let m = document.createelementns('http://www.w3.org/2000/svg', 'svg').createsvgmatrix(); m.a =...
PaymentAddress - Web APIs
paymentaddress.phone read only a domstring specifying the telephone number of the recipient or contact person.
Payment Request API - Web APIs
consistent error handling: the browser can check the validity of card numbers, and can tell the user if a card has expired (or is about to expire).
performance.now() - Web APIs
WebAPIPerformancenow
otherwise, performance.timing.navigationstart + performance.now() will be approximately equal to date.now().
PerformanceEntry.startTime - Web APIs
"resource" - returns the timestamp immediately before the browser starts fetching the resource.
PerformanceResourceTiming.connectEnd - Web APIs
the connectend read-only property returns the timestamp immediately after the browser finishes establishing the connection to the server to retrieve the resource.
PerformanceResourceTiming.workerStart - Web APIs
the workerstart read-only property of the performanceresourcetiming interface returns a domhighrestimestamp immediately before dispatching the fetchevent if a service worker thread is already running, or immediately before starting the service worker thread if it is not already running.
Using the Performance API - Web APIs
function print_json() { var json; var o = document.getelementsbytagname("output")[0]; if (window.performance.tojson === undefined) { json = "window.performance.tojson() is not supported"; o.innerhtml += json + "<br>"; } else { var s; json = window.performance.tojson(); // print the performance object s = json.stringify(json); o.innerhtml = "<p>performance = " + s + "</p>"; // print the performance.timing and perfo...
Using Performance Timeline - Web APIs
function log(s) { var o = document.getelementsbytagname("output")[0]; o.innerhtml += s + " <br>"; } function do_work (n) { for (var i=0 ; i < n; i++) { var m = math.random(); } } function print_perf_entry(pe) { log("..name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } function print_performanceentries() { if (performance.mar...
PluginArray - Web APIs
var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i = 0; i < pluginslength; i++) { let newrow = table.insertrow(); newrow.insertcell().textcontent = navigator.plugins[i].name; newrow.insertcell().textcontent = navigator.plugins[i].filename; newrow.insertcell().textcontent = navigator.plugins[i].description; newrow.insertcell().textcontent = navigator.plugins[i].version?navigator.plugins[i].version:""; ...
PointerEvent.pointerType - Web APIs
targetelement.addeventlistener('pointerdown', function(event) { // call the appropriate pointer type handler switch (event.pointertype) { case 'mouse': process_pointer_mouse(event); break; case 'pen': process_pointer_pen(event); break; case 'touch': process_pointer_touch(event); break; default: console.log(`pointertype ${event.pointertype} is n...
ProgressEvent() - Web APIs
in other words, it tells if the progress is measurable or not.
ProgressEvent.initProgressEvent() - Web APIs
in other words, it tells if the progress is measurable or not.
PromiseRejectionEvent - Web APIs
these events are particularly useful for telemetry and debugging purposes.
PublicKeyCredentialRequestOptions.rpId - Web APIs
if it is not explicitely provided, the user agent will use the value of the current origin's domain.
RTCDTMFSender: tonechange event - Web APIs
this can be done using addeventlistener(): dtmfsender.addeventlistener("tonechange", ev => { let tone = ev.tone; if (tone === "") { tone = "&lt;none&gt;"; } document.getelementbyid("playingtone").innertext = tone; }, false); you can also just set the ontonechange event handler property directly: dtmfsender.ontonechange = function( ev ) { let tone = ev.tone; if (tone === "") { tone = "&lt;none&gt;" } document.getelementbyid("playingtone").innertext = tone; }; specifications specification status comment webrtc 1.0: real-time ...
RTCDTMFSender - Web APIs
the primary purpose for webrtc's dtmf support is to allow webrtc-based communication clients to be connected to a public-switched telephone network (pstn) or other legacy telephone service, including extant voice over ip (voip) services.
RTCDTMFToneChangeEvent.tone - Web APIs
dtmfsender.ontonechange = function( ev ) { let tone = ev.tone; if (tone === "") { tone = "&lt;none&gt;" } document.getelementbyid("playingtone").innertext = tone; }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtmftonechangeevent.tone' in that specification.
RTCDataChannel.bufferedAmount - Web APIs
*/ function showbufferedamount(channel) { let el = document.getelementbyid("buffersize"); el.innerhtml = channel.bufferedamount + " bytes"; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.bufferedamount' in that specification.
RTCDataChannel.label - Web APIs
*/ document.getelementbyid("channel-name").innerhtml = "<span class='channelname'>" + dc.label + "</span>"; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.label' in that specification.
RTCDataChannel.onclose - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("messagechannel")}}; dc.onopen = function(event) { document.getelementbyid("messagebox").disabled = false; document.getelementbyid("sendbutton").disabled = false; }; dc.onclose = function(event) { document.getelementbyid("messagebox").disabled = true; document.getelementbyid("sendbutton").disabled = true; } /* now negotiate the connection, etc...
RTCDataChannel.onopen - Web APIs
let dc = mypeerconnection.createdatachannel("message channel"); dc.onopen = function(event) { let messagebox = document.getelementbyid("messagebox"); let sendbutton = document.getelementbyid("sendbutton"); messagebox.disabled = false; messagebox.focus(); sendbutton.disabled = false; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.onopen' in that specification.
RTCDataChannel: open event - Web APIs
finally, the message input box is focused so the user can immediately begin to type.
RTCDataChannel.send() - Web APIs
in this scenario, the underlying transport is immediately closed.
RTCIceCandidate.port - Web APIs
var candidateloc = { address: candidate.ip, port: candidate.port } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.port' in that specification.
RTCIceCandidate.relatedAddress - Web APIs
here's an sdp attribute line (a-line) describing an ice candidate discovered by the stun server: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 6502 typ srflx raddr 192.168.2.77 rport 32768 generation 0 the remote address, relatedaddress, is the dotted quad (for ipv4) or colon-delineated 64-bit address (for ipv6) immediately following the text "raddr", or "192.168.2.77".
RTCIceCandidate.relatedPort - Web APIs
here's an sdp attribute line (a-line) describing an ice candidate discovered by the stun server: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 6502 typ srflx raddr 192.168.2.77 rport 32768 generation 0 the remote port, relatedport, is the number immediately following the "rport" label on the a-line, or 32768.
RTCIceCandidate.usernameFragment - Web APIs
example although the webrtc infrastructure will filter out obsolete candidates for you after an ice restart, you can do it yourself if you're trying to absolutely minimize the number of messages going back and forth.
RTCIceCandidatePair - Web APIs
var icetransport = pc.getsenders()[0].transport.icetransport; var localproto = document.getelementbyid("local-protocol"); var remoteproto = document.getelementbyid("remote-protocol"); icetransport.onselectedcandidatepairchange = function(event) { var pair = icetransport.getselectedcandidatepair(); localprotocol.innertext = pair.local.protocol.touppercase(); remoteprotocol.innertext = pair.remote.protocol.touppercase(); } specifications specification status comment...
RTCIceCandidatePairStats.priority - Web APIs
note: this property was removed from the specification as its value cannot be guaranteed to be accurately represented in a javascript number.
RTCIceCandidatePairStats.requestsReceived - Web APIs
because there's no way to tell the difference between requests made to check connectivity and requests made to check consent, the returned figure includes both.
RTCIceCandidatePairStats.responsesSent - Web APIs
note: since it isn't possible to tell the difference between connectivity check requests and consent requests, this value includes both.
RTCIceCandidatePairStats.state - Web APIs
this may happen immediately upon being added to the check list.
RTCIceServer.url - Web APIs
WebAPIRTCIceServerurl
mypeerconnection = new rtcpeerconnection({ iceservers: [ { url: "stun:stunserver.example.org" } ] }); unfortunately, the only way to tell ice that the server has a backup domain name of stunserver2.example.org is to add a new entry to the iceservers array for it.
RTCIceTransport.getSelectedCandidatePair() - Web APIs
var icetransport = pc.getsenders()[0].transport.icetransport; var localproto = document.getelementbyid("local-protocol"); var remoteproto = document.getelementbyid("remote-protocol"); icetransport.onselectedcandidatepairchange = function(event) { var pair = icetransport.getselectedcandidatepair(); localprotocol.innertext = pair.local.protocol.touppercase(); remoteprotocol.innertext = pair.remote.protocol.touppercase(); } specifications specification status comment...
RTCIceTransport.onselectedcandidatepairchange - Web APIs
var icetransport = pc.getsenders()[0].transport.icetransport; var localproto = document.getelementbyid("local-protocol"); var remoteproto = document.getelementbyid("remote-protocol"); icetransport.onselectedcandidatepairchange = function(event) { var pair = icetransport.getselectedcandidatepair(); localprotocol.innertext = pair.local.protocol.touppercase(); remoteprotocol.innertext = pair.remote.protocol.touppercase(); } specifications specification status comment...
RTCInboundRtpStreamStats.firCount - Web APIs
this tells the sender to send a full frame instead of a delta frame, so that the receiver can catch up.
RTCInboundRtpStreamStats.nackCount - Web APIs
a nack (negative acknowledgement, also called "generic nack") packet tells the sender that one or more of the rtp packets it sent were lost in transport.
RTCInboundRtpStreamStats - Web APIs
slicount an integer indicating the number of times the receiver sent a slice loss indication (sli) frame to the sender to tell it that one or more consecutive (in terms of scan order) video macroblocks have been lost or corrupted.
RTCOfferOptions.iceRestart - Web APIs
the icerestart property of the rtcofferoptions dictionary is a boolean value which, when true, tells the rtcpeerconnection to start ice renegotiation.
RTCOfferOptions - Web APIs
icerestart optional a boolean which, when set to true, tells createoffer() to generate and use new values for the identifying properties of the sdp it creates, resulting in a request that triggers renegotiation of the ice connection.
RTCOutboundRtpStreamStats.firCount - Web APIs
this tells the sender to send a full frame instead of a delta frame, so that the receiver can catch up.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
if trickling isn't supported, or you aren't able to tell, you can check for a falsy value for this property and then wait until the value of icegatheringstate changes to "completed" before creating and sending the initial offer.
RTCPeerConnection.getIdentityAssertion() - Web APIs
the method returns immediately.
RTCPeerConnection.onicecandidateerror - Web APIs
the event offers properties describing the error to help you handle it appropriately.
RTCPeerConnection.onicegatheringstatechange - Web APIs
the status is simply presented as text in a <div> element: <div id="icestatus"></div> the actual event handler looks like this: pc.onicegatheringstatechange = function() { let label = "unknown"; switch(pc.icegatheringstate) { case "new": case "complete": label = "idle"; break; case "gathering": label = "determining route"; break; } document.getelementbyid("icestatus").innerhtml = label; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.onicegatheringstatechange' in that specification.
RTCPeerConnection.ontrack - Web APIs
pc.ontrack = function(event) { document.getelementbyid("received_video").srcobject = event.streams[0]; document.getelementbyid("hangup-button").disabled = false; }; the first line of our ontrack event handler takes the first stream in the incoming track and sets the srcobject attribute to that.
RTCPeerConnection.removeStream() - Web APIs
example var pc, videostream; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerconnection(); videostream = stream; pc.addstream(stream); } document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removestream(videostream); pc.close(); }, false); ...
RTCPeerConnection.setConfiguration() - Web APIs
the changes are not additive; instead, the new values completely replace the existing ones.
RTCPeerConnection.setLocalDescription() - Web APIs
because descriptions will be exchanged until the two peers agree on a configuration, the description submitted by calling setlocaldescription() does not immediately take effect.
RTCPeerConnection.signalingState - Web APIs
further candidates will be delivered separately later.
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
each one represents approximately one second of time (since that's much time we're waiting between calling networkteststart() and networkteststop()).
RTCRtpCapabilities - Web APIs
its properties are: the browser will only report distinct capability combinations separately.
RTCRtpContributingSource.audioLevel - Web APIs
a value of 1.0 represents 0 dbov (maximum volume), a value of 0.0 represents silence, and a value of 0.5 represents approximately 6 db spl (decibels of sound pressure level) change in the sound pressure level from 0 dbov.
RTCRtpParameters - Web APIs
it is extended separately for senders and receivers in the form of the rtcrtpsendparameters and rtcrtpreceiveparameters dictionaries.
RTCRtpReceiver.getStats() - Web APIs
receiver.getstats().then(function(stats) { document.getelementbyid("lostpackets").innertext = stats.packetslost; }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver.getstats()' in that specification.
RTCRtpSender.getStats() - Web APIs
sender.getstats().then(function(stats) { document.getelementbyid("currentrtt").innertext = stats.roundtriptime; }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.getstats()' in that specification.
RTCRtpStreamStats.firCount - Web APIs
this tells the sender to send a full frame instead of a delta frame, so that the receiver can catch up.
RTCRtpStreamStats.nackCount - Web APIs
a nack (negative acknowledgement, also called "generic nack") packet tells the sender that one or more of the rtp packets it sent were lost in transport.
RTCRtpTransceiver.stop() - Web APIs
usage notes when you call stop() on a transceiver, the sender immediately stops sending media and each of its rtp streams are closed using the rtcp "bye" message.
RTCTrackEvent - Web APIs
peerconnection.addeventlistener("track", e => { let videoelement = document.getelementbyid("videobox"); videoelement.srcobject = e.streams[0]; }, false); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtctrackevent' in that specification.
Range.cloneContents() - Web APIs
syntax documentfragment = range.clonecontents(); example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); documentfragment = range.clonecontents(); document.body.appendchild(documentfragment); specifications specification status comment domthe definition of 'range.clonecontents()' in that specification.
Range.cloneRange() - Web APIs
WebAPIRangecloneRange
syntax clone = range.clonerange(); example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); clone = range.clonerange(); specifications specification status comment domthe definition of 'range.clonerange()' in that specification.
Range.collapse() - Web APIs
WebAPIRangecollapse
example var range = document.createrange(); referencenode = document.getelementsbytagname("div").item(0); range.selectnode(referencenode); range.collapse(true); specifications specification status comment domthe definition of 'range.collapse()' in that specification.
Range.compareBoundaryPoints() - Web APIs
example var range, sourcerange, compare; range = document.createrange(); range.selectnode(document.getelementsbytagname("div")[0]); sourcerange = document.createrange(); sourcerange.selectnode(document.getelementsbytagname("div")[1]); compare = range.compareboundarypoints(range.start_to_end, sourcerange); specifications specification status comment domthe definition of 'range.compareboundarypoints()' in that specification.
Range.comparePoint() - Web APIs
example range = document.createrange(); range.selectnode(document.getelementsbytagname('div').item(0)); returnvalue = range.comparepoint(document.getelementsbytagname('p').item(0), 1); specification specification status comment domthe definition of 'range.comparepoint()' in that specification.
Range.createContextualFragment() - Web APIs
example var tagstring = "<div>i am a div node</div>"; var range = document.createrange(); // make the parent of the first div in the document becomes the context node range.selectnode(document.getelementsbytagname("div").item(0)); var documentfragment = range.createcontextualfragment(tagstring); document.body.appendchild(documentfragment); specification specification status comment dom parsing and serializationthe definition of 'range.createcontextualfragment()' in that specification.
Range.deleteContents() - Web APIs
syntax range.deletecontents() example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); range.deletecontents(); specifications specification status comment domthe definition of 'range.deletecontents()' in that specification.
Range.detach() - Web APIs
WebAPIRangedetach
syntax range.detach(); example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); range.detach(); specifications specification status comment domthe definition of 'range.detach()' in that specification.
Range.getBoundingClientRect() - Web APIs
the bounding client rectangle contains everything selected in the range.</p> css #highlight { background: yellow; position: absolute; z-index: -1; } p { width: 200px; } javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); const clientrect = range.getboundingclientrect(); const highlight = document.getelementbyid('highlight'); highlight.style.left = `${clientrect.x}px`; highlight.style.top = `${clientrect.y}px`; highlight.style.width = `${clientrect.width}px`; highlight.style.height = `${clientrect.height}px`; resul...
Range.getClientRects() - Web APIs
syntax rectlist = range.getclientrects() example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); rectlist = range.getclientrects(); specification specification status comment css object model (cssom) view modulethe definition of 'range.getclientrects()' in that specification.
Range.insertNode() - Web APIs
WebAPIRangeinsertNode
example range = document.createrange(); newnode = document.createelement("p"); newnode.appendchild(document.createtextnode("new node inserted here")); range.selectnode(document.getelementsbytagname("div").item(0)); range.insertnode(newnode); specifications specification status comment domthe definition of 'range.insertnode()' in that specification.
Range.intersectsNode() - Web APIs
example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); var bool = range.intersectsnode(document.getelementsbytagname("p").item(0)); specification specification status comment domthe definition of 'range.intersectnode()' in that specification.
Range.isPointInRange() - Web APIs
example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); bool = range.ispointinrange(document.getelementsbytagname("p").item(0),1); specification specification status comment domthe definition of 'range.ispointinrange()' in that specification.
Range.selectNode() - Web APIs
WebAPIRangeselectNode
example let range = document.createrange(); let referencenode = document.getelementsbytagname('div').item(0); range.selectnode(referencenode); specifications specification status comment domthe definition of 'range.selectnode()' in that specification.
Range.setEnd() - Web APIs
WebAPIRangesetEnd
example const range = document.createrange(); const endnode = document.getelementsbytagname('p').item(3); const endoffset = endnode.childnodes.length; range.setend(endnode, endoffset); setend() is commonly used in conjunction with setstart() to fully configure a range.
Range.setEndAfter() - Web APIs
WebAPIRangesetEndAfter
example var range = document.createrange(); var referencenode = document.getelementsbytagname('div').item(0); range.setendafter(referencenode); specifications specification status comment domthe definition of 'range.setendafter()' in that specification.
Range.setEndBefore() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setendbefore(referencenode); specifications specification status comment domthe definition of 'range.setendbefore()' in that specification.
Range.setStartAfter() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartafter(referencenode); specifications specification status comment domthe definition of 'range.setstartafter()' in that specification.
Range.setStartBefore() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartbefore(referencenode); specifications specification status comment domthe definition of 'range.setstartbefore()' in that specification.
Range.toString() - Web APIs
WebAPIRangetoString
look at the output below.</p> <p id="log"></p> javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); document.getelementbyid('log').textcontent = range.tostring(); result specifications specification status comment domthe definition of 'range.tostring()' in that specification.
ReadableStream - Web APIs
if (done) { // tell the browser that we have finished sending data controller.close(); return; } // get the data and send it to the browser via the controller controller.enqueue(value); push(); }); }; push(); } }); return new response(stream, { headers: { "content-type": "text/html" } }); }); specifications s...
ReadableStreamDefaultController.close() - Web APIs
if you want to completely get rid of the stream and discard any enqueued chunks, you'd use readablestream.cancel() or readablestreamdefaultreader.cancel().
ReadableStreamDefaultReader - Web APIs
if (done) { // tell the browser that we have finished sending data controller.close(); return; } // get the data and send it to the browser via the controller controller.enqueue(value); push(); }); }; push(); } }); return new response(stream, { headers: { "content-type": "text/html" } }); }); specifications s...
ReportingObserver - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constrai...
Reporting API - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constrai...
Request.cache - Web APIs
WebAPIRequestcache
example // download a resource with cache busting, to bypass the cache // completely.
ResizeObserver() - Web APIs
observer a reference to the resizeobserver itself, so it will definitely be accessible from inside the callback, should you need it.
format - Web APIs
f common extensions truedoc-pfr truedoc™ portable font resource .pfr embedded-opentype embedded opentype .eot type-1 postscript™ type 1 .pfb, .pfa truetype truetype .ttf opentype opentype, including truetype open .ttf truetype-gx truetype with gx extensions - speedo speedo - intellifont intellifont - example myglyph.format = "truedoc-pfr"; specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'format' in that specification.
cx - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle cx="50" cy="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.cx); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.cx' in that specification.
cy - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle cy="50" cy="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.cy); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.cy' in that specification.
r - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle r="50" r="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.r); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.r' in that specification.
SVGCircleElement - Web APIs
function clickcircle() { var circle = document.getelementbyid("circle"); // randomly determine if the circle radius will increase or decrease var change = math.random() > 0.5 ?
SVGElement: abort event - Web APIs
the abort event is fired when page loading is stopped before an svg element has been allowed to load completely.
SVGEllipseElement - Web APIs
example svg content <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <ellipse cx="100" cy="100" rx="100" ry="60" id="ellipse" onclick="outputsize();"/> </svg> javascript content function outputsize() { var ellipse = document.getelementbyid("ellipse"); // outputs "horizontal radius: 100 vertical radius: 60" console.log( 'horizontal radius: ' + ellipse.rx.baseval.valueasstring, 'vertical radius: ' + ellipse.ry.baseval.valueasstring ) } result specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgellipseelement' in that specification.
SVGGeometryElement.isPointInFill() - Web APIs
example svg <svg viewbox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelementbyid('circle'); // point not in circle console.log('point at 10,10:', circle.ispointinfill(new dompoint(10, 10))); // point in circle console.log('point at 40,30:', circle.ispointinfill(new dompoint(40, 30))); result specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.ispointinfill()' in that specific...
SVGGeometryElement.isPointInStroke() - Web APIs
example svg <svg viewbox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> <circle cx="83" cy="17" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelementbyid('circle'); // point not in circle console.log('point at 10,10:', circle.ispointinstroke(new dompoint(10, 10))); // point in circle but not stroke console.log('point at 40,30:', circle.ispointinstroke(new dompoint(40, 30))); // point in circle stroke console.log('point at 83,17:', circle.ispointinstroke(new dompoint(83, 17))); result specifications specification status...
SVGGraphicsElement: copy event - Web APIs
ttp://www.w3.org/2000/svg"> <text x="5" y="10" id="text-to-copy">copy this text</text> <foreignobject x="5" y="20" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" placeholder="paste it here"/> </foreignobject> </svg> css input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; } javascript document.getelementsbytagname("text")[0].addeventlistener("copy", evt => { evt.clipboarddata.setdata('text/plain', document.getselection().tostring().touppercase()); evt.preventdefault(); }); result specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation definition that the clipboard events apply to svg elements.
SVGGraphicsElement: paste event - Web APIs
/2000/svg"> <foreignobject x="5" y="-10" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" value="copy this text"/> </foreignobject> <text x="5" y="30" id="element-to-paste-text" tabindex="1">paste it here</text> </svg> css input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; } javascript document.getelementbyid("element-to-paste-text").addeventlistener("paste", evt => { evt.target.textcontent = evt.clipboarddata.getdata("text/plain").touppercase(); evt.preventdefault(); }); result specifications specification status comment scalable vector graphics (svg) 2 candidate recommendation definition that the clipboard events apply to svg elements.
SVGLength - Web APIs
WebAPISVGLength
5 svg_lengthtype_cm = 6 svg_lengthtype_mm = 7 svg_lengthtype_in = 8 svg_lengthtype_pt = 9 svg_lengthtype_pc = 10 normative document svg 1.1 (2nd edition) example <svg height="200" onload="start();" version="1.1" width="200" xmlns="http://www.w3.org/2000/svg"> <script type="text/javascript"><![cdata[ function start() { var rect = document.getelementbyid("myrect"); var val = rect.x.baseval; // read x in pixel and cm units console.log("value: " + val.value + ", valueinspecifiedunits: " + val.unittype + ": " + val.valueinspecifiedunits + ", valueasstring: " + val.valueasstring); // set x = 20pt and read it out in pixel and pt units val.newvaluespecifiedunits(svglength.svg_lengthtype_pt, 20); console.l...
SVGLengthList - Web APIs
any changes made to the item are immediately reflected in the list.
SVGNumberList - Web APIs
any changes made to the item are immediately reflected in the list.
SVGPathSegList - Web APIs
any changes made to the item are immediately reflected in the list.
SVGPoint - Web APIs
WebAPISVGPoint
example // create an svgpoint in the user coordinate system let s = document.getelementbyid("svg-elementid").createsvgpoint(); // then, set the x and y values of the returned svgpoint object // (which is the variable `s`) s.y = 10; s.x = 10; ...
SVGPointList - Web APIs
any changes made to the item are immediately reflected in the list.
The 'X' property - Web APIs
its syntax is the same as that for <length> // rect draws a rectangle with upper left-hand corner at x,y, with width w, and height h, with optional style // standard reference: http://www.w3.org/tr/svg11/shapes.html#rectelement func (svg *svg) rect(x float64, y float64, w float64, h float64, s ...string) { svg.printf(`<rect %s %s`, dim(x, y, w, h, svg.decimals), endstyle(s, emptyclose)) } ​ ...
SVGStringList - Web APIs
any changes made to the item are immediately reflected in the list.
SVGTSpanElement - Web APIs
roke="#d4dde4" stroke-width="2px" /><text x="391" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svggraphicselement</text></a><polyline points="301,89 291,84 291,94 301,89" stroke="#d4dde4" fill="none"/><line x1="291" y1="89" x2="261" y2="89" stroke="#d4dde4"/><a xlink:href="/docs/web/api/svgtextcontentelement" target="_top"><rect x="51" y="65" width="210" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="156" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">svgtextcontentelement</text></a><polyline points="51,89 41,84 41,94 51,89" stroke="#d4dde4" fill="none"/><line x1="41" y1="89" ...
SVGTransform - Web APIs
the matrix object is live, meaning that any changes made to the svgtransform object are immediately reflected in the matrix object and vice versa.
SVGViewElement - Web APIs
each of the domstring values can be associated with the corresponding element using the getelementbyid() method call.
Screen.availHeight - Web APIs
for instance, on a mac whose dock is located at the bottom of screen (which is the default), the value of availheight is approximately the value of height (the total height of the screen in css pixels) minus the heights of the dock and menu bar, as seen in the diagram below.
Screen Capture API - Web APIs
mediatrackconstraints.logicalsurface indicates whether or not the video in the stream represents a logical display surface (that is, one which may not be entirely visible onscreen, or may be completely offscreen).
Selection.addRange() - Web APIs
html <p>i <strong>insist</strong> that you <strong>try</strong> selecting the <strong>strong words</strong>.</p> <button>select strong words</button> javascript let button = document.queryselector('button'); button.addeventlistener('click', function () { let selection = window.getselection(); let strongs = document.getelementsbytagname('strong'); if (selection.rangecount > 0) { selection.removeallranges(); } for (let i = 0; i < strongs.length; i++) { let range = document.createrange(); range.selectnode(strongs[i]); selection.addrange(range); } }); result specifications specification status comment selection apithe definition of 'selection.addrange()' in that ...
Selection.collapse() - Web APIs
*/ var body = document.getelementsbytagname("body")[0]; window.getselection().collapse(body,0); specifications specification status comment selection apithe definition of 'selection.collapse()' in that specification.
Selection.containsNode() - Web APIs
html <p>can you find the secret word?</p> <p>hmm, where <span id="secret" style="color:transparent">secret</span> could it be?</p> <p id="win" hidden>you found it!</p> javascript const secret = document.getelementbyid('secret'); const win = document.getelementbyid('win'); // listen for selection changes document.addeventlistener('selectionchange', () => { const selection = window.getselection(); const found = selection.containsnode(secret); win.toggleattribute('hidden', !found); }); result specifications specification status comment selection apithe definition of '...
Selection.modify() - Web APIs
WebAPISelectionmodify
this makes the behavior more consistent, as well as making it work the same way webkit used to work, but unfortunately they have recently changed their behavior.
Selection.setBaseAndExtent() - Web APIs
er" 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.queryselector('.one'); var two = document.queryselector('.two'); var aoffset = document.getelementbyid('aoffset'); var foffset = document.getelementbyid('foffset'); var button = document.queryselector('button'); var output = document.queryselector('.output'); var selection; button.onclick = function() { try { selection = document.getselection(); selection.setbaseandextent(one, aoffset.value, two, foffset.value); var text = selection.tostring(); output.textcontent = t...
Selection - Web APIs
WebAPISelection
in cross-browser compatible code, it's better to handle them separately.
Sensor APIs - Web APIs
the presence of a sensor api does not tell you whether that api is connected to a real hardware sensor, whether that sensor works, if it's still connected, or even whether the user has granted access to it.
Using server-sent events - Web APIs
he client script is on example.com: const evtsource = new eventsource("//api.example.com/ssedemo.php", { withcredentials: true } ); once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the message event: evtsource.onmessage = function(event) { const newelement = document.createelement("li"); const eventlist = document.getelementbyid("list"); newelement.innerhtml = "message: " + event.data; eventlist.appendchild(newelement); } this code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's html.
ServiceWorker.onstatechange - Web APIs
this is because the statechange // event gets queued, meanwhile the underlying worker may have gone into the waiting // state and will be immediately activated if possible.
ServiceWorkerContainer.ready - Web APIs
it returns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an active worker.
ServiceWorkerContainer - Web APIs
it returns a promise that will never reject, and which waits indefinitely until the serviceworkerregistration associated with the current page has an serviceworkerregistration.active worker.
ServiceWorkerGlobalScope: activate event - Web APIs
globalscope.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); you can also set up the event handler using the serviceworkerglobalscope.onactivate property: globalscope.onactivate = function(event) { ...
ServiceWorkerGlobalScope.onactivate - Web APIs
then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); specifications specification status comment service workersthe definition of 'event handlers' in that specification.
ServiceWorkerGlobalScope.onsync - Web APIs
the attempt to sync is made either immediately if the network is available or as soon as the network becomes available.
ServiceWorkerGlobalScope - Web APIs
the attempt to sync is made either immediately if the network is available or as soon as the network becomes available.
ServiceWorkerRegistration.unregister() - Web APIs
example the following simple example registers a service worker example, but then immediately unregisters it again: if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('registration succeeded.'); registration.unregister().then(function(boolean) { // if boolean = true, unregister is successful }); }).catch(function(error) { // registration ...
ShadowRoot.delegatesFocus - Web APIs
let hostelem = shadow.delegatesfocus; specifications this feature is not currently in a specification.
ShadowRoot.host - Web APIs
WebAPIShadowRoothost
// return the original host element some time later let hostelem = shadow.host; specifications specification status comment domthe definition of 'shadowroot.host' in that specification.
ShadowRoot - Web APIs
the shadowroot interface of the shadow dom api is the root node of a dom subtree that is rendered separately from a document's main dom tree.
SourceBuffer.abort() - Web APIs
saying that, current implementations can be useful in certain situations, when you want to stop the current append (or whatever) operation occuring on a sourcebuffer, and then immediately start performing operations on it again.
SpeechSynthesis.getVoices() - Web APIs
= speechsynthesis.getvoices(); for(var i = 0; i < voices.length; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); document.getelementbyid("voiceselect").appendchild(option); } } populatevoicelist(); if (typeof speechsynthesis !== 'undefined' && speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } html <select id="voiceselect"></select> specifications specification status comment web speech apithe definition of 'getvoices()' in that speci...
Storage.getItem() - Web APIs
WebAPIStoragegetItem
function setstyles() { var currentcolor = localstorage.getitem('bgcolor'); var currentfont = localstorage.getitem('font'); var currentimage = localstorage.getitem('image'); document.getelementbyid('bgcolor').value = currentcolor; document.getelementbyid('font').value = currentfont; document.getelementbyid('image').value = currentimage; htmlelem.style.backgroundcolor = '#' + currentcolor; pelem.style.fontfamily = currentfont; imgelem.setattribute('src', currentimage); } note: to see this used within a real world example, see our web storage demo.
StorageEstimate.quota - Web APIs
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'quota' in that specification.
StorageEstimate.usage - Web APIs
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'usage' in that specification.
StorageManager.estimate() - Web APIs
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'estimate()' in that specification.
Storage API - Web APIs
origin 3's storage unit is completely full; it's reached its quota and can't store any more data without some existing material being removed.
Streams API - Web APIs
related stream apis and operations bytelengthqueuingstrategy provides a built-in byte length queuing strategy that can be used when constructing streams.
SubmitEvent() - Web APIs
then the event is sent to the form, telling the form that it's been submitted by the button.
SubtleCrypto.deriveKey() - Web APIs
lickey) { return window.crypto.subtle.derivekey( { name: "ecdh", public: publickey }, privatekey, { name: "aes-gcm", length: 256 }, false, ["encrypt", "decrypt"] ); } async function agreesharedsecretkey() { // generate 2 ecdh key pairs: one for alice and one for bob // in more normal usage, they would generate their key pairs // separately and exchange public keys securely let aliceskeypair = await window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivekey"] ); let bobskeypair = await window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivekey"] ); // alice then generates a secret key using her priva...
SubtleCrypto.digest() - Web APIs
the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const encoder = new textencoder(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('sha-256', data); return hash; } const digestbuffer = await digestmessage(text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are often represented as hex strings.
SubtleCrypto - Web APIs
errors in security system design and implementation can make the security of the system completely ineffective.
Text.splitText() - Web APIs
WebAPITextsplitText
syntax newnode = textnode.splittext(offset) parameters offset the index immediately before which to break the text node.
TextDecoder.prototype.decode() - Web APIs
html <p>encoded value: <span id="encoded-value"></span></p> <p>decoded value: <span id="decoded-value"></span></p> javascript const encoder = new textencoder(); const array = encoder.encode('€'); // uint8array(3) [226, 130, 172] document.getelementbyid('encoded-value').textcontent = array; const decoder = new textdecoder(); const str = decoder.decode(array); // string "€" document.getelementbyid('decoded-value').textcontent = str; result specifications specification status comment encodingthe definition of 'textdecoder.decode()' in that specification.
TextEncoder.prototype.encodeInto() - Web APIs
}; textencoderprototype["encodeinto"] = polyfill_encodeinto; if (!globaltextencoder) { window["textencoder"] = textencoder; } else if (!(globaltextencoderprototype = globaltextencoder["prototype"])["encodeinto"]) { globaltextencoderinstance = new globaltextencoder; globaltextencoderprototype["encodeinto"] = function(string, u8arr) { // unfortunately, there's no way i can think of to quickly extract the number of bits written and the number of bytes read and such var strlen = string.length|0, u8len = u8arr.length|0; if (strlen < ((u8len >> 1) + 3|0)) { // in most circumstances, this means its safe.
TextMetrics.width - Web APIs
WebAPITextMetricswidth
you can get a textmetrics object using the following code: const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let text = ctx.measuretext('foo'); // textmetrics object text.width; // 16; specifications specification html living standardthe definition of 'textmetrics.width' in that specification.
TextTrack: cuechange event - Web APIs
let texttrackelem = document.getelementbyid("texttrack"); texttrackelem.addeventlistener("cuechange", (event) => { let cues = event.target.track.activecues; }); in addition, you can use the oncuechange event handler: let texttrackelem = document.getelementbyid("texttrack"); texttrackelem.oncuechange = (event) => { let cues = event.target.track.activecues; }); specifications specification status ...
TextTrack.mode - Web APIs
WebAPITextTrackmode
the activecues list is being maintained and events are firing at the appropriate times; the track's text is also being drawn appropriately based on the styling and the track's kind.
TimeRanges.end() - Web APIs
WebAPITimeRangesend
example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded.
TimeRanges.length - Web APIs
WebAPITimeRangeslength
syntax length = timeranges.length; example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded.
TimeRanges.start() - Web APIs
WebAPITimeRangesstart
example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded.
Touch.clientX - Web APIs
WebAPITouchclientX
// register touchstart and touchend listeners for element 'source' var src = document.getelementbyid("source"); var clientx, clienty; src.addeventlistener('touchstart', function(e) { // cache the client x/y coordinates clientx = e.touches[0].clientx; clienty = e.touches[0].clienty; }, false); src.addeventlistener('touchend', function(e) { var deltax, deltay; // compute the change in x and y coordinates.
Touch.clientY - Web APIs
WebAPITouchclientY
// register touchstart and touchend listeners for element 'source' var src = document.getelementbyid("source"); var clientx, clienty; src.addeventlistener('touchstart', function(e) { // cache the client x/y coordinates clientx = e.touches[0].clientx; clienty = e.touches[0].clienty; }, false); src.addeventlistener('touchend', function(e) { var deltax, deltay; // compute the change in x and y coordinates.
Touch.pageX - Web APIs
WebAPITouchpageX
// register a touchmove listeners for the 'source' element var src = document.getelementbyid("source"); src.addeventlistener('touchmove', function(e) { // iterate through the touch points that have moved and log each // of the pagex/y coordinates.
Touch.pageY - Web APIs
WebAPITouchpageY
// register a touchmove listeners for the 'source' element var src = document.getelementbyid("source"); src.addeventlistener('touchmove', function(e) { // iterate through the touch points that have moved and log each // of the pagex/y coordinates.
Touch.radiusX - Web APIs
WebAPITouchradiusX
</div> var src = document.getelementbyid("src"); src.addeventlistener('touchstart', rotate); src.addeventlistener('touchmove', rotate); src.addeventlistener('touchend', rotate); function rotate (e) { var touch = e.changedtouches.item(0); // turn off default event handling e.preventdefault(); // rotate element 'src'.
Touch.screenX - Web APIs
WebAPITouchscreenX
// register a touchstart listeners for the 'source' element var src = document.getelementbyid("source"); src.addeventlistener('touchstart', function(e) { // iterate through the touch points and log each screenx/y coordinate.
Touch.target - Web APIs
WebAPITouchtarget
// register a touchmove listener for the 'source' element var src = document.getelementbyid("source"); src.addeventlistener('touchstart', function(e) { // iterate through the touch points that were activiated // for this element.
Touch - Web APIs
WebAPITouch
touch.rotationangle read only returns the angle (in degrees) that the ellipse described by radiusx and radiusy must be rotated, clockwise, to most accurately cover the area of contact between the user and the surface.
TouchList.item() - Web APIs
WebAPITouchListitem
target = document.getelementbyid("target"); target.addeventlistener('touchstart', function(ev) { // if this touchstart event started on element target, // set touch to the first item in the targettouches list; // otherwise set touch to the first item in the touches list var touch; if (ev.targettouches.length >= 1) touch = ev.targettouches.item(0); else touch = ev.touches.item(0); }, false); s...
TouchList.length - Web APIs
WebAPITouchListlength
target = document.getelementbyid("target"); target.addeventlistener('touchstart', function(ev) { // if this touchstart event started on element target, // set touch to the first item in the targettouches list; // otherwise set touch to the first item in the touches list var touch; if (ev.targettouches.length >= 1) touch = ev.targettouches.item(0); else touch = ev.touches.item(0); }, false); specifications specification status c...
TransformStream - Web APIs
async transform(chunk, controller) { chunk = await chunk switch (typeof chunk) { case 'object': // just say the stream is done i guess if (chunk === null) controller.terminate() else if (arraybuffer.isview(chunk)) controller.enqueue(new uint8array(chunk.buffer, chunk.byteoffset, chunk.bytelength)) else if (array.isarray(chunk) && chunk.every(value => typeof value === 'number')) controller.enqueue(new uint8array(chunk)) else if ('function' === typeof chunk.valueof && chunk.valueof() !== chunk) this.transform(chunk.valueof(), controller) // hack else if ('tojson' in chunk) this.transform(json.stringify(chunk), controller) break ...
URL.origin - Web APIs
WebAPIURLorigin
the exact structure varies depending on the type of url: for http or https urls, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified).
URLUtilsReadOnly.origin - Web APIs
the urlutilsreadonly.origin read-only property is a domstring containing the unicode serialization of the origin of the represented url, that is, for http and https, the scheme followed by '://', followed by the domain, followed by ':', followed by the port (the default port, 80 and 443 respectively, if explicitely specified).
USBDevice.clearHalt() - Web APIs
while (true) { let result = await data.transferin(1, 6); if (result.data && result.data.bytelength === 6) { console.log('channel 1: ' + result.data.getuint16(0)); console.log('channel 2: ' + result.data.getuint16(2)); console.log('channel 5: ' + result.data.getuint16(4)); } if (result.status === 'stall') { console.warn('endpoint stalled.
UserProximityEvent.near - Web APIs
the near property tell if there is an object close to the device (true) or not (false).
validityState.badInput - Web APIs
example <input type="number" id="age"> var input = document.getelementbyid("age"); if (input.validity.badinput) { console.log("bad input detected…"); } else { console.log("content of input ok."); } specifications specification status comment html living standardthe definition of 'validitystate.badinput' in that specification.
Vibration API - Web APIs
each value in the array is converted to an integer, then interpreted alternately as the number of milliseconds the device should vibrate and the number of milliseconds it should not be vibrating.
VideoPlaybackQuality.corruptedVideoFrames - Web APIs
var videoelem = document.getelementbyid("my_vid"); var quality = videoelem.getvideoplaybackquality(); if (quality.corruptedvideoframes/quality.totalvideoframes > 0.05) { downgradevideo(videoelem); } specifications specification status comment media playback qualitythe definition of 'videoplaybackquality: corruptedvideoframes' in that specification.
VideoPlaybackQuality.creationTime - Web APIs
var videoelem = document.getelementbyid("my_vid"); var quality = videoelem.getvideoplaybackquality(); if ((quality.corruptedvideoframes + quality.droppedvideoframes)/quality.totalvideoframes > 0.1) { lostframesthresholdexceeded(); } specifications specification status comment media playback qualitythe definition of 'videoplaybackquality.corruptedvideoframes' in that specification.
VideoPlaybackQuality.droppedVideoFrames - Web APIs
var videoelem = document.getelementbyid("my_vid"); var percentelem = document.getelementbyid("percent"); var quality = videoelem.getvideoplaybackquality(); var droppercent = (quality.droppedvideoframes/quality.totalvideoframes)*100; percentelem.innertext = math.trunc(droppercent).tostring(10); specifications specification status comment media playback qualitythe definition of 'videoplaybackquality.d...
VideoPlaybackQuality.totalFrameDelay - Web APIs
syntax value = videoplaybackquality.totalframedelay; example var videoelt = document.getelementbyid('my_vid'); var quality = videoelt.getvideoplaybackquality(); alert(quality.totalframedelay); ...
VideoPlaybackQuality.totalVideoFrames - Web APIs
var videoelem = document.getelementbyid("my_vid"); var quality = videoelem.getvideoplaybackquality(); if ((quality.corruptedvideoframes + quality.droppedvideoframes)/quality.totalvideoframes > 0.1) { lostframesthresholdexceeded(); } a similar algorithm might be used to attempt to switch to a lower-resolution video that requires less bandwidth, in order to avoid dropping frames.
Visual Viewport API - Web APIs
let pendingupdate = false; function viewporthandler(event) { if (pendingupdate) return; pendingupdate = true; requestanimationframe(() => { pendingupdate = false; var layoutviewport = document.getelementbyid('layoutviewport'); // since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin.
WEBGL_debug_renderer_info - Web APIs
examples with the help of this extension, privileged contexts are able to retrieve debugging information about about the user's graphic driver: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var debuginfo = gl.getextension('webgl_debug_renderer_info'); var vendor = gl.getparameter(debuginfo.unmasked_vendor_webgl); var renderer = gl.getparameter(debuginfo.unmasked_renderer_webgl); console.log(vendor); console.log(renderer); specifications specification status comment webgl_debug_renderer_infothe defi...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var shader = gl.createshader(gl.fragment_shader); gl.shadersource(shader, 'void main() { gl_fragcolor = vec4(gl_fragcoord.x, 0.0, 0.0, 1.0); }'); gl.compileshader(shader); var src = gl.getextension('webgl_debug_shaders').gettranslatedshadersource(shader); console.log(src); // "void main(){ // (gl_fragcolor = vec4(gl_fragcoord.x, 0.0, 0.0,...
WEBGL_lose_context.loseContext() - Web APIs
syntax gl.getextension('webgl_lose_context').losecontext(); examples with this method, you can simulate the webglcontextlost event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').losecontext(); // webglcontextevent event with type "webglcontextlost" is logged.
WEBGL_lose_context.restoreContext() - Web APIs
examples with this method, you can simulate the webglcontextrestored event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').restorecontext(); specifications specification status comment webgl_lose_contextthe definition of 'webgl_lose_context.losecontext' in that specification.
WEBGL_lose_context - Web APIs
examples with this extension, you can simulate the webglcontextlost and webglcontextrestored events: const canvas = document.getelementbyid('canvas'); const gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', (event) => { console.log(event); }); gl.getextension('webgl_lose_context').losecontext(); // webglcontextevent event with type "webglcontextlost" is logged.
WebGL2RenderingContext.getBufferSubData() - Web APIs
exceptions an invalid_value error is generated if: offset + returneddata.bytelength would extend beyond the end of the buffer returneddata is null offset is less than zero.
WebGL2RenderingContext.waitSync() - Web APIs
the webgl2renderingcontext.waitsync() method of the webgl 2 api returns immediately, but waits on the gl server until the given webglsync object is signaled.
WebGLBuffer - Web APIs
when working with webglbuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindbuffer() webglrenderingcontext.createbuffer() webglrenderingcontext.deletebuffer() webglrenderingcontext.isbuffer() examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'webglbuffer' in that specification.
WebGLContextEvent.statusMessage - Web APIs
var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextcreationerror', function(e) { console.log('webgl context creation failed:' + e.statusmessage || 'unknown error'); }, false); specifications specification status comment webgl 1.0the definition of 'webglcontextevent.statusmessage' in that specification.
WebGLContextEvent - Web APIs
examples with the help of the webgl_lose_context extension, you can simulate the webglcontextlost and webglcontextrestored events: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').losecontext(); // webglcontextevent event with type "webglcontextlost" is logged.
WebGLFramebuffer - Web APIs
when working with webglframebuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindframebuffer() webglrenderingcontext.createframebuffer() webglrenderingcontext.deleteframebuffer() webglrenderingcontext.isframebuffer() examples creating a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createframebuffer(); specifications specification status comment webgl 1.0the definition of 'webglframebuffer' in that specification.
WebGLRenderbuffer - Web APIs
when working with webglrenderbuffer objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindrenderbuffer() webglrenderingcontext.createrenderbuffer() webglrenderingcontext.deleterenderbuffer() webglrenderingcontext.isrenderbuffer() examples creating a render buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createrenderbuffer(); specifications specification status comment webgl 1.0the definition of 'webglrenderbuffer' in that specification.
WebGLRenderingContext.bindBuffer() - Web APIs
examples binding a buffer to a target var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); getting current bindings to check the current buffer bindings, query the array_buffer_binding and element_array_buffer_binding constants.
WebGLRenderingContext.bindFramebuffer() - Web APIs
examples binding a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, framebuffer); getting current bindings to check the current frame buffer binding, query the framebuffer_binding constant.
WebGLRenderingContext.bindRenderbuffer() - Web APIs
examples binding a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); gl.bindrenderbuffer(gl.renderbuffer, renderbuffer); getting current bindings to check the current renderbuffer binding, query the renderbuffer_binding constant.
WebGLRenderingContext.bindTexture() - Web APIs
examples binding a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); getting current bindings to check the current texture binding, query the gl.texture_binding_2d or gl.texture_binding_cube_map constants.
WebGLRenderingContext.blendEquationSeparate() - Web APIs
the webglrenderingcontext.blendequationseparate() method of the webgl api is used to set the rgb blend equation and alpha blend equation separately.
WebGLRenderingContext.blendFuncSeparate() - Web APIs
the webglrenderingcontext.blendfuncseparate() method of the webgl api defines which function is used for blending pixel arithmetic for rgb and alpha components separately.
WebGLRenderingContext.bufferData() - Web APIs
examples using bufferdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, 1024, gl.static_draw); getting buffer information to check the current buffer usage and buffer size, use the webglrenderingcontext.getbufferparameter() method.
WebGLRenderingContext.bufferSubData() - Web APIs
examples using buffersubdata var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, 1024, gl.static_draw); gl.buffersubdata(gl.array_buffer, 512, data); specifications specification status comment webgl 1.0the definition of 'buffersubdata' in that specification.
WebGLRenderingContext.canvas - Web APIs
examples canvas element given this <canvas> element: <canvas id="canvas"></canvas> you can get back a reference to it from the webglrenderingcontext using the canvas property: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.canvas; // htmlcanvaselement offscreen canvas example using the experimental offscreencanvas object.
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); // ...
WebGLRenderingContext.createBuffer() - Web APIs
examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'createbuffer' in that specification.
WebGLRenderingContext.createFramebuffer() - Web APIs
examples creating a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); specifications specification status comment webgl 1.0the definition of 'createframebuffer' in that specification.
WebGLRenderingContext.createRenderbuffer() - Web APIs
examples creating a render buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); specifications specification status comment webgl 1.0the definition of 'createrenderbuffer' in that specification.
WebGLRenderingContext.createTexture() - Web APIs
creating a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); specifications specification status comment webgl 1.0the definition of 'createtexture' in that specification.
WebGLRenderingContext.deleteBuffer() - Web APIs
examples deleting a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); // ...
WebGLRenderingContext.deleteFramebuffer() - Web APIs
examples deleting a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); // ...
WebGLRenderingContext.deleteProgram() - Web APIs
examples deleting a program var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var program = gl.createprogram(); // ...
WebGLRenderingContext.deleteRenderbuffer() - Web APIs
examples deleting a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); // ...
WebGLRenderingContext.deleteTexture() - Web APIs
examples deleting a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); // ...
WebGLRenderingContext.disable() - Web APIs
when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard deactivates that primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage.
WebGLRenderingContext.drawingBufferHeight - Web APIs
syntax gl.drawingbufferheight; examples given this <canvas> element: <canvas id="canvas"></canvas> you can get the height of the drawing buffer with the following lines: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.drawingbufferheight; // 150 specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.drawingbufferheight' in that specification.
WebGLRenderingContext.drawingBufferWidth - Web APIs
syntax gl.drawingbufferwidth; examples given this <canvas> element: <canvas id="canvas"></canvas> you can get the width of the drawing buffer with the following lines: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.drawingbufferwidth; // 300 specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.drawingbufferwidth' in that specification.
WebGLRenderingContext.enable() - Web APIs
when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage.
WebGLRenderingContext.getContextAttributes() - Web APIs
examples given this <canvas> element <canvas id="canvas"></canvas> and given this webgl context var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getcontextattributes(); the getcontextattributes method returns an object that describes the attributes set on this context, for example: { alpha: true, antialias: true, depth: true, failifmajorperformancecaveat: false, powerpreference: "default", premultipliedalpha: true, preservedrawingbuffer: false, stencil: false, ...
WebGLRenderingContext.getExtension() - Web APIs
var canvas = document.getelementbyid('canvas'); gl = canvas.getcontext('webgl'); gl.getextension('webgl_lose_context').losecontext(); webgl extensions extensions for the webgl api are registered in the webgl extension registry.
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float); // webglshaderprecisionformat { rangemin: 127, rangemax: 127, precision: 23 } specifications specification status comment webgl 1.0the definition of 'getshaderprecisionformat' in that specification.
WebGLRenderingContext.getSupportedExtensions() - Web APIs
examples var canvas = document.getelementbyid('canvas'); gl = canvas.getcontext('webgl'); var extensions = gl.getsupportedextensions(); // array [ 'angle_instanced_arrays', 'ext_blend_minmax', ...
WebGLRenderingContext.isBuffer() - Web APIs
examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.isbuffer(buffer); specifications specification status comment webgl 1.0the definition of 'isbuffer' in that specification.
WebGLRenderingContext.isContextLost() - Web APIs
examples include: two or more pages are using the gpu, but together place too high a demand on the gpu, so the browser tells the two contexts that they've lost the connection, then selects one of the two to restore access for.
WebGLRenderingContext.isEnabled() - Web APIs
when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage.
WebGLRenderingContext.isFramebuffer() - Web APIs
examples checking a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); gl.isframebuffer(framebuffer); specifications specification status comment webgl 1.0the definition of 'isframebuffer' in that specification.
WebGLRenderingContext.isProgram() - Web APIs
examples checking a program var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var program = gl.createprogram(); // ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
examples checking a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); gl.isrenderbuffer(renderbuffer); specifications specification status comment webgl 1.0the definition of 'isrenderbuffer' in that specification.
WebGLRenderingContext.isShader() - Web APIs
examples checking a shader var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var shader = gl.createshader(gl.vertex_shader); // ...
WebGLRenderingContext.isTexture() - Web APIs
examples checking a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); gl.istexture(texture); specifications specification status comment webgl 1.0the definition of 'istexture' in that specification.
WebGLRenderingContext.readPixels() - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var pixels = new uint8array(gl.drawingbufferwidth * gl.drawingbufferheight * 4); gl.readpixels(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight, gl.rgba, gl.unsigned_byte, pixels); console.log(pixels); // uint8array specifications specification status comment webgl 1.0the definition of 'readpixels' in that spec...
WebGLRenderingContext.viewport() - Web APIs
however, if you resize the canvas, you will need to tell the webgl context a new viewport setting.
WebGLShaderPrecisionFormat.precision - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).precision; // 23 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).precision; // 0 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.precision' in that specification.
WebGLShaderPrecisionFormat.rangeMax - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).rangemax; // 127 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).rangemax; // 24 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.rangemax' in that specification.
WebGLShaderPrecisionFormat.rangeMin - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).rangemin; // 127 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).rangemin; // 24 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.rangemin' in that specification.
WebGLShaderPrecisionFormat - Web APIs
var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float); // webglshaderprecisionformat { rangemin: 127, rangemax: 127, precision: 23 } specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat' in that specification.
WebGLTexture - Web APIs
when working with webgltexture objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.bindtexture() webglrenderingcontext.createtexture() webglrenderingcontext.deletetexture() webglrenderingcontext.istexture() examples creating a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); specifications specification status comment webgl 1.0the definition of 'webgltexture' in that specification.
WebGLUniformLocation - Web APIs
when working with webgluniformlocation objects, the following methods of the webglrenderingcontext are useful: webglrenderingcontext.getuniformlocation() webglrenderingcontext.uniform() examples getting an uniform location var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var location = gl.getuniformlocation(webglprogram, 'uniformname'); specifications specification status comment webgl 1.0the definition of 'webgluniformlocation' in that specification.
Basic scissoring - Web APIs
if they fail the test, they are immediately discarded, no further processing occurs, and pixels are not updated.
Canvas size and WebGL - Web APIs
does not seem to support html5 canvas.</canvas> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : inline-block; width : 120px; height : 80px; margin : auto; padding : 0; border : none; background-color : black; } window.addeventlistener("load", function() { "use strict" var firstcanvas = document.getelementsbytagname("canvas")[0], secondcanvas = document.getelementsbytagname("canvas")[1]; firstcanvas.width = firstcanvas.clientwidth; firstcanvas.height = firstcanvas.clientheight; [firstcanvas, secondcanvas].foreach(function(canvas) { var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.queryselector("p").innerhtml = ...
Simple color animation - Web APIs
stopanimation({type: "click"}); var gl; function drawanimation () { if (!gl) { var canvas = document.getelementbyid("canvas-view"); gl = canvas.getcontext("webgl") ||canvas.getcontext("experimental-webgl"); if (!gl) { clearinterval(timer); alert("failed to get webgl context.\n" + "your browser or device may not support webgl."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a rando...
WebGL by example - Web APIs
we believe that it leads to a more effective learning experience and ultimately a deeper understanding of the underlying concepts.
Matrix math for the web - Web APIs
// create the matrix3d style property from a matrix array function matrixarraytocssmatrix(array) { return 'matrix3d(' + array.join(',') + ')'; } // grab the dom element let moveme = document.getelementbyid('move-me'); // returns a result like: "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 50, 100, 0, 1);" let matrix3drule = matrixarraytocssmatrix(translationmatrix); // set the transform moveme.style.transform = matrix3drule; view on jsfiddle scale matrix a scale matrix makes something larger or smaller in one or more of the three dimensions: width, height, and depth.
Animating textures in WebGL - Web APIs
stead, all it does is create an empty texture object, put a single pixel in it, and set its filtering for later use: function inittexture(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because video has to be download over the internet // they might take a moment until it's ready so // put a single pixel in the texture so we can // use it immediately.
Using shaders to apply color in WebGL - Web APIs
then, drawscene() can have the following added to it so it actually uses these colors when drawing the square: // tell webgl how to pull out the colors from the color buffer // into the vertexcolor attribute.
WebRTC connectivity - Web APIs
signaling unfortunately, webrtc can’t create connections without some sort of server in the middle.
Introduction to WebRTC protocols - Web APIs
you would create a connection with a turn server and tell all peers to send packets to the server which will then be forwarded to you.
Lifetime of a WebRTC session - Web APIs
each peer tells the signaling server that they want to join the same webrtc session (identified by the token established in step 4).
Taking still photos with WebRTC - Web APIs
function startup() { video = document.getelementbyid('video'); canvas = document.getelementbyid('canvas'); photo = document.getelementbyid('photo'); startbutton = document.getelementbyid('startbutton'); get the media stream the next task is to get the media stream: navigator.mediadevices.getusermedia({ video: true, audio: false }) .then(function(stream) { video.srcobject = stream; video.play(); })...
Web Video Text Tracks Format (WebVTT) - Web APIs
in this case, you insert your css rules into the file with each rule preceded by the string "style" all by itelf on a line of text, as shown below: webvtt style ::cue { background-image: linear-gradient(to bottom, dimgray, lightgray); color: papayawhip; } /* style blocks cannot use blank lines nor "dash dash greater than" */ note comment blocks can be used between style blocks.
Movement, orientation, and motion: A WebXR example - Web APIs
the webxr session is toggled on and off by the handler for click events on the button, whose label is appropriately set to either "enter webxr" or "exit webxr".
WebXR Device API - Web APIs
the xrreferencespace coordinate system is expected to remain unchanged through the lifespan of the xrsession.the world has no boundaries and extends infinitely in every direction.
Basic concepts behind Web Audio API - Web APIs
here's a couple of simple examples: var context = new audiocontext(); var buffer = context.createbuffer(2, 22050, 44100); note: in digital audio, 44,100 hz (alternately represented as 44.1 khz) is a common sampling frequency.
Example and tutorial: Simple synth keyboard - Web APIs
we then connect it to the master gain node by calling the new oscillator's oscillatornode.connect() method;, which tells the oscillator where to send its output to.
Using the Web Audio API - Web APIs
controlling sound programmatically from javascript code is covered by browsers' autoplay support policies, as such is likely to be blocked without permission being granted by the user (or a whitelist).
Web Audio API - Web APIs
timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate.
Web Crypto API - Web APIs
errors in security system design and implementation can make the security of the system completely ineffective.
Web Speech API - Web APIs
there are two components to this api: speech recognition is accessed via the speechrecognition interface, which provides the ability to recognize voice context from an audio input (normally via the device's default speech recognition service) and respond appropriately.
Web Storage API - Web APIs
a different storage object is used for the sessionstorage and localstorage for each origin — they function and are controlled separately.
Functions and classes available to Web Workers - Web APIs
48 (48) (yes) (yes) (yes) domrequest and domcursor respectively, these objects represents an ongoing operation (with listeners for reacting to the operation completely successfully, or failing, for example), and an ongoing operation over a list of results.
The structured clone algorithm - Web APIs
it clones by recursing through the input object while maintaining a map of previously visited references, to avoid infinitely traversing cycles.
Window: DOMContentLoaded event - Web APIs
the domcontentloaded event fires when the initial html document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
Window: blur event - Web APIs
WebAPIWindowblur event
click outside the document to lose focus.'; } const log = document.getelementbyid('log'); window.addeventlistener('blur', pause); window.addeventlistener('focus', play); result specifications specification status comment ui events working draft added info that this event is composed.
Window.clearImmediate() - Web APIs
examples let immediateid = setimmediate(() => { // run some code } document.getelementbyid("button") .addeventlistener(() => { clearimmediate(immediateid); }); specifications specification status comment efficient script yielding the definition of 'setimmediate' in that specification.
Window.content - Web APIs
WebAPIWindowcontent
syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getelementsbytagname("div")[0].style.border = "solid red 1px"; specification none.
Window.crypto - Web APIs
WebAPIWindowcrypto
javascript genrandomnumbers = function getrandomnumbers() { var array = new uint32array(10); window.crypto.getrandomvalues(array); var randtext = document.getelementbyid("myrandtext"); randtext.innerhtml = "the random numbers are: " for (var i = 0; i < array.length; i++) { randtext.innerhtml += array[i] + " "; } } html <p id="myrandtext">the random numbers are: </p> <button type="button" onclick='genrandomnumbers()'>generate 10 random numbers</button> result specifications specification status comment web cryptogr...
Window.customElements - Web APIs
ne() method to define and register a new custom element, e.g.: let customelementregistry = window.customelements; customelementregistry.define('my-custom-element', mycustomelement); however, it is usually shortened to something like the following: customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(true)); } } ); see our web-components-examples repo for more usage examples.
Window: focus event - Web APIs
click outside the document to lose focus.'; } const log = document.getelementbyid('log'); window.addeventlistener('blur', pause); window.addeventlistener('focus', play); result specifications specification status comment ui events working draft added info that this event is composed.
Window.frames - Web APIs
WebAPIWindowframes
each item in the window.frames pseudo-array represents the window object corresponding to the given <frame>'s or <iframe>'s content, not the (i)frame dom element (i.e., window.frames[0] is the same thing as document.getelementsbytagname("iframe")[0].contentwindow).
Window.getAttention() - Web APIs
on linux, the behaviour varies from window manager to window manager - some flash the taskbar button, others focus the window immediately.
Window.getComputedStyle() - Web APIs
returned values are sometimes deliberately inaccurate.
Window.getSelection() - Web APIs
htmlinputelement.setselectionrange() or the selectionstart and selectionend properties could be used to work around this.
Window.navigator - Web APIs
WebAPIWindownavigator
refox/61.0" } else if (susrag.indexof("samsungbrowser") > -1) { sbrowser = "samsung internet"; // "mozilla/5.0 (linux; android 9; samsung sm-g955f build/ppr1.180610.011) applewebkit/537.36 (khtml, like gecko) samsungbrowser/9.4 chrome/67.0.3396.87 mobile safari/537.36 } else if (susrag.indexof("opera") > -1 || susrag.indexof("opr") > -1) { sbrowser = "opera"; // "mozilla/5.0 (macintosh; intel mac os x 10_14_0) applewebkit/537.36 (khtml, like gecko) chrome/70.0.3538.102 safari/537.36 opr/57.0.3098.106" } else if (susrag.indexof("trident") > -1) { sbrowser = "microsoft internet explorer"; // "mozilla/5.0 (windows nt 10.0; wow64; trident/7.0; .net4.0c; .net4.0e; zoom 3.6.0; wbx 1.0.0; rv:11.0) like gecko" } else if (susrag.indexof("edge") > -1) { sbrowser = "microsoft edge"; // "...
Window.onmozbeforepaint - Web APIs
notes this event fires immediately before the browser window is repainted, if the event has been requested by one or more scripts calling window.mozrequestanimationframe().
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
the call to opendialog() returns immediately.
Window: popstate event - Web APIs
if the history traversal is being performed with replacement enabled, the entry immediately prior to the destination entry (taking into account the delta parameter on methods such as go()) is removed from the history stack.
Window.print() - Web APIs
WebAPIWindowprint
however in more recent versions of safari, it may return immediately.
Window.sessionStorage - Web APIs
// get the text field that we're going to track let field = document.getelementbyid("field"); // see if we have an autosave value // (this will only happen if the page is accidentally refreshed) if (sessionstorage.getitem("autosave")) { // restore the contents of the text field field.value = sessionstorage.getitem("autosave"); } // listen for changes in the text field field.addeventlistener("change", function() { // and save the results into the session storage ...
Window.setImmediate() - Web APIs
this method is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates.
Window.sidebar - Web APIs
WebAPIWindowsidebar
note: this was made obsolete in firefox 44, and has been removed completely in firefox 59.
WindowEventHandlers - Web APIs
the windoweventhandlers mixin describes the event handlers common to several interfaces like window, or htmlbodyelement and htmlframesetelement.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
it creates a microtask by using a promise that resolves immediately.
Worker - Web APIs
WebAPIWorker
worker.terminate() immediately terminates the worker.
WritableStream.abort() - Web APIs
the abort() method of the writablestream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
WritableStreamDefaultWriter.abort() - Web APIs
the abort() method of the writablestreamdefaultwriter interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
WritableStreamDefaultWriter - Web APIs
methods writablestreamdefaultwriter.abort() aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded.
Synchronous and asynchronous requests - Web APIs
starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable xhr, passed to the success callback function xhrsuccess., and ultimately supplied to the callback function (in this case, showmessage) which is invoked by function xhrsuccess.
Using XMLHttpRequest - Web APIs
these tell the client making the xmlhttprequest important information about the status of the response.
XMLHttpRequest.responseText - Web APIs
while handling an asynchronous request, the value of responsetext always has the current content received from the server, even if it's incomplete because the data has not been completely received yet.
XMLHttpRequestEventTarget.onprogress - Web APIs
the xmlhttprequesteventtarget.onprogress is the function called periodically with information when an xmlhttprequest before success completely.
XMLSerializer - Web APIs
note: in the real world, you should usually instead call importnode() method to import the new node into the dom, then call one of the following methods to add the node to the dom tree: the document and element methods append() and prepend() the node.replacewith() method (to replace an existing node with the new one) the document.insertadjacentelement() and element.insertadjacentelement() methods.
XRBoundedReferenceSpace.boundsGeometry - Web APIs
that said, the bounds extend upward indefinitely, since the bounds are defined in only two dimensions.
XRInputSourceEvent.inputSource - Web APIs
this information lets you handle the event appropriately given the particulars of the user input device being manipulated.
XRSession.onselect - Web APIs
the select event is sent after tracking of the primary action begins, as announced by the selectstart event, and immediately before the tracking of the primary action ends, which is announced by the selectend event.
XRSession.onsqueezeend - Web APIs
this is sent immediately after the squeeze event, which announces the successful completion of the squeeze action.
XRSession.requestAnimationFrame() - Web APIs
if (!xrsession) { renderframe(time, null) } } // the window animation loop can be started immediately upon the page loading.
XRWebGLLayer.ignoreDepthValues - Web APIs
the depth, in tandem with the coordinates of each point being rendered, makes it possible to more accurately represent the scene in the 3d space.
msCapsLockWarningOff - Web APIs
example fiddle: http://jsfiddle.net/jonathansampson/mqcha/1/ example 2 <html> <head> <title>mscapslockwarningoff example</title> <script type="text/javascript"> function capsoff() { if (document.mscapslockwarningoff == false) { document.mscapslockwarningoff = true; document.getelementbyid("caps").innerhtml = "warning off"; } else { document.mscapslockwarningoff = false; document.getelementbyid("caps").innerhtml = "warning on"; } } </script> </head> <body> <label>type a password: <input type="password" /></label><br /> <button id="caps" onclick="capsoff();">warning off</button> </body> </html> ...
msWriteProfilerMark - Web APIs
notes mswriteprofilermark enables you to inject dom based performance markers in addition to existing javascript api to learn exactly when parts of the page are being rendered, building a waterfall view for every one of our impressions showing latency per object, which can be useful for more accurately debugging real users perf issues.
Using the aria-valuenow attribute - Accessibility
when the rendered value cannot be accurately represented as a number, authors should use the aria-valuetext attribute in conjunction with aria-valuenow to provide a user-friendly representation of the range's current value.
Using the aria-valuetext attribute - Accessibility
authors should only set the aria-valuetext attribute when the rendered value cannot be accurately represented as a number.
Using the slider role - Accessibility
valuemin="1" aria-valuemax="7" aria-valuenow="2" aria-valuetext="monday"> </div> </div> the code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes: var daynames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; var updateslider = function (newvalue) { var handle = document.getelementbyid("day-handle"); handle.setattribute("aria-valuenow", newvalue.tostring()); handle.setattribute("aria-valuetext", daynames[newvalue]); }; working examples: slider example notes aria attributes used aria-valuemin aria-valuemax aria-valuenow aria-valuetext aria-orientation related aria techniques compatibility tbd: add support information for common ua and ...
ARIA annotations - Accessibility
les and objects are currently exposed in: firefox from version 75 onwards, on windows and linux (on macos, we are first waiting for apple to define what safari will expose as apple-dialect attributes to voiceover, and will then follow suit.) chrome from version 81 onwards, currently behind the #enable-accessibility-expose-aria-annotations flag (go to chrome://flags to enable this.) unfortunately, you won’t be able to use any of these yet, as screenreader support is currently not there.
ARIA: timer role - Accessibility
<div id="clock" role="timer" aria-live="off">20</div> <button onclick="starttimer('clock')">start</button> /* basic javascript to update a timer */ function starttimer(timername) { // get the number of seconds let timer = document.getelementbyid(timername), seconds = parseint(timer.innertext); // remove a second // updated the content of timer timer.innertext = --seconds // if timer != 0, settimeout if (seconds) { settimeout( function() { starttimer(timername); }, 1000); } } the first time the function executes, the entirety of the string that is added will be announced.
ARIA: Complementary role - Accessibility
labeling landmarks multiple landmarks if there is more than one complementary landmark role or <aside> element in a document, provide a label for each landmark using the aria-label attribute, or, if the aside has an appropriately descriptive title, point to it with the aria-labelledby attribute.
ARIA: document role - Accessibility
generally used in complex composite widgets or applications, the document role can inform assistive technologies to switch context to a reading mode: the document role tells assistive technologies with reading or browse modes to use the document mode to read the content contained within this element.
ARIA: feed role - Accessibility
a feed enables screen readers to use the browse mode reading cursor to both read and scroll through a stream of rich content that may continue scrolling infinitely by loading more content as the user reads.
ARIA: form role - Accessibility
the html <form> element is sufficient to tell assistive technologies that there is a form.
ARIA: Region role - Accessibility
a region role is a more generic term, and should only be used if the section needing to be identified is not accurately described by one of the other landmark roles, such as banner, main, contentinfo, complementary, or navigation.
ARIA: checkbox role - Accessibility
box()" tabindex="0" aria-labelledby="chk1-label"></span> <label id="chk1-label" onclick="changecheckbox()" onkeypress="changecheckbox()">remember my preferences</label> css [role="checkbox"] { padding:5px; } [aria-checked="true"]::before { content: "[x]"; } [aria-checked="false"]::before { content: "[ ]"; } javascript function changecheckbox(event) { let item = document.getelementbyid('chkpref'); switch(item.getattribute('aria-checked')) { case "true": item.setattribute('aria-checked', "false"); break; case "false": item.setattribute('aria-checked', "true"); break; } } accessibility concerns when the checkbox role is added to an element, the user agent should do the following: expose the el...
ARIA: heading role - Accessibility
in addition, the level tells assistive technologies which part of the page structure this heading represents.
Basic form hints - Accessibility
<div> <label for="phone">phone:</label> <input type="text" value="phone" id="phone" aria-required="false"/> </div> <div> <label for="email">* e-mail:</label> <input type="text" value="email" id="email" aria-required="true"/> </div> </form> the script that validates the form entry would look something like this: var validate = function () { var emailelement = document.getelementbyid(emailfieldid); var valid = emailvalid(formdata.email); // returns true if valid, false otherwise emailelement.setattribute("aria-invalid", !valid); setelementbordercolour(emailelement, valid); // sets the border to red if second arg is false }; providing helpful error messages read how to use aria alerts to enhance forms.
Multipart labels: Using ARIA for labels with embedded fields inside them - Accessibility
if you’re using a screen reader, have you noticed that, when you go to this setting in firefox, it tells you “delete history after 21 days”?, followed by the announcement that you’re in a textbox, and that it contains the number 21.
Mobile accessibility checklist - Accessibility
unless absolutely unavoidable, aria-hidden attribute should not be used.
Web Accessibility: Understanding Colors and Luminance - Accessibility
this fact is also used by televsion signals to allocate less bandwidth to the yellow-blue part of their signal, thus saving bandwidth.
-moz-image-rect - CSS: Cascading Style Sheets
function rotate() { var prevstyle = window.getcomputedstyle(document.getelementbyid("box4"), null).getpropertyvalue("background-image"); // now that we've saved the last one, start rotating for (var i=1; i<=4; i++) { var curid = "box" + i; // shift the background images var curstyle = window.getcomputedstyle(document.getelementbyid(curid), null).getpropertyvalue("background-image"); document.getelementbyid(curid).style.backgroundimage = prevstyle...
-moz-outline-radius - CSS: Cascading Style Sheets
html <p>this element has a rounded outline!</p> css p { margin: 5px; border: 1px solid black; outline: dotted red; -moz-outline-radius: 12% 1em 25px; } result notes dotted or dashed radiused corners were rendered as solid until firefox 50, bug 382721 future versions of gecko/firefox may drop this property completely.
:-moz-ui-invalid - CSS: Cascading Style Sheets
however, if the user is trying to correct a previously-flagged value, the control shows immediately when the value becomes valid.
:-moz-ui-valid - CSS: Cascading Style Sheets
however, if the user is trying to correct a previously-flagged value, the control shows immediately when the value becomes valid.
::first-letter (:first-letter) - CSS: Cascading Style Sheets
/* selects the first letter of a <p> */ p::first-letter { font-size: 130%; } the first letter of an element is not always trivial to identify: punctuation that precedes or immediately follows the first letter is included in the match.
::slotted() - CSS: Cascading Style Sheets
WebCSS::slotted
on-name">name missing</slot> <ul> <li><slot name="person-age">age missing</slot></li> <li><slot name="person-occupation">occupation missing</slot></li> </ul> </div> </template> a custom element — <person-details> — is defined like so: customelements.define('person-details', class extends htmlelement { constructor() { super(); let template = document.getelementbyid('person-template'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}); let style = document.createelement('style'); style.textcontent = 'div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }' + 'h2 { margin: 0 0 10px; }' + 'ul { margin: 0; }' + ...
:active - CSS: Cascading Style Sheets
WebCSS:active
to style links appropriately, put the :active rule after all other link-related rules, as defined by the lvha-order: :link — :visited — :hover — :active.
:disabled - CSS: Cascading Style Sheets
WebCSS:disabled
ext" placeholder="name" disabled> <input type="text" placeholder="address" disabled> <input type="text" placeholder="zip code" disabled> </fieldset> </form> css input[type="text"]:disabled { background: #ccc; } javascript // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').onchange = togglebilling; }, false); function togglebilling() { // select the billing text fields var billingitems = document.queryselectorall('#billing input[type="text"]'); // toggle the billing text fields for (var i = 0; i < billingitems.length; i++) { billingitems[i].disabled = !billingitems[i].disabled; } } result specifications sp...
:hover - CSS: Cascading Style Sheets
WebCSS:hover
to style links appropriately, put the :hover rule after the :link and :visited rules but before the :active one, as defined by the lvha-order: :link — :visited — :hover — :active.
:indeterminate - CSS: Cascading Style Sheets
html <div> <input type="checkbox" id="checkbox"> <label for="checkbox">this label starts out lime.</label> </div> <div> <input type="radio" id="radio"> <label for="radio">this label starts out lime.</label> </div> css input:indeterminate + label { background: lime; } javascript var inputs = document.getelementsbytagname("input"); for (var i = 0; i < inputs.length; i++) { inputs[i].indeterminate = true; } progress bar html <progress> css progress { margin: 4px; } progress:indeterminate { opacity: 0.5; background-color: lightgray; box-shadow: 0 0 2px 1px red; } result specifications specification status comment html living standardthe definition...
:link - CSS: Cascading Style Sheets
WebCSS:link
to style links appropriately, put the :link rule before all other link-related rules, as defined by the lvha-order: :link — :visited — :hover — :active.
:nth-child() - CSS: Cascading Style Sheets
the <code>&lt;em&gt;</code> is completely skipped over and ignored.</p> <div class="third"> <span>span!</span> <span>span</span> <em>this is an `em`.</em> <span>span!</span> <span>span</span> <span>span!</span> <span>span</span> <span>span!</span> </div> css html { font-family: sans-serif; } span, div em { padding: 5px; border: 1px solid green; display: inline-block; margin-bottom: 3px; } .first span:nt...
:valid - CSS: Cascading Style Sheets
WebCSS:valid
we then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively.
:visited - CSS: Cascading Style Sheets
WebCSS:visited
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.
@charset - CSS: Cascading Style Sheets
WebCSS@charset
it must be the name of a web-safe character encoding defined in the iana-registry, and must be double-quoted, following exactly one space character (u+0020), and immediately terminated with a semicolon.
@counter-style - CSS: Cascading Style Sheets
if there are either no fallback systems described or if the chain of fallback systems are unable to represent a counter value, then it will ultimately fall back to the decimal style.
font-weight - CSS: Cascading Style Sheets
the font-weight property can separately be used to set how thick or thin characters in text should be displayed.
unicode-range - CSS: Cascading Style Sheets
in the css we are in effect defining a completely separate @font-face that only includes a single character in it, meaning that only this character will be styled with this font.
overflow-block - CSS: Cascading Style Sheets
nullam ac turpis eleifend, fringilla velit ac, aliquam tellus.
overflow-inline - CSS: Cascading Style Sheets
nullam ac turpis eleifend, fringilla velit ac, aliquam tellus.
prefers-color-scheme - CSS: Cascading Style Sheets
alternately, users can create the numeric preference ui.systemusesdarktheme to override the default behavior and return light (value: 0), dark (value: 1), or no-preference (value: 2).
prefers-reduced-motion - CSS: Cascading Style Sheets
changes to this preference take effect immediately.
scripting - CSS: Cascading Style Sheets
WebCSS@mediascripting
none scripting is completely unavailable on the current document.
Attribute selectors - CSS: Cascading Style Sheets
[attr|=value] represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, - (u+002d).
Coordinate systems - CSS: Cascading Style Sheets
let inner = document.queryselector(".inner"); let log = document.queryselector(".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.
Detecting CSS animation support - CSS: Cascading Style Sheets
'from {' + keyframeprefix + 'transform:rotate( 0deg ) }'+ 'to {' + keyframeprefix + 'transform:rotate( 360deg ) }'+ '}'; if( document.stylesheets && document.stylesheets.length ) { document.stylesheets[0].insertrule( keyframes, 0 ); } else { var s = document.createelement( 'style' ); s.innerhtml = keyframes; document.getelementsbytagname( 'head' )[ 0 ].appendchild( s ); } } this code looks at the value of animation; if it's false, we know we need to use our javascript fallback code to perform our animation.
CSS Animations tips and tricks - CSS: Cascading Style Sheets
hows how you'd achieve the aforementioned javascript technique: .slidein { animation-duration: 5s; animation-name: slidein; animation-iteration-count: infinite; } .stopped { animation-name: none; } @keyframes slidein { 0% { margin-left: 0%; } 50% { margin-left: 50%; } 100% { margin-left: 0%; } } <h1 id="watchme">click me to stop</h1> let watchme = document.getelementbyid('watchme') watchme.classname = 'slidein' const listener = (e) => { watchme.classname = 'slidein stopped' } watchme.addeventlistener('click', () => watchme.addeventlistener('animationiteration', listener, false) ) demo https://jsfiddle.net/morenoh149/5ty5a4oy/ ...
Using URL values for the cursor property - CSS: Cascading Style Sheets
an example of the css3 syntax is: .foo { cursor: auto; cursor: url(cursor1.png) 4 12, auto; } .bar { cursor: pointer; cursor: url(cursor2.png) 2 2, pointer; } /* falls back onto 'auto' and 'pointer' in ie, but must be set separately */ the first number is the x-coordinate, and the second number is the y-coordinate.
CSS Box Alignment - CSS: Cascading Style Sheets
ailing individual alignment properties as the css box alignment properties are implemented differently depending on the specification they interact with, refer to the following pages for each layout type for details of how to use the alignment properties with it: box alignment in flexbox box alignment in css grid layout box alignment in multiple-column layout box alignment for block, absolutely positioned and table layout reference css properties justify-content align-content place-content justify-items align-items place-items justify-self align-self place-self row-gap column-gap gap glossary entries cross axis main axis alignment container alignment subject fallback alignment guides css flexbox guide: basic concepts of flexbox css flexbox guide: ali...
Mastering margin collapsing - CSS: Cascading Style Sheets
note that the margins of floating and absolutely positioned elements never collapse.
Spanning and Balancing Columns - CSS: Cascading Style Sheets
column filling and balancing a balanced set of columns is where all columns have approximately the same amount of content.
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
it is expected that this spec will ultimately supersede the properties as defined in flexbox level one.
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
they have been renamed and moved to box alignment in order that they can be used in all layout methods — this will ultimately include flexbox.
Typical use cases of Flexbox - CSS: Cascading Style Sheets
in the future we may not need to make a container a flex container just to centre a single item, as the box alignment properties will ultimately be implemented in block layout.
OpenType font features guide - CSS: Cascading Style Sheets
caution: there are many css attributes defined to leverage font features, but unfortunately many are not fully implemented.
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
grid-row: 2; } <div class="wrapper"> <div class="item1">item 1</div> <div class="item2">item 2</div> <div class="item3">item 3</div> </div> what this demonstrates, is that if you are switching the direction of your text, either for entire pages or for parts of pages, and are using lines: you may want to name your lines, if you do not want the layout to completely switch direction.
Grid template areas - CSS: Cascading Style Sheets
leaving a grid cell empty we have completely filled our grid with areas in this example, leaving no white space.
Using CSS gradients - CSS: Cascading Style Sheets
in the first background declaration we listed every color stop separately.
Consistent list indentation - CSS: Cascading Style Sheets
if the parent is the body, there's a strong chance your bullets will be completely outside the browser window, and thus will not be visible.
Stacking with floated blocks - CSS: Cascading Style Sheets
ng blocks are placed between non-positioned blocks and positioned blocks: the background and borders of the root element descendant non-positioned blocks, in order of appearance in the html floating blocks descendant positioned elements, in order of appearance in the html actually, as you can see in the example below, the background and border of the non-positioned block (div #4) is completely unaffected by floating blocks, but the content is affected.
Stacking context example 1 - CSS: Cascading Style Sheets
inside div #1 there is an absolutely positioned div #2, while in div #3 there is an absolutely positioned div #4, both without z-index properties.
Understanding CSS z-index - CSS: Cascading Style Sheets
last updated date: july 9, 2005 author's note: thanks to wladimir palant and rod whiteley for the review.
Shapes From Images - CSS: Cascading Style Sheets
you could also try removing the background image completely, thus using the gradient purely to create the shape and not displaying it on the page at all.
Introducing the CSS Cascade - CSS: Cascading Style Sheets
WebCSSCascade
all lets you opt to immediately restore all properties to any of their initial (default) state, the state inherited from the previous level of the cascade, a specific origin (the user-agent stylesheet, the author stylesheet, or the user stylesheet), or even to clear the values of the properties entirely.
Layout and the containing block - CSS: Cascading Style Sheets
percentage values that are applied to the width, height, padding, margin, and offset properties of an absolutely positioned element (i.e., which has its position set to absolute or fixed) are computed from the element's containing block.
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.
Cookbook template - CSS: Cascading Style Sheets
this section is deliberately loose as patterns range from the very simple to more complex.
Using media queries - CSS: Cascading Style Sheets
each query in a comma-separated list is treated separately from the others.
Mozilla CSS extensions - CSS: Cascading Style Sheets
opic-halehame -moz-ethiopic-halehame-am -moz-ethiopic-halehame-ti-er -moz-ethiopic-halehame-ti-et -moz-ethiopic-numeric -moz-gujarati -moz-gurmukhi -moz-hangul -moz-hangul-consonant -moz-japanese-formal -moz-japanese-informal -moz-kannada -moz-khmer -moz-lao -moz-malayalam -moz-myanmar -moz-oriya -moz-persian -moz-simp-chinese-formal -moz-simp-chinese-informal -moz-tamil -moz-telugu -moz-thai -moz-trad-chinese-formal -moz-trad-chinese-informal -moz-urdu overflow -moz-scrollbars-none -moz-scrollbars-horizontal -moz-scrollbars-vertical -moz-hidden-unscrollable text-align -moz-center -moz-left -moz-right text-decoration -moz-anchor-decoration -moz-user-select -moz-all -moz-none width, min-width, and max-width -moz-min-conten...
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
this ensures that its width:height ratio is always 3:4, unless it's deliberately scaled to a disproportionate size (that is, by explicitly specifying both width and height that aren't of that ratio).
Syntax - CSS: Cascading Style Sheets
WebCSSSyntax
a property and value pair is called a declaration, and any css engine calculates which declarations apply to every single element of a page in order to appropriately lay it out, and to style it.
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
unfortunately, these valid values can be used, via the var() functional notation, in a context where they might not make sense.
Visual formatting model - CSS: Cascading Style Sheets
an element is called out of flow if it is floated, absolutely positioned, or is the root element.
align-content - CSS: Cascading Style Sheets
afe center</option> <option value="safe right">safe right</option> <option value="unsafe right">unsafe right</option> <option value="safe end">safe end</option> <option value="unsafe end">unsafe end</option> <option value="safe flex-end">safe flex-end</option> <option value="unsafe flex-end">unsafe flex-end</option> </select> </div> javascript var values = document.getelementbyid('values'); var display = document.getelementbyid('display'); var container = document.getelementbyid('container'); values.addeventlistener('change', function (evt) { container.style.aligncontent = evt.target.value; }); display.addeventlistener('change', function (evt) { container.classname = evt.target.value; }); result specifications specification status comm...
background-blend-mode - CSS: Cascading Style Sheets
ion>difference</option> <option>exclusion</option> <option>hue</option> <option>saturation</option> <option>color</option> <option>luminosity</option> </select> #div { width: 300px; height: 300px; background: url('https://mdn.mozillademos.org/files/8543/br.png'),url('https://mdn.mozillademos.org/files/8545/tr.png'); background-blend-mode: screen; } document.getelementbyid("select").onchange = function(event) { document.getelementbyid("div").style.backgroundblendmode = document.getelementbyid("select").selectedoptions[0].innerhtml; } console.log(document.getelementbyid('div')); specifications specification status comment compositing and blending level 1the definition of 'background-blend-mode' in that specification.
background-position-x - CSS: Cascading Style Sheets
]#where <length-percentage> = <length> | <percentage> examples basic example the following example shows a simple background image implementation, with background-position-x and background-position-y used to define the image's horizontal and vertical positions separately.
background-position-y - CSS: Cascading Style Sheets
]#where <length-percentage> = <length> | <percentage> examples basic example the following example shows a simple background image implementation, with background-position-x and background-position-y used to define the image's horizontal and vertical positions separately.
background - CSS: Cascading Style Sheets
the syntax of each layer is as follows: each layer may include zero or one occurrences of any of the following values: <attachment> <bg-image> <position> <bg-size> <repeat-style> the <bg-size> value may only be included immediately after <position>, separated with the '/' character, like this: "center/80%".
border-image-repeat - CSS: Cascading Style Sheets
ry out various border repetition rules on me!</div> <select id="repetition"> <option value="stretch">stretch</option> <option value="repeat">repeat</option> <option value="round">round</option> <option value="space">space</option> <option value="stretch repeat">stretch repeat</option> <option value="space round">space round</option> </select> javascript var repetition = document.getelementbyid("repetition"); repetition.addeventlistener("change", function (evt) { document.getelementbyid("bordered").style.borderimagerepeat = evt.target.value; }); results specifications specification status comment css backgrounds and borders module level 3the definition of 'border-image-repeat' in that specification.
border-image-slice - CSS: Cascading Style Sheets
>30</output> </li> </ul> css .wrapper { width: 400px; height: 300px; } div > div { width: 300px; height: 200px; border-width: 30px; border-style: solid; border-image: url(https://udn.realityripple.com/samples/56/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.queryselector('div > div'); widthslider.addeventlistener('input', () => { const newvalue = widthslider.value + 'px'; divelem.style.borderwidth = newvalue; widthoutput.textc...
box-sizing - CSS: Cascading Style Sheets
border-box tells the browser to account for any border and padding in the values you specify for an element's width and height.
clip-path - CSS: Cascading Style Sheets
WebCSSclip-path
option> <option value="circle(100px at 110px 100px)">circle</option> <option value="url(#cross)" selected>cross</option> <option value="inset(20px round 20px)">inset</option> <option value="path('m 0 200 l 0,110 a 110,90 0,0,1 240,100 l 200 340 z')">path</option> </select> css #clipped { margin-bottom: 20px; clip-path: url(#cross); } javascript const clippathselect = document.getelementbyid("clippath"); clippathselect.addeventlistener("change", function (evt) { document.getelementbyid("clipped").style.clippath = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'clip-path' in that specification.
color-adjust - CSS: Cascading Style Sheets
for whatever reason, this is the desired appearance in any rendering environment, including on paper, so we also use color-adjust: exact to tell the browser not to make color or style adjustments to the box when rendering it.
contain - CSS: Cascading Style Sheets
WebCSScontain
if the containing box is offscreen, the browser does not need to paint its contained elements — these must also be offscreen as they are contained completely by that box.
counter-set - CSS: Cascading Style Sheets
if there isn't currently a counter of the given name on the element, the element will create a new counter of the given name with a starting value of 0 (though it may then immediately set or increment that value to something different).
<custom-ident> - CSS: Cascading Style Sheets
ranch, cjk-heavenly-stem, cjk-ideographic, devanagari, ethiopic-numeric, georgian, gujarati, gurmukhi, hebrew, hiragana, hiragana-iroha, japanese-formal, japanese-informal, kannada, katakana, katakana-iroha, khmer, korean-hangul-formal, korean-hanja-formal, korean-hanja-informal, lao, lower-armenian, malayalam, mongolian, myanmar, oriya, persian, simp-chinese-formal, simp-chinese-informal, tamil, telugu, thai, tibetan, trad-chinese-formal, trad-chinese-informal, upper-armenian, disclosure-open, and disclosure-close.
element() - CSS: Cascading Style Sheets
WebCSSelement
desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetelement() experimentalchrome no support noedge no support nofirefox full support 57prefixed full support 57prefixed prefixed implemented with the vendor prefix: -moz- no support 29 — 57prefixed...
env() - CSS: Cascading Style Sheets
WebCSSenv
to tell the browser to use the whole available space on the screen, and so enabling us to use the env() variables, we need to add a new viewport meta value: <meta name="viewport" content="viewport-fit=cover" /> body { padding: env(safe-area-inset-top, 20px) env(safe-area-inset-right, 20px) env(safe-area-inset-bottom, 20px) env(safe-area-inset-left, 20px); } in addition, unlike custo...
flex - CSS: Cascading Style Sheets
WebCSSflex
| <'flex-basis'> ] examples setting flex: auto html <div id="flex-container"> <div class="flex-item" id="flex">flex box (click to toggle raw box)</div> <div class="raw-item" id="raw">raw box</div> </div> css #flex-container { display: flex; flex-direction: row; } #flex-container > .flex-item { flex: auto; } #flex-container > .raw-item { width: 5rem; } var flex = document.getelementbyid("flex"); var raw = document.getelementbyid("raw"); flex.addeventlistener("click", function() { raw.style.display = raw.style.display == "none" ?
font-family - CSS: Cascading Style Sheets
the glyphs are partially or completely connected, and the result looks more like handwritten pen or brush writing than printed letterwork.
font-kerning - CSS: Cascading Style Sheets
ij</textarea> css div { font-size: 2rem; font-family: serif; } #nokern { font-kerning: none; } #kern { font-kerning: normal; } javascript let input = document.getelementbyid('input'); let kern = document.getelementbyid('kern'); let nokern = document.getelementbyid('nokern'); input.addeventlistener('keyup', function() { kern.textcontent = input.value; /* update content */ nokern.textcontent = input.value; }); kern.textcontent = input.value; /* initialize content */ nokern.textcontent = input.value; specifications specification status ...
font-size - CSS: Cascading Style Sheets
WebCSSfont-size
this is an os-independent and cross-browser way of literally telling the browsers to render the letters at exactly the number of pixels in height that you specified.
grid-area - CSS: Cascading Style Sheets
WebCSSgrid-area
formal definition initial valueas each of the properties of the shorthand:grid-row-start: autogrid-column-start: autogrid-row-end: autogrid-column-end: autoapplies togrid items and absolutely-positioned boxes whose containing block is a grid containerinheritednocomputed valueas each of the properties of the shorthand:grid-row-start: as specifiedgrid-column-start: as specifiedgrid-row-end: as specifiedgrid-column-end: as specifiedanimation typediscrete formal syntax <grid-line> [ / <grid-line> ]{0,3}where <grid-line> = auto | <custom-ident> | [ <integer> && <custom-ident>?
grid-auto-flow - CSS: Cascading Style Sheets
repeat(4, 1fr) / repeat(2, 1fr); grid-auto-flow: column; /* or 'row', 'row dense', 'column dense' */ } #item1 { background-color: lime; grid-row-start: 3; } #item2 { background-color: yellow; } #item3 { background-color: blue; } #item4 { grid-column-start: 2; background-color: red; } #item5 { background-color: aqua; } function changegridautoflow() { var grid = document.getelementbyid("grid"); var direction = document.getelementbyid("direction"); var dense = document.getelementbyid("dense"); var gridautoflow = direction.value === "row" ?
grid-column-end - CSS: Cascading Style Sheets
formal definition initial valueautoapplies togrid items and absolutely-positioned boxes whose containing block is a grid containerinheritednocomputed valueas specifiedanimation typediscrete formal syntax <grid-line>where <grid-line> = auto | <custom-ident> | [ <integer> && <custom-ident>?
grid-column-start - CSS: Cascading Style Sheets
formal definition initial valueautoapplies togrid items and absolutely-positioned boxes whose containing block is a grid containerinheritednocomputed valueas specifiedanimation typediscrete formal syntax <grid-line>where <grid-line> = auto | <custom-ident> | [ <integer> && <custom-ident>?
grid-column - CSS: Cascading Style Sheets
formal definition initial valueas each of the properties of the shorthand:grid-column-start: autogrid-column-end: autoapplies togrid items and absolutely-positioned boxes whose containing block is a grid containerinheritednocomputed valueas each of the properties of the shorthand:grid-column-start: as specifiedgrid-column-end: as specifiedanimation typediscrete formal syntax <grid-line> [ / <grid-line> ]?where <grid-line> = auto | <custom-ident> | [ <integer> && <custom-ident>?
grid-row-end - CSS: Cascading Style Sheets
formal definition initial valueautoapplies togrid items and absolutely-positioned boxes whose containing block is a grid containerinheritednocomputed valueas specifiedanimation typediscrete formal syntax <grid-line>where <grid-line> = auto | <custom-ident> | [ <integer> && <custom-ident>?
grid-row-start - CSS: Cascading Style Sheets
formal definition initial valueautoapplies togrid items and absolutely-positioned boxes whose containing block is a grid containerinheritednocomputed valueas specifiedanimation typediscrete formal syntax <grid-line>where <grid-line> = auto | <custom-ident> | [ <integer> && <custom-ident>?
grid-row - CSS: Cascading Style Sheets
WebCSSgrid-row
formal definition initial valueas each of the properties of the shorthand:grid-row-start: autogrid-row-end: autoapplies togrid items and absolutely-positioned boxes whose containing block is a grid containerinheritednocomputed valueas each of the properties of the shorthand:grid-row-start: as specifiedgrid-row-end: as specifiedanimation typediscrete formal syntax <grid-line> [ / <grid-line> ]?where <grid-line> = auto | <custom-ident> | [ <integer> && <custom-ident>?
grid-template - CSS: Cascading Style Sheets
use grid (as opposed to grid-template) to prevent these values from cascading in seperately.
height - CSS: Cascading Style Sheets
WebCSSheight
if the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto.
justify-content - CSS: Cascading Style Sheets
">baseline</option> <option value="first baseline">first baseline</option> <option value="last baseline">last baseline</option> <option value="space-between" selected>space-between</option> <option value="space-around">space-around</option> <option value="space-evenly">space-evenly</option> <option value="stretch">stretch</option> </select> javascript var justifycontent = document.getelementbyid("justifycontent"); justifycontent.addeventlistener("change", function (evt) { document.getelementbyid("container").style.justifycontent = evt.target.value; }); result specifications specification status comment css box alignment module level 3the definition of 'justify-content' in that specification.
line-height - CSS: Cascading Style Sheets
if the page is zoomed to increase the text size, using a unitless value ensures that the line height will scale proportionately.
list-style-type - CSS: Cascading Style Sheets
一万一千一百一十一 tamil -moz-tamil example telugu -moz-telugu example thai -moz-thai example tibetan * example trad-chinese-formal traditional chinese formal numbering.
list-style - CSS: Cascading Style Sheets
g wcag, guideline 1.3 explanations understanding success criterion 1.3.1 | w3c understanding wcag 2.0 formal definition initial valueas each of the properties of the shorthand:list-style-type: disclist-style-position: outsidelist-style-image: noneapplies tolist itemsinheritedyescomputed valueas each of the properties of the shorthand:list-style-image: none or the image with its uri made absolutelist-style-position: as specifiedlist-style-type: as specifiedanimation typediscrete formal syntax <'list-style-type'> | <'list-style-position'> | <'list-style-image'> examples setting list style type and position html list 1 <ul class="one"> <li>list item1</li> <li>list item2</li> <li>list item3</li> </ul> list 2 <ul class="two"> <li>list item a</li> <li>list item b</li> <li>list...
margin-left - CSS: Cascading Style Sheets
absolutely positioned layout mode flex, inline-flex any any 0, except if there is any positive horizontal free space.
margin-right - CSS: Cascading Style Sheets
absolutely positioned layout mode flex, inline-flex any any 0, except if there is any positive horizontal free space.
mask-clip - CSS: Cascading Style Sheets
WebCSSmask-clip
x</option> <option value="padding-box">padding-box</option> <option value="border-box" selected>border-box</option> <option value="margin-box">margin-box</option> <option value="fill-box">fill-box</option> <option value="stroke-box">stroke-box</option> <option value="view-box">view-box</option> <option value="no-clip">no-clip</option> </select> javascript var clipbox = document.getelementbyid("clipbox"); clipbox.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskclip = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-clip' in that specification.
mask-composite - CSS: Cascading Style Sheets
os.org/files/12676/star.svg); mask-size: 100% 100%; mask-composite: add; /* can be changed in the live sample */ } html <div id="masked"> </div> <select id="compositemode"> <option value="add">add</option> <option value="subtract">subtract</option> <option value="intersect">intersect</option> <option value="exclude">exclude</option> </select> javascript var clipbox = document.getelementbyid("compositemode"); clipbox.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskcomposite = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-composite' in that specification.
mask-mode - CSS: Cascading Style Sheets
WebCSSmask-mode
r-gradient(red, blue); mask-image: url(https://mdn.mozillademos.org/files/12668/mdn.svg); mask-mode: alpha; /* can be changed in the live sample */ } html <div id="masked"> </div> <select id="maskmode"> <option value="alpha">alpha</option> <option value="luminance">luminance</option> <option value="match-source">match-source</option> </select> javascript var maskmode = document.getelementbyid("maskmode"); maskmode.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskmode = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-mode' in that specification.
mask-origin - CSS: Cascading Style Sheets
n"> <option value="content-box">content-box</option> <option value="padding-box">padding-box</option> <option value="border-box" selected>border-box</option> <option value="margin-box">margin-box</option> <option value="fill-box">fill-box</option> <option value="stroke-box">stroke-box</option> <option value="view-box">view-box</option> </select> javascript var origin = document.getelementbyid("origin"); origin.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskorigin = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-origin' in that specification.
mask-position - CSS: Cascading Style Sheets
op</option> <option value="center">center</option> <option value="bottom">bottom</option> <option value="top right" selected>top right</option> <option value="center center">center center</option> <option value="bottom left">bottom left</option> <option value="10px 20px">10px 20px</option> <option value="60% 20%">60% 20%</option> </select> javascript var maskposition = document.getelementbyid("maskposition"); maskposition.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskposition = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-position' in that specification.
mask-repeat - CSS: Cascading Style Sheets
10px; } html content <div id="masked"> </div> <select id="repetition"> <option value="repeat-x">repeat-x</option> <option value="repeat-y">repeat-y</option> <option value="repeat" selected>repeat</option> <option value="space">space</option> <option value="round">round</option> <option value="no-repeat">no-repeat</option> </select> javascript content var repetition = document.getelementbyid("repetition"); repetition.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskrepeat = evt.target.value; }); result multiple mask image support you can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { mask-image: url('mask1.png'), url('mask2.png'); mask-repeat: repeat-x, repeat-y; } each image...
mask-size - CSS: Cascading Style Sheets
WebCSSmask-size
sample */ margin-bottom: 10px; } html <div id="masked"> </div> <select id="masksize"> <option value="auto">auto</option> <option value="40% 80%">40% 80%</option> <option value="50%" selected>50%</option> <option value="200px 100px">200px 100px</option> <option value="cover">cover</option> <option value="contain">contain</option> </select> javascript var masksize = document.getelementbyid("masksize"); masksize.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.masksize = evt.target.value; }); result specifications specification status comment css masking module level 1the definition of 'mask-size' in that specification.
max-height - CSS: Cascading Style Sheets
if the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as none.computed valuethe percentage as specified or the absolute length or noneanimation typea length, percentage or calc(); formal syntax auto | <length> | <percentage> | min-content | max-content | fit-content(<length-percentage>)where <length-percentage> = <length> | <percentage> examples setting max-height using percentage and keyword values ...
min-height - CSS: Cascading Style Sheets
if the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as 0.computed valuethe percentage as specified or the absolute lengthanimation typea length, percentage or calc(); formal syntax auto | <length> | <percentage> | min-content | max-content | fit-content(<length-percentage>)where <length-percentage> = <length> | <percentage> examples setting min-height table { min-height: 75%; } form { min-height: ...
object-fit - CSS: Cascading Style Sheets
the entire object will completely fill the box.
offset - CSS: Cascading Style Sheets
WebCSSoffset
examples animating an element along a path html <div id="offsetelement"></div> css @keyframes move { from { offset-distance: 0%; } to { offset-distance: 100%; } } #offsetelement { width: 50px; height: 50px; background-color: blue; offset: path("m 100 100 l 300 100 l 200 300 z") auto; animation: move 3s linear infinite; } result specifications specification status comment motion path module level 1the ...
repeating-linear-gradient() - CSS: Cascading Style Sheets
it is similar to linear-gradient() and takes the same arguments, but it repeats the color stops infinitely in all directions so as to cover its entire container.
repeating-radial-gradient() - CSS: Cascading Style Sheets
it is similar to radial-gradient() and takes the same arguments, but it repeats the color stops infinitely in all directions so as to cover its entire container, similar to repeating-linear-gradient() .
revert - CSS: Cascading Style Sheets
WebCSSrevert
so to iterate on above example instead of reverting font-weight and color separately you could just revert all of them.
transform-box - CSS: Cascading Style Sheets
//www.w3.org/2000/svg" viewbox="0 0 50 50"> <g> <circle id="center" fill="red" r="1" transform="translate(25 25)" /> <circle id="boxcenter" fill="blue" r=".5" transform="translate(15 15)" /> <rect id="box" x="10" y="10" width="10" height="10" rx="1" ry="1" stroke="black" fill="none" /> </g> </svg> in the css we have an animation that uses a transform to rotate the rectangle infinitely.
scale() - CSS: Cascading Style Sheets
understanding success criterion 2.3.3 | w3c understanding wcag 2.1 examples scaling the x and y dimensions together html <div>normal</div> <div class="scaled">scaled</div> css div { width: 80px; height: 80px; background-color: skyblue; } .scaled { transform: scale(0.7); /* equal to scalex(0.7) scaley(0.7) */ background-color: pink; } result scaling x and y dimensions separately, and translating the origin html <div>normal</div> <div class="scaled">scaled</div> css div { width: 80px; height: 80px; background-color: skyblue; } .scaled { transform: scale(2, 0.5); /* equal to scalex(2) scaley(0.5) */ transform-origin: left; background-color: pink; } result specifications specification status comment css transforms level 1t...
transform-style - CSS: Cascading Style Sheets
.right { background: rgba(210,0,0,.7); transform: 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); } javascript const cube = document.getelementbyid('example-element'); const checkbox = document.getelementbyid('preserve'); checkbox.addeventlistener('change', () => { if(checkbox.checked) { cube.style.transformstyle = 'preserve-3d'; } else { cube.style.transformstyle = 'flat'; } }) result specifications specification status comment css transforms level 2the definition of 'transform-style'...
will-change - CSS: Cascading Style Sheets
var el = document.getelementbyid('element'); // set will-change when the element is hovered el.addeventlistener('mouseenter', hintbrowser); el.addeventlistener('animationend', removehint); function hintbrowser() { // the optimizable properties that are going to change // in the animation's keyframes block this.style.willchange = 'transform, opacity'; } function removehint() { this.style.willchange = 'auto'; }...
CSS: Cascading Style Sheets
WebCSS
from css3, the scope of the specification increased significantly and the progress on different css modules started to differ so much, that it became more effective to develop and release recommendations separately per module.
Event reference
show mouseevent html5 a contextmenu event was fired on (or bubbled to) an element that has a contextmenu attribute slotchange event dom the node contents of a htmlslotelement (<slot>) have changed.
Community - Developer guides
WebGuideAJAXCommunity
ajax resources ajax workshops and courses skillsmatter.com: courses and events on javascript, ajax, and reverse ajax technologies telerik.com: an active community forum for ajax community.tableau.com: community support forum and courses available for ajax codementor.io: social platform with ajax forums and tutorials lynda.com: tutorials available for learning the fundamentals of ajax ajax interview questions and answer and answerinterwiki links ...
Web Audio playbackRate explained - Developer guides
dn.realityripple.com/samples/6f/08625b424a.m4v" type='video/mp4' /> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type='video/webm' /> </video> <form> <input id="pbr" type="range" value="1" min="0.5" max="4" step="0.1" > <p>playback rate <span id="currentpbr">1</span></p> </form> and apply some javascript to it: window.onload = function () { var v = document.getelementbyid("myvideo"); var p = document.getelementbyid("pbr"); var c = document.getelementbyid("currentpbr"); p.addeventlistener('input',function(){ c.innerhtml = p.value; v.playbackrate = p.value; },false); }; finally, we listen for the input event firing on the <input> element, allowing us to react to the playback rate control being changed.
Challenge solutions - Developer guides
the following script achieves the desired result: // javascript demonstration function dodemo (button) { var square = document.getelementbyid("square"); square.style.backgroundcolor = "#fa4"; square.style.marginleft = "20em"; button.setattribute("disabled", "true"); settimeout(cleardemo, 2000, button); } function cleardemo (button) { var square = document.getelementbyid("square"); square.style.backgroundcolor = "transparent"; square.style.marginleft = "0em"; button.removeattribute("disabled"); } svg and ...
Creating and triggering events - Developer guides
function simulateclick() { const event = new mouseevent('click', { view: window, bubbles: true, cancelable: true }); const cb = document.getelementbyid('checkbox'); const cancelled = !cb.dispatchevent(event); if (cancelled) { // a handler called preventdefault.
Media events - Developer guides
you can easily watch for these events, using code such as the following: var v = document.getelementsbytagname("video")[0]; v.addeventlistener("seeked", function() { v.play(); }, true); v.currenttime = 10.0; this example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes.
Overview of events and handlers - Developer guides
this pattern can easily be followed using completely custom code, as explained in the article on custom events.
Event developer guide - Developer guides
WebGuideEvents
unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.
Mobile-friendliness - Developer guides
for example, it is absolutely critical to keep in mind which browsers and devices you will target when picking a mobile strategy.
User input and controls - Developer guides
bear in mind that many browsers still implement this with a vendor prefix, so you will probably need to fork your code something like this: var elem = document.getelementbyid("myvideo"); if (elem.requestfullscreen) { elem.requestfullscreen(); } else if (elem.msrequestfullscreen) { elem.msrequestfullscreen(); } else if (elem.mozrequestfullscreen) { elem.mozrequestfullscreen(); } else if (elem.webkitrequestfullscreen) { elem.webkitrequestfullscreen(); } note: to find more out about adding fullscreen functionality your application, read our documentati...
Writing forward-compatible websites - Developer guides
unfortunately, libraries are common transgressors of these guidelines.
Developer guides
this set of guides tells you all you need to know about pwas.
HTML attribute: crossorigin - HTML: Hypertext Markup Language
example: crossorigin with the script element you can use the following <script> element to tell a browser to execute the https://example.com/example-framework.js script without sending user-credentials.
HTML attribute: readonly - HTML: Hypertext Markup Language
the readonly attribute is supported by text, search, url, tel, email, password, date, month, week, time, datetime-local, and number<input> types and the <textarea> form control elements.
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
this tells the browser to request cross-origin access when trying to download the image data.
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
it makes logical sense — <h1> is the most important heading, and tells you what the purpose of the overall page is.
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
WebHTMLElementapplet
dom interface htmlappletelement attributes align this attribute is used to position the applet on the page relative to content that might flow around it.
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
WebHTMLElementbdi
the html bidirectional isolate element (<bdi>) tells the browser's bidirectional algorithm to treat the text it contains in isolation from its surrounding text.
<body>: The Document Body element - HTML: Hypertext Markup Language
WebHTMLElementbody
the end tag may be omitted if the <body> element has contents or has a start tag, and is not immediately followed by a comment.
<caption>: The Table Caption element - HTML: Hypertext Markup Language
WebHTMLElementcaption
tag omission the end tag can be omitted if the element is not immediately followed by ascii whitespace or a comment.
<cite>: The Citation element - HTML: Hypertext Markup Language
WebHTMLElementcite
usage notes in the context of the <cite> element, a creative work that might be cited could be, for example, one of the following: a book a research paper an essay a poem a musical score a song a play or film script a film a television show a game a sculpture a painting a theatrical production a play an opera a musical an exhibition a legal case report a computer program a web site a web page a blog post or comment a forum post or comment a tweet a facebook post a written or oral statement and so forth.
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementcontent
dom interface htmlcontentelement attributes this element includes the global attributes.
<datalist>: The HTML Data List element - HTML: Hypertext Markup Language
WebHTMLElementdatalist
implicit aria role listbox permitted aria roles no role permitted dom interface htmldatalistelement attributes this element has no other attributes than the global attributes, common to all elements.
<dd>: The Description Details element - HTML: Hypertext Markup Language
WebHTMLElementdd
the end tag may be omitted if the <dd> element is immediately followed by another <dd> element or a <dt> element, or if there is no more content in the parent element.
<del>: The Deleted Text element - HTML: Hypertext Markup Language
WebHTMLElementdel
del::before, del::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } del::before { content: " [deletion start] "; } del::after { content: " [deletion end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity.
<details>: The Details disclosure element - HTML: Hypertext Markup Language
WebHTMLElementdetails
note: unfortunately, at this time there's no built-in way to animate the transition between open and closed.
<dl>: The Description List element - HTML: Hypertext Markup Language
WebHTMLElementdl
implicit aria role no corresponding role permitted aria roles group, list, none, presentation dom interface htmldlistelement attributes this element only includes the global attributes.
<dt>: The Description Term element - HTML: Hypertext Markup Language
WebHTMLElementdt
the end tag may be omitted if this element is immediately followed by another <dt> or a <dd> element, or if there is no more content in the parent element.
<element>: The Custom Element element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementelement
desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetelement deprecatednon-standardchrome ?
<fieldset>: The Field Set element - HTML: Hypertext Markup Language
WebHTMLElementfieldset
implicit aria role group permitted aria roles radiogroup, presentation, none dom interface htmlfieldsetelement specifications specification status comment html living standardthe definition of '<fieldset>' in that specification.
<font> - HTML: Hypertext Markup Language
WebHTMLElementfont
dom interface this element implements the htmlfontelement interface.
<html>: The HTML Document / Root element - HTML: Hypertext Markup Language
WebHTMLElementhtml
the end tag may be omitted if the <html> element is not immediately followed by a comment.
<i>: The Idiomatic Text element - HTML: Hypertext Markup Language
WebHTMLElementi
be sure the text in question is not actually more appropriately marked up with another element.
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
WebHTMLElementiframe
loading indicates how the browser should load the iframe: eager: load the iframe immediately, regardless if it is outside the visible viewport (this is the default value).
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
you should be aware of this behavior so your code can respond appropriately in either case.
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
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.
<input type="hidden"> - HTML: Hypertext Markup Language
WebHTMLElementinputhidden
hidden inputs are completely invisible in the rendered page, and there is no way to make it visible in the page's content.
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
its value can, however, still be changed by javascript code directly setting the htmlinputelement.value property.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
this might not be a look you'd want in a real web application, but it definitely shows off the possibilities.
<input type="range"> - HTML: Hypertext Markup Language
WebHTMLElementinputrange
standards according to the specification, making it vertical requires adding css to change the dimensions of the control so that it's taller than it is wide, like this: css #volume { height: 150px; width: 50px; } html <input type="range" id="volume" min="0" max="11" value="7" step="1"> result screenshotlive sample unfortunately, no major browsers currently support vertical range controls directly.
<ins> - HTML: Hypertext Markup Language
WebHTMLElementins
ins::before, ins::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } ins::before { content: " [insertion start] "; } ins::after { content: " [insertion end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity.
<li> - HTML: Hypertext Markup Language
WebHTMLElementli
tag omission the end tag can be omitted if the list item is immediately followed by another <li> element, or if there is no more content in its parent element.
<mark>: The Mark Text element - HTML: Hypertext Markup Language
WebHTMLElementmark
mark::before, mark::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } mark::before { content: " [highlight start] "; } mark::after { content: " [highlight end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity.
<optgroup> - HTML: Hypertext Markup Language
WebHTMLElementoptgroup
the end tag is optional if this element is immediately followed by another <optgroup> element, or if the parent element has no more content.
<option>: The HTML Option element - HTML: Hypertext Markup Language
WebHTMLElementoption
the end tag is optional if this element is immediately followed by another <option> element or an <optgroup>, or if the parent element has no more content.
<output>: The Output element - HTML: Hypertext Markup Language
WebHTMLElementoutput
implicit aria role status permitted aria roles any dom interface htmloutputelement attributes this element includes the global attributes.
<p>: The Paragraph element - HTML: Hypertext Markup Language
WebHTMLElementp
the end tag may be omitted if the <p> element is immediately followed by an <address>, <article>, <aside>, <blockquote>, <div>, <dl>, <fieldset>, <footer>, <form>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <header>, <hr>, <menu>, <nav>, <ol>, <pre>, <section>, <table>, <ul> or another <p> element, or if there is no more content in the parent element and the parent element is not an <a> element.
<rt>: The Ruby Text element - HTML: Hypertext Markup Language
WebHTMLElementrt
tag omission the end tag may be omitted if the <rt> element is immediately followed by an <rt> or <rp> element, or if there is no more content in the parent element permitted parents a <ruby> element.
<rtc>: The Ruby Text Container element - HTML: Hypertext Markup Language
WebHTMLElementrtc
tag omission the closing tag can be omitted if it is immediately followed by a <rb>, <rtc> or <rt> element opening tag or by its parent closing tag.
<s> - HTML: Hypertext Markup Language
WebHTMLElements
s::before, s::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } s::before { content: " [start of stricken text] "; } s::after { content: " [end of stricken text] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity.
<section>: The Generic Section element - HTML: Hypertext Markup Language
WebHTMLElementsection
if it makes sense to separately syndicate the content of a <section> element, use an <article> element instead.
<select>: The HTML Select element - HTML: Hypertext Markup Language
WebHTMLElementselect
implicit aria role combobox with no multiple attribute and no size attribute greater than 1, otherwise listbox permitted aria roles menu with no multiple attribute and no size attribute greater than 1, otherwise no role permitted dom interface htmlselectelement specifications specification status comments html living standardthe definition of '<select>' in that specification.
<slot> - HTML: Hypertext Markup Language
WebHTMLElementslot
permitted parents any element that accepts phrasing content implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlslotelement attributes this element includes the global attributes.
<style>: The Style Information element - HTML: Hypertext Markup Language
WebHTMLElementstyle
nonce a cryptographic nonce (number used once) used to whitelist inline styles in a style-src content-security-policy.
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
WebHTMLElementtd
the end tag may be omitted, if it is immediately followed by a <th> or <td> element or if there are no more data in its parent element.
<textarea> - HTML: Hypertext Markup Language
WebHTMLElementtextarea
possible values are: none: completely disables automatic capitalization.
<th> - HTML: Hypertext Markup Language
WebHTMLElementth
the end tag may be omitted, if it is immediately followed by a <th> or <td> element or if there are no more data in its parent element.
<thead>: The Table Head element - HTML: Hypertext Markup Language
WebHTMLElementthead
the end tag may be omitted if the <thead> element is immediately followed by a <tbody> or <tfoot> element.
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
end tag may be omitted if the <tr> element is immediately followed by a <tr> element, or if the row is the last element in its parent table group (<thead>, <tbody> or <tfoot>) element permitted parents <table> (only if the table has no child <tbody> element, and even then only after any <caption>, <colgroup>, and <thead> elements); otherwise, the parent must be <thead>, <tbody> or <tfoot> implicit aria role row permitte...
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
WebHTMLElementtrack
let texttrackelem = document.getelementbyid("texttrack"); texttrackelem.addeventlistener("cuechange", (event) => { let cues = event.target.track.activecues; }); in addition, you can use the oncuechange event handler: let texttrackelem = document.getelementbyid("texttrack"); texttrackelem.oncuechange = (event) => { let cues = event.target.track.activecues; }); examples <video controls poster="/images/sample.gif"> <sou...
<ul>: The Unordered List element - HTML: Hypertext Markup Language
WebHTMLElementul
implicit aria role list permitted aria roles directory, group, listbox, menu, menubar, none, presentation, radiogroup, tablist, toolbar, tree dom interface htmlulistelement attributes this element includes the global attributes.
<xmp> - HTML: Hypertext Markup Language
WebHTMLElementxmp
it was completely removed from the language in html5.
class - HTML: Hypertext Markup Language
classes allow css and javascript to select and access specific elements via the class selectors or functions like the dom method document.getelementsbyclassname.
contextmenu - HTML: Hypertext Markup Language
i am learning contextmenu from mdn via mozilla"); } function shareviafacebook() { window.open("https://facebook.com/sharer/sharer.php?u=" + "https://developer.mozilla.org/en/html/element/using_html_context_menus"); } function incfont() { document.getelementbyid("fontsizing").style.fontsize = "larger"; } function decfont() { document.getelementbyid("fontsizing").style.fontsize = "smaller"; } function changeimage() { var index = math.ceil(math.random() * 39 + 1); document.images[0].src = "https://developer.mozilla.org/media/img/promote/promobutton_mdn" + index + ".png"; } result specifications specification st...
itemprop - HTML: Hypertext Markup Language
etween the following two examples <figure> <img src="castle.jpeg"> <figcaption><span itemscope><span itemprop="name">the castle</span></span> (1986)</figcaption> </figure> <span itemscope><meta itemprop="name" content="the castle"></span> <figure> <img src="castle.jpeg"> <figcaption>the castle (1986)</figcaption> </figure> both have a figure with a caption, and both, completely unrelated to the figure, have an item with a name-value pair with the name "name" and the value "the castle".
x-ms-format-detection - HTML: Hypertext Markup Language
existing links, such as ones with the tel: scheme, are unaffected.
Inline elements - HTML: Hypertext Markup Language
for example, by changing the value of display from "inline" to "block", you can tell the browser to render the inline element in a block box rather than an inline box, and vice versa.
Link types - HTML: Hypertext Markup Language
<link> <a>, <area>, <form> preload tells the browser to download a resource because this resource will be needed later during the current navigation.
Microformats - HTML: Hypertext Markup Language
prefixes are syntax independent from vocabularies, which are developed separately.
MIME types (IANA media types) - HTTP
0/" method="post" enctype="multipart/form-data"> <label>name: <input name="mytextfield" value="test"></label> <label><input type="checkbox" name="mycheckbox"> check</label> <label>upload file: <input type="file" name="myfile" value="test.txt"></label> <button>send the file</button> </form> will send this message: post / http/1.1 host: localhost:8000 user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language: en-us,en;q=0.5 accept-encoding: gzip, deflate connection: keep-alive upgrade-insecure-requests: 1 content-type: multipart/form-data; boundary=---------------------------8721656041911415653955004498 content-length: 465 -----------------------------8721656041...
Basics of HTTP - HTTP
connection management in http/2 http/2 completely revisited how connections are created and maintained.
HTTP caching - HTTP
WebHTTPCaching
in addition, it can help google and other search engines to discover the mobile version of a page, and might also tell them that no cloaking is intended.
HTTP conditional requests - HTTP
the client first reads the original files, modifies them, and finally pushes them to the server: unfortunately, things get a little inaccurate as soon as we take into account concurrency.
Access-Control-Allow-Credentials - HTTP
the access-control-allow-credentials response header tells browsers whether to expose the response to frontend javascript code when the request's credentials mode (request.credentials) is include.
CSP: base-uri - HTTP
use this sparingly and definitely not for scripts.
CSP: connect-src - HTTP
use this sparingly and definitely not for scripts.
CSP: default-src - HTTP
use this sparingly and definitely not for scripts.
CSP: form-action - HTTP
use this sparingly and definitely not for scripts.
CSP: frame-ancestors - HTTP
use this sparingly and definitely not for scripts.
CSP: img-src - HTTP
use this sparingly and definitely not for scripts.
CSP: navigate-to - HTTP
use this sparingly and definitely not for scripts.
CSP: prefetch-src - HTTP
use this sparingly and definitely not for scripts.
CSP: script-src-attr - HTTP
use this sparingly and definitely not for scripts.
CSP: script-src-elem - HTTP
use this sparingly and definitely not for scripts.
CSP: style-src-attr - HTTP
use this sparingly and definitely not for scripts.
CSP: style-src-elem - HTTP
use this sparingly and definitely not for scripts.
Public-Key-Pins - HTTP
max-age=5184000 tells the client to store this information for two months, which is a reasonable time limit according to the ietf rfc.
Set-Cookie - HTTP
a zero or negative number will expire the cookie immediately.
Vary - HTTP
WebHTTPHeadersVary
it can help google and other search engines to discover the mobile version of a page, and might also tell them that no cloaking is intended.
WWW-Authenticate - HTTP
charset=<charset> tells the client the server's prefered encoding scheme when submitting a username and password.
X-Content-Type-Options - HTTP
this is a way to opt out of mime type sniffing, or, in other words, to say that the mime types are deliberately configured.
HTTP headers - HTTP
WebHTTPHeaders
large-allocation tells the browser that the page being loaded is going to want to perform a large allocation.
HTTP Messages - HTTP
WebHTTPMessages
it can be an absolute path, ultimately followed by a '?' and query string.
Proxy Auto-Configuration (PAC) file - HTTP
le will work in an environment where the internal dns server is set up so that it can only resolve internal host names, and the goal is to use a proxy only for hosts that aren't resolvable: function findproxyforurl(url, host) { if (isresolvable(host)) return "direct"; else return "proxy proxy.mydomain.com:8080"; } the above requires consulting the dns every time; it can be grouped intelligently with other rules so that dns is consulted only if other rules do not yield a result: function findproxyforurl(url, host) { if ( isplainhostname(host) || dnsdomainis(host, ".mydomain.com") || isresolvable(host) ) { return "direct"; } else { return "proxy proxy.mydomain.com:8080"; } } example 4 subnet based decisions in this example all of the hosts in a give...
205 Reset Content - HTTP
WebHTTPStatus205
the http 205 reset content response status tells the client to reset the document view, so for example to clear the content of a form, reset a canvas state, or to refresh the ui.
406 Not Acceptable - HTTP
WebHTTPStatus406
it is assumed that even if the user won't be completely happy, they will prefer this to an error code.
451 Unavailable For Legal Reasons - HTTP
WebHTTPStatus451
any attempt to identify the entity ultimately responsible for the resource being unavailable belongs in the response body, not in the rel="blocked-by" link.
501 Not Implemented - HTTP
WebHTTPStatus501
this status can also send a retry-after header, telling the requester when to check back to see if the functionality is supported by then.
HTTP
WebHTTP
http is a stateless protocol, meaning that the server does not keep any data (state) between two requests.
CSS Houdini
<script> css.paintworklet.addmodule('csscomponent.js'); </script> this added module contains registerpaint() functions, which register completely configurable worklets.
Equality comparisons and sameness - JavaScript
unfortunately, object.is simply has to be thought of in terms of its specific characteristics, rather than its looseness or strictness with regard to the equality operators.
Details of the object model - JavaScript
you might think that, having called the workerbee constructor from inside the engineer constructor, you have set up inheritance appropriately for engineer objects.
Grammar and types - JavaScript
the first element of the car object defines a property, mycar, and assigns to it a new string, "saturn"; the second element, the getcar property, is immediately assigned the result of invoking the function (cartypes("honda")); the third element, the special property, uses an existing variable (sales).
Quantifiers - JavaScript
for example, /e?le?/ matches the "el" in "angel" and the "le" in "angle." if used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).
Text formatting - JavaScript
with simple unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result.
Memory Management - JavaScript
cycles are a common mistake that can generate memory leaks: var div; window.onload = function() { div = document.getelementbyid('mydivelement'); div.circularreference = div; div.lotsofdata = new array(10000).join('*'); }; in the above example, the dom element "mydivelement" has a circular reference to itself in the "circularreference" property.
SyntaxError: invalid regular expression flag "x" - JavaScript
regular expression flags can be used separately or together in any order, but there are only six of them in ecmascript.
SyntaxError: missing variable name - JavaScript
var x, y = "foo", var x, = "foo" var first = document.getelementbyid('one'), var second = document.getelementbyid('two'), // syntaxerror: missing variable name the fixed version: var x, y = "foo"; var x = "foo"; var first = document.getelementbyid('one'); var second = document.getelementbyid('two'); arrays array literals in javascript need square brackets around the values.
TypeError: "x" is not a constructor - JavaScript
to do this, you would write the following function: function car(make, model, year) { this.make = make; this.model = model; this.year = year; } now you can create an object called mycar as follows: var mycar = new car('eagle', 'talon tsi', 1993); in promises when returning an immediately-resolved or immediately-rejected promise, you do not need to create a new promise(...) and act on it.
TypeError: "x" is not a function - JavaScript
.prototype.foreach(), array.prototype.map(), array.prototype.filter(), array.prototype.reduce(), array.prototype.reduceright(), array.prototype.find() when working with map and set objects: map.prototype.foreach() and set.prototype.foreach() examples a typo in the function name in this case, which happens way too often, there is a typo in the method name: let x = document.getelementbyid('foo'); // typeerror: document.getelementbyid is not a function the correct function name is getelementbyid: let x = document.getelementbyid('foo'); function called on the wrong object for certain methods, you have to provide a (callback) function and it will work on specific objects only.
Warning: unreachable code after return statement - JavaScript
warnings will not be shown for semicolon-less returns if these statements follow it: throw break var function examples invalid cases function f() { var x = 3; x += 4; return x; // return exits the function immediately x -= 3; // so this line will never run; it is unreachable } function f() { return // this is treated like `return;` 3 + 4; // so the function returns, and this line is never reached } valid cases function f() { var x = 3; x += 4; x -= 3; return x; // ok: return after all other statements } function f() { return 3 + 4 // ok: semicolon-less return with expression...
SyntaxError: function statement requires a name - JavaScript
examples statements vs expressions a function statement (or function declaration) requires a name, this won't work: function () { return 'hello world'; } // syntaxerror: function statement requires a name you can use a function expression (assignment) instead: var greet = function() { return 'hello world'; }; or, you function is maybe intended to be an iife (immediately invoked function expression), which is a function that runs as soon as it is defined.
Arrow function expressions - JavaScript
let callback; callback = callback || function() {}; // ok callback = callback || () => {}; // syntaxerror: invalid arrow-function arguments callback = callback || (() => {}); // ok examples basic usage // an empty arrow function returns undefined let empty = () => {}; (() => 'foobar')(); // returns "foobar" // (this is an immediately invoked function expression) var simple = a => a > 15 ?
getter - JavaScript
get notifier() { delete this.notifier; return this.notifier = document.getelementbyid('bookmarked-notification-anchor'); }, for firefox code, see also the xpcomutils.jsm code module, which defines the definelazygetter() function.
Array.prototype[@@iterator]() - JavaScript
examples iteration using for...of loop html <ul id="letterresult"> </ul> javascript var arr = ['a', 'b', 'c']; var earr = arr[symbol.iterator](); var letterresult = document.getelementbyid('letterresult'); // your browser must support for..of loop // and let-scoped variables in for loops // const and var could also be used for (let letter of earr) { letterresult.innerhtml += "<li>" + letter + "</li>"; } result alternative iteration var arr = ['a', 'b', 'c', 'd', 'e']; var earr = arr[symbol.iterator](); console.log(earr.next().value); // a console.log(earr.next().val...
Array.prototype.reduce() - JavaScript
the reducer function takes four arguments: accumulator (acc) current value (cur) current index (idx) source array (src) your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value.
Array.prototype.filter() - JavaScript
the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
Array.prototype.find() - JavaScript
if so, find immediately returns the value of that element.
Array.prototype.findIndex() - JavaScript
if such an element is found, findindex() immediately returns the element's index.
Array.prototype.flatMap() - JavaScript
in other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one.
Array.prototype.forEach() - JavaScript
the thisarg value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
Array.prototype.indexOf() - JavaScript
// this version tries to optimize by only checking for "in" when looking for undefined and // skipping the definitely fruitless nan search.
Array.prototype.lastIndexOf() - JavaScript
array.lastindexof(element, idx - 1) : -1); } console.log(indices); // [4, 2, 0] note that we have to handle the case idx == 0 separately here because the element will always be found regardless of the fromindex parameter if it is the first element of the array.
Array.prototype.map() - JavaScript
the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
ArrayBuffer - JavaScript
instance properties arraybuffer.prototype.bytelength the read-only size, in bytes, of the arraybuffer.
BigInt64Array - JavaScript
bigint64array.prototype.bytelength returns the length (in bytes) of the bigint64array from the start of its arraybuffer.
BigUint64Array - JavaScript
biguint64array.prototype.bytelength returns the length (in bytes) of the biguint64array from the start of its arraybuffer.
DataView.prototype.buffer - JavaScript
examples using the buffer property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.buffer' in that specification.
DataView - JavaScript
dataview.prototype.bytelength the length (in bytes) of this view from the start of its arraybuffer.
Date - JavaScript
event to time goes here: dosomethingforalongtime() let end = date.now() let elapsed = end - start // elapsed time in milliseconds // using built-in methods let start = new date() // the event to time goes here: dosomethingforalongtime() let end = new date() let elapsed = end.gettime() - start.gettime() // elapsed time in milliseconds // to test a function and get back its return function printelapsedtime(ftest) { let nstarttime = date.now(), vreturn = ftest(), nendtime = date.now() console.log(`elapsed time: ${ string(nendtime - nstarttime) } milliseconds`) return vreturn } let yourfunctionreturn = printelapsedtime(yourfunction) note: in browsers that support the web performance api's high-resolution time feature, performance.now() can provide more reliable and pre...
Error.prototype.stack - JavaScript
argument values in the stack: prior to firefox 14, the function name would be followed by the argument values converted to string in parentheses immediately before the at (@) sign.
Float32Array - JavaScript
float32array.prototype.bytelength returns the length (in bytes) of the float32array from the start of its arraybuffer.
Float64Array - JavaScript
float64array.prototype.bytelength returns the length (in bytes) of the float64array from the start of its arraybuffer.
Function.prototype.bind() - JavaScript
if it's absolutely necessary and performance is not a concern, a far slower (but more specification-compliant solution) can be found at https://github.com/raynos/function-bind.
Int16Array - JavaScript
int16array.prototype.bytelength returns the length (in bytes) of the int16array from the start of its arraybuffer.
Int32Array - JavaScript
int32array.prototype.bytelength returns the length (in bytes) of the int32array from the start of its arraybuffer.
Int8Array - JavaScript
int8array.prototype.bytelength returns the length (in bytes) of the int8array from the start of its arraybuffer.
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
alue: ', ' }, { type: 'hour', value: '3' }, { type: 'literal', value: ':' }, { type: 'minute', value: '00' }, { type: 'literal', value: ':' }, { type: 'second', value: '42' }, { type: 'fractionalsecond', value: '000' }, { type: 'literal', value: ' ' }, { type: 'dayperiod', value: 'am' } ] now the information is available separately and it can be formatted and concatenated again in a customized way.
Intl.DisplayNames() constructor - JavaScript
possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
Intl.Locale.prototype.numberingSystem - JavaScript
als — algorithmic saur saurashtra digits shrd sharada digits sind khudawadi digits sinh sinhala lith digits sora sora_sompeng digits sund sundanese digits takr takri digits talu new tai lue digits taml tamil numerals — algorithmic tamldec modern tamil decimal digits telu telugu digits thai thai digits tirh tirhuta digits tibt tibetan digits traditio traditional numerals — may be algorithmic vaii vai digits wara warang citi digits wcho wancho digits examples setting the numberingsystem value via the locale string in the unicode locale string spec, the values that num...
Intl.NumberFormat.prototype.formatToParts() - JavaScript
providing you the string in parts: formatter.formattoparts(number); // return value: [ { type: "integer", value: "3" }, { type: "group", value: "." }, { type: "integer", value: "500" }, { type: "decimal", value: "," }, { type: "fraction", value: "00" }, { type: "literal", value: " " }, { type: "currency", value: "€" } ] now the information is available separately and it can be formatted and concatenated again in a customized way.
Map.prototype.forEach() - JavaScript
the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
Math.E - JavaScript
the math.e property represents the base of natural logarithms, e, approximately 2.718.
Math.LN10 - JavaScript
the math.ln10 property represents the natural logarithm of 10, approximately 2.302: math.ln10=ln(10)≈2.302\mathtt{\mi{math.ln10}} = \ln(10) \approx 2.302 the source for this interactive example is stored in a github repository.
Math.LN2 - JavaScript
the math.ln2 property represents the natural logarithm of 2, approximately 0.693: math.ln2=ln(2)≈0.693\mathtt{\mi{math.ln2}} = \ln(2) \approx 0.693 the source for this interactive example is stored in a github repository.
Math.LOG10E - JavaScript
the math.log10e property represents the base 10 logarithm of e, approximately 0.434: math.log10e=log10(e)≈0.434\mathtt{\mi{math.log10e}} = \log_10(e) \approx 0.434 the source for this interactive example is stored in a github repository.
Math.LOG2E - JavaScript
the math.log2e property represents the base 2 logarithm of e, approximately 1.442: math.log2e=log2(e)≈1.442\mathtt{\mi{math.log2e}} = \log_2(e) \approx 1.442 the source for this interactive example is stored in a github repository.
Math.PI - JavaScript
the math.pi property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159: math.pi=π≈3.14159\mathtt{\mi{math.pi}} = \pi \approx 3.14159 the source for this interactive example is stored in a github repository.
Math.SQRT1_2 - JavaScript
the math.sqrt1_2 property represents the square root of 1/2 which is approximately 0.707: math.sqrt1_2=12=12≈0.707\mathtt{\mi{math.sqrt1_2}} = \sqrt{\frac{1}{2}} = \frac{1}{\sqrt{2}} \approx 0.707 the source for this interactive example is stored in a github repository.
Math.SQRT2 - JavaScript
the math.sqrt2 property represents the square root of 2, approximately 1.414: math.sqrt2=2≈1.414\mathtt{\mi{math.sqrt2}} = \sqrt{2} \approx 1.414 the source for this interactive example is stored in a github repository.
Math.clz32() - JavaScript
now, inversing the bits reveals the lowest bits return 32 - clz(~integer) |0; } function ctron(integer) { // count trailing ones integer = integer | 0; // coerce to an integer return ctrz(~integer) |0; } // unfourtunately, asm.js demands slow crummy objects: return {a: ctrz, b: ctron}; })(window, null, null); var ctrz = counttrailsmethods.a; var ctron = counttrailsmethods.b; polyfill the following polyfill is the most efficient.
Math.random() - JavaScript
the math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.
Math.random() - JavaScript
the math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.
Number.EPSILON - JavaScript
property attributes of number.epsilon writable no enumerable no configurable no description the epsilon property has a value of approximately 2.2204460492503130808472633361816e-16, or 2-52.
Number.MAX_VALUE - JavaScript
property attributes of number.max_value writable no enumerable no configurable no description the max_value property has a value of approximately 1.79e+308, or 21024.
Number.MIN_VALUE - JavaScript
min_value has a value of approximately 5e-324.
Object.prototype.constructor - JavaScript
unfortunately, the answer is: it depends.
Object.defineProperties() - JavaScript
polyfill assuming a pristine execution environment with all names and properties referring to their initial values, object.defineproperties is almost completely equivalent (note the comment in iscallable) to the following reimplementation in javascript: function defineproperties(obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } function iscallable(v) { // nb: modify as necessary if other values than functions are callable.
Object - JavaScript
however, an object may be deliberately created for which this is not true (e.g.
Promise.allSettled() - JavaScript
in comparison, the promise returned by promise.all() may be more appropriate if the tasks are dependent on each other / if you'd like to immediately reject upon any of them rejecting.
Promise.race() - JavaScript
examples asynchronicity of promise.race this following example demonstrates the asynchronicity of promise.race: // we are passing as argument an array of promises that are already resolved, // to trigger promise.race as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.race(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code after the stack is empty settimeout(function(){ console.log('the stack is now empty'); console.log(p); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 33 } an empty iterable causes the returned promise to be forever pending: var...
Proxy - JavaScript
newval) { let oldval = obj[prop]; if (prop === 'selected') { if (oldval) { oldval.setattribute('aria-selected', 'false'); } if (newval) { newval.setattribute('aria-selected', 'true'); } } // the default behavior to store the value obj[prop] = newval; // indicate success return true; } }); let i1 = view.selected = document.getelementbyid('item-1'); //giving error here, i1 is null console.log(i1.getattribute('aria-selected')); // 'true' let i2 = view.selected = document.getelementbyid('item-2'); console.log(i1.getattribute('aria-selected')); // 'false' console.log(i2.getattribute('aria-selected')); // 'true' note: even if selected: !null, then giving oldval.setattribute is not a function value correction and an ex...
Planned changes to shared memory - JavaScript
sharedarraybuffer objects are in principle always available, but unfortunately the constructor on the global object is hidden, unless the two headers mentioned above are set, for compatibility with web content.
String.prototype.big() - JavaScript
size of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <fontsize=7>hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '2em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.big' in that specification.
String.prototype.fontcolor() - JavaScript
or('red') + ' is red in this line'); // '<font color="red">hello, world</font> is red in this line' console.log(worldstring.fontcolor('ff00') + ' is red in hexadecimal in this line'); // '<font color="ff00">hello, world</font> is red in hexadecimal in this line' with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.color = 'red'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fontcolor' in that specification.
String.prototype.fontsize() - JavaScript
e of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '0.7em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fontsize' in that specification.
String.prototype.small() - JavaScript
e of a string: var worldstring = 'hello, world'; console.log(worldstring.small()); // <small>hello, world</small> console.log(worldstring.big()); // <big>hello, world</big> console.log(worldstring.fontsize(7)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '0.7em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.small' in that specification.
Symbol.asyncIterator - JavaScript
ield "async"; yield "iteration!"; } }; (async () => { for await (const x of myasynciterable) { console.log(x); // expected output: // "hello" // "async" // "iteration!" } })(); when creating an api, remember that async iterables are designed to represent something iterable — like a stream of data or a list —, not to completely replace callbacks and events in most situations.
Symbol - JavaScript
let obj = {} obj[symbol('a')] = 'a' obj[symbol.for('b')] = 'b' obj['c'] = 'c' obj.d = 'd' for (let i in obj) { console.log(i) // logs "c" and "d" } symbols and json.stringify() symbol-keyed properties will be completely ignored when using json.stringify(): json.stringify({[symbol('foo')]: 'foo'}) // '{}' for more details, see json.stringify().
TypedArray.prototype.buffer - JavaScript
examples using the buffer property var buffer = new arraybuffer(8); var uint16 = new uint16array(buffer); uint16.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.buffer' in that specification.
TypedArray.prototype.filter() - JavaScript
the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
TypedArray.prototype.find() - JavaScript
if such an element is found, find immediately returns the value of that element.
TypedArray.prototype.findIndex() - JavaScript
if such an element is found, findindex immediately returns the index of that element.
TypedArray.prototype.forEach() - JavaScript
the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.
TypedArray.prototype.map() - JavaScript
the this value ultimately observable by mapfn is determined according to the usual rules for determining the this seen by a function.
TypedArray.prototype.set() - JavaScript
typedarray if the source array is a typed array, the two arrays may share the same underlying arraybuffer; the javascript engine will intelligently copy the source range of the buffer to the destination range.
TypedArray - JavaScript
typedarray.prototype.bytelength returns the length (in bytes) of the typed array.
Uint16Array - JavaScript
uint16array.prototype.bytelength returns the length (in bytes) of the uint16array from the start of its arraybuffer.
Uint32Array - JavaScript
uint32array.prototype.bytelength returns the length (in bytes) of the uint32array from the start of its arraybuffer.
Uint8Array - JavaScript
uint8array.prototype.bytelength returns the length (in bytes) of the uint8array.
Uint8ClampedArray - JavaScript
uint8clampedarray.prototype.bytelength returns the length (in bytes) of the uint8clampedarray from the start of its arraybuffer.
WeakMap - JavaScript
the second inconvenience is a memory leak because the arrays ensure that references to each key and each value are maintained indefinitely.
WeakRef - JavaScript
ement.textcontent = ++this.count; } else { // the element doesn't exist anymore console.log("the element is gone."); this.stop(); this.ref = null; } }; tick(); this.timer = setinterval(tick, 1000); } stop() { if (this.timer) { clearinterval(this.timer); this.timer = 0; } } } const counter = new counter(document.getelementbyid("counter")); counter.start(); settimeout(() => { document.getelementbyid("counter").remove(); }, 5000); specifications specification weakrefsthe definition of 'weakref' in that specification.
WebAssembly.Global() constructor - JavaScript
const output = document.getelementbyid('output'); function asserteq(msg, got, expected) { output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success!
WebAssembly.Global - JavaScript
const output = document.getelementbyid('output'); function asserteq(msg, got, expected) { output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success!
WebAssembly.Instance() constructor - JavaScript
syntax important: since instantiation for large modules can be expensive, developers should only use the instance() constructor when synchronous instantiation is absolutely required; the asynchronous webassembly.instantiatestreaming() method should be used at all other times.
WebAssembly.Memory.prototype.grow() - JavaScript
var memory = new webassembly.memory({initial:1, maximum:10}); we can then grow the instance by one page like so: const bytesperpage = 64 * 1024; console.log(memory.buffer.bytelength / bytesperpage); // "1" console.log(memory.grow(1)); // "1" console.log(memory.buffer.bytelength / bytesperpage); // "2" note the return value of grow() here is the previous number of webassembly pages.
WebAssembly.Module - JavaScript
a webassembly.module object contains stateless webassembly code that has already been compiled by the browser — this can be efficiently shared with workers, and instantiated multiple times.
WebAssembly - JavaScript
webassembly.module() contains stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.
eval() - JavaScript
fortunately, there's a very good alternative to eval(): simply using window.function().
Lexical grammar - JavaScript
if the digits after 0x are outside the range (0123456789abcdef), the following syntaxerror is thrown: "identifier starts immediately after numeric literal".
Exponentiation (**) - JavaScript
that is, you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number; doing so will cause a syntaxerror.
Logical OR assignment (||=) - JavaScript
examples setting default content if the "lyrics" element is empty, set the innerhtml to a default value: document.getelementbyid('lyrics').innerhtml ||= '<i>no lyrics.</i>' here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc.
async function expression - JavaScript
an async function expression can be used as an iife (immediately invoked function expression) which runs as soon as it is defined.
delete operator - JavaScript
in the following example, trees[3] is removed from the array completely using splice(): var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees); // ["redwood", "bay", "cedar", "maple"] specifications specification ecmascript (ecma-262)the definition of 'the delete operator' in that specification.
this - JavaScript
// when called as a listener, turns the related element blue function bluify(e) { // always true console.log(this === e.currenttarget); // true when currenttarget and target are the same object console.log(this === e.target); this.style.backgroundcolor = '#a5d9f3'; } // get a list of every element in the document var elements = document.getelementsbytagname('*'); // add bluify as a click listener so when the // element is clicked on, it turns blue for (var i = 0; i < elements.length; i++) { elements[i].addeventlistener('click', bluify, false); } in an inline event handler when the code is called from an inline on-event handler, its this is set to the dom element on which the listener is placed: <button onclick="alert(this.tagnam...
void operator - JavaScript
it should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator: void 2 == '2'; // (void 2) == '2', returns false void (2 == '2'); // void (2 == '2'), returns undefined examples immediately invoked function expressions when using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.
export - JavaScript
uld have: import { cube, foo, graph } from './my-module.js'; graph.options = { color:'blue', thickness:'3px' }; graph.draw(); console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888 it is important to note the following: you need to include this script in your html with a <script> element of type="module", so that it gets recognised as a module and dealt with appropriately.
for - JavaScript
function showoffsetpos(sid) { var nleft = 0, ntop = 0; for ( var oitnode = document.getelementbyid(sid); /* initialization */ oitnode; /* condition */ nleft += oitnode.offsetleft, ntop += oitnode.offsettop, oitnode = oitnode.offsetparent /* final-expression */ ); /* semicolon */ console.log('offset position of \'' + sid + '\' element:\n left: ' + nleft + 'px;\n top: ' + ntop + 'px;'); } /* example call: */ showoffsetpos('content'); // output: // "offset position of...
function* - JavaScript
calling a generator function does not execute its body immediately; an iterator object for the function is returned instead.
return - JavaScript
to avoid this problem (to prevent asi), you could use parentheses: return ( a + b ); examples interrupt a function a function immediately stops at the point where return is called.
switch - JavaScript
ultimately, this is due to both let statements being interpreted as duplicate declarations of the same variable name within the same block scope.
try...catch - JavaScript
if any statement within the try-block (or in a function called from within the try-block) throws an exception, control is immediately shifted to the catch-block.
var - JavaScript
so you can just type: function foo() { string('s') // note the function `string` is implicitly visible } ...because globalthis.hasownproperty('string') // true so the global object will ultimately be searched for unqualified identifiers.
Strict mode - JavaScript
those previous arguments remain available through arguments[i], so they're not completely inaccessible.
Template literals (Template strings) - JavaScript
(alternatively, it can return something completely different, as described in one of the following examples.) the name of the function used for the tag can be whatever you want.
JavaScript typed arrays - JavaScript
we can confirm that it is indeed 16 bytes long, and that's about it: if (buffer.bytelength === 16) { console.log("yes, it's 16 bytes."); } else { console.log("oh no, it's the wrong size!"); } before we can really work with this buffer, we need to create a view.
<mrow> - MathML
WebMathMLElementmrow
it allows for more intelligent line-breaking and indentation.
MathML documentation index - MathML
WebMathMLIndex
html becomes verbose when your document contains advanced structures like lists or tables but fortunately there are many generators from simple notations, wysiwyg editors and other content management systems to help writing web pages.
Media container formats (file types) - Web media technologies
unfortunately, neither of the relatively major lossless compression formats (flac and alac) are universally supported.
Digital video concepts - Web media technologies
in broadcast television, the luma signal is the primary signal, while the chrominance data is sent on a subcarrier.
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
to keep images from breaking out of their containers when the container becomes narrower than the image, developers started using css like the following: img { max-width: 100%; height: auto; } this is really useful for responsive layouts, but unfortunately it causes the jank problem to return — the above css overrides the width and height attribute information, meaning that if the image has not loaded for some reason, its height will be set to 0.
CSS and JavaScript animation performance - Web Performance
even if an element is in the middle of a transition, the new transition starts from the current style immediately instead of jumping to the end css state.
Critical rendering path - Web Performance
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.
Recommended Web Performance Timings: How long is too long? - Web Performance
as noted in the description of the critical rendering path, when received, browsers immediately start processing the html, rendering the content as it is received rather than waiting for additional assets to load.
Optimizing startup performance - Web Performance
the source application might have a main loop that can easily be made to operate asynchronously (by running each main loop iteration separately); startup is often just a continuous, monolithic procedure that might periodically update a progress meter.
Understanding latency - Web Performance
on a connection with low latency, requested resources will appear almost immediately.
Web Performance
lazy-loading javascript with dynamic imports when developers hear the term "lazy loading", they immediately think of below-the-fold imagery that loads when it scrolls into the viewport.
Privacy, permissions, and information security
to access http public key pinning (hpkp) hpkp is used by servers to instruct a client to associate a specific public key with the server going forward in order to decrease the likelihood of man-in-the-middle attacks http strict transport security (hsts) hsts is used by servers to let them protect themselves from protocol downgrade and cookie hijack attacks by letting sites tell clients that they can only use https to communicate with the server http/2 while http/2 technically does not have to use encryption, most browser developers are only supporting it when used with https, so it can be thought of in that regard as being security-related permissions api provides a way to determine the status of permissions for the current browser context ...
Installing and uninstalling web apps - Progressive web apps (PWAs)
unfortunately, there isn't a standard for icons and symbols used for operations such as this.
How to make PWAs installable - Progressive web apps (PWAs)
if the user clicks the button, there is a final step showing what the app will look like, and letting the user choose if they definitely want to add the app.
Introduction to progressive web apps - Progressive web apps (PWAs)
absolutely!
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
service workers are quite powerful as they can take control over network requests, modify them, serve custom responses retrieved from the cache, or synthesize responses completely.
Mobile first - Progressive web apps (PWAs)
i had to make sure both of these were not direct children of the <article>, otherwise the following would not work: #bottom, #top { font-size: 0.8em; position:absolute; right: 1em; text-decoration: none; } #top { color: white; top: 0.5em; } #bottom { bottom: 0.5em; } i also set their parents to be positioned relatively, so they would become the positioning contexts of the absolutely positioned elements (you don't want them to be positioned relative to the <body> element.) adding a mobile first layout the above layout is fine for narrower layouts, but it doesn't work very well when you get wider than about 480px.
Progressive web apps (PWAs)
this set of docs tells you all you need to know about them.
SVG Presentation Attributes - SVG: Scalable Vector Graphics
value: auto|text-bottom|alphabetic|ideographic|middle|central| mathematical|hanging|text-top; animatable: yes enable-background deprecated since svg 2 it tells the browser how to manage the accumulation of the background image.
clip-path - SVG: Scalable Vector Graphics
s is the same as having a custom clipping path with a clippathunits set to userspaceonuse --> <rect x="11" y="11" width="8" height="8" stroke="green" clip-path="circle() view-box" /> </svg> usage notes value <url> | [ <basic-shape> || <geometry-box> ] | none default value none animatable yes <geometry-box> an extra information to tell how a <basic-shape> is applied to an element: fill-box indicates to use the object bounding box; stroke-box indicates to use the object bounding box extended with the stroke; view-box indicates to use the nearest svg viewport as the reference box.
format - SVG: Scalable Vector Graphics
WebSVGAttributeformat
ttribute: format string format truedoc-pfr truedoc™ portable font resource embedded-opentype embedded opentype type-1 postscript™ type 1 truetype truetype opentype opentype, including truetype open truetype-gx truetype with gx extensions speedo speedo intellifont intellifont specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'format for <glyphref>' in that specification.
repeatCount - SVG: Scalable Vector Graphics
indefinite this value indicates that the animation will be repeated indefinitely (i.e.
repeatDur - SVG: Scalable Vector Graphics
indefinite this value indicates that the animation will be repeated indefinitely (i.e.
restart - SVG: Scalable Vector Graphics
WebSVGAttributerestart
<animate attributetype="xml" attributename="y" from="30" to="100" dur="5s" repeatcount="1" restart="always" /> </rect> <rect x="120" y="30" width="100" height="100"> <animate attributetype="xml" attributename="y" from="30" to="100" dur="5s" repeatcount="1" restart="whennotactive"/> </rect> <a id="restart"><text y="20">restart animation</text></a> </svg> document.getelementbyid("restart").addeventlistener("click", evt => { document.queryselectorall("animate").foreach(element => { element.beginelement(); }); }); usage notes value always | whennotactive | never default value always animatable no always this value indicates that the animation can be restarted at any time.
stroke-miterlimit - SVG: Scalable Vector Graphics
the outer tip and the inner corner of the miter) to stroke-width is directly related to the angle (theta) between the segments in user space by the formula: stroke-miterlimit = miterlength stroke-width = 1 sin ( θ 2 ) for example, a miter limit of 1.414 converts miters to bevels for theta less than 90 degrees, a limit of 4.0 converts them for theta less than approximately 29 degrees, and a limit of 10.0 converts them for theta less than approximately 11.5 degrees.
textLength - SVG: Scalable Vector Graphics
it starts by stashing references to the elements it will need to access, using document.getelementbyid(): const widthslider = document.getelementbyid("widthslider"); const widthdisplay = document.getelementbyid("widthdisplay"); const textelement = document.getelementbyid("hello"); const baselength = math.floor(textelement.textlength.baseval.value); widthslider.value = baselength; widthslider.addeventlistener("input", function(event) { textelement.textlength.baseval.newvaluespecifiedu...
xml:space - SVG: Scalable Vector Graphics
preserve this value tells the user agent to convert all newline and tab characters into spaces.
<feColorMatrix> - SVG: Scalable Vector Graphics
r' = r1 * r + r2 * g + r3 * b + r4 * a + r5 new red = [ r1 * old red ] + [ r2 * old green ] + [ r3 * old blue ] + [ r4 * old alpha ] + [ shift of r5 ] if, say, we want to make a completely black image redder, we can make the r5 a positive real number x, boosting the redness on every pixel of the new image by x.
<feDistantLight> - SVG: Scalable Vector Graphics
usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes azimuth elevation dom interface this element implements the svgfedistantlightelement interface.
<feOffset> - SVG: Scalable Vector Graphics
WebSVGElementfeOffset
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 dx dy dom interface this element implements the svgfeoffsetelement interface.
<fePointLight> - SVG: Scalable Vector Graphics
usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes x y z dom interface this element implements the svgfepointlightelement interface.
<feSpotLight> - SVG: Scalable Vector Graphics
usage context categorieslight source elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes specific attributes x y z pointsatx pointsaty pointsatz specularexponent limitingconeangle dom interface this element implements the svgfespotlightelement interface.
<font-face-format> - SVG: Scalable Vector Graphics
usage context categoriesfont elementpermitted contentempty attributes global attributes core attributes specific attributes string dom interface this element implements the svgfontfaceformatelement interface.
<font-face-src> - SVG: Scalable Vector Graphics
it serves as container for <font-face-name>, pointing to locally installed copies of this font, and <font-face-uri>, utilizing remotely defined fonts.
<font> - SVG: Scalable Vector Graphics
WebSVGElementfont
umber of the following elements, in any order:descriptive elements<font-face>, <glyph>, <hkern>, <missing-glyph>, <vkern> attributes global attributes core attributes presentation attributes class style externalresourcesrequired specific attributes horiz-origin-x horiz-origin-y horiz-adv-x vert-origin-x vert-origin-y vert-adv-y dom interface this element implements the svgfontelement interface.
<symbol> - SVG: Scalable Vector Graphics
WebSVGElementsymbol
that means that some browsers could refuse to directly display a <symbol> element even if the css display property tells otherwise.
SVG animation with SMIL - SVG: Scalable Vector Graphics
example 1: linear motion in this example, a blue circle bounces between the left and right edges of a black box, over and over again, indefinitely.
Basic shapes - SVG: Scalable Vector Graphics
ellipse an <ellipse> is a more general form of the <circle> element, where you can scale the x and y radius (commonly refferred to as the semimajor and semiminor axes in maths) of the circle separately.
Getting started - SVG: Scalable Vector Graphics
unfortunately, it is very problematic to get gzip-compressed svg files to work reliably across all svg capable user agents when served from a microsoft iis server, and firefox cannot load gzip-compressed svg from the local computer.
Introduction - SVG: Scalable Vector Graphics
the image and its components can also be transformed, composited together, or filtered to change their appearance completely.
SVG fonts - SVG: Scalable Vector Graphics
internet explorer hasn't considered implementing this, the functionality has been removed from chrome 38 (and opera 25) and firefox has postponed its implementation indefinitely to concentrate on woff.
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
actually, in mozilla firefox 1.5, the media type for files embedded into html using the html <embed> and <object> tags is (unfortunately) obtained in the same way as it's obtained for local files instead of using the http headers as it should.
Information Security Basics - Web security
confidentiality, integrity, and availability describes the primary security objectives, which are absolutely fundamental to understanding security security controls defines major categories of security controls and discusses their potential disadvantages tcp/ip security an overview of the tcp/ip model, with a focus on the security considerations for ssl threats briefly introduces major threat concepts vulnerabilities defin...
Insecure passwords - Web security
unfortunately, password reuse is a big problem.
Same-origin policy - Web security
the port number is checked separately by the browser.
How to turn off form autocompletion - Web security
lete="off" you can do this either for an entire form, or for specific input elements in a form: <form method="post" action="/form" autocomplete="off"> […] </form> <form method="post" action="/form"> […] <div> <label for="cc">credit card:</label> <input type="text" id="cc" name="cc" autocomplete="off"> </div> </form> setting autocomplete="off" on fields has two effects: it tells the browser not to save data inputted by the user for later autocompletion on similar forms, though heuristics for complying vary by browser.
Using shadow DOM - Web Components
note: as this blog post shows, it is actually fairly easy to work around closed shadow doms, and the hassle to completely hide them is often more than it's worth.
XPath
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.queryselectorall() methods, the node.childnodes properties, and other dom core features.
<xsl:namespace-alias> - XSLT: Extensible Stylesheet Language Transformations
to prevent a normally xsl:-prefixed literal result element (which should simply be copied as-is to the result tree) from being misunderstood by the processor, it is assigned a temporary namespace which is appropriately re-converted back to the xslt namespace in the output tree.
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
this intelligent structuring is particularly important as more and more data transfers are automated and take place between highly heterogeneous machines linked by a network.
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
transforming html unfortunately it is currently not supported to transform html nodes using xslt.
Basic Example - XSLT: Extensible Stylesheet Language Transformations
null); xslstylesheet = myxmlhttprequest.responsexml; xsltprocessor.importstylesheet(xslstylesheet); // load the xml file, example1.xml myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xml", false); myxmlhttprequest.send(null); xmldoc = myxmlhttprequest.responsexml; var fragment = xsltprocessor.transformtofragment(xmldoc, document); document.getelementbyid("example").innerhtml = ""; mydom = fragment; document.getelementbyid("example").appendchild(fragment); } ...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
// importnode is used to clone the nodes we want to process via xslt - true makes it do a deep clone var mynode = document.getelementbyid("example"); var clonednode = xmlref.importnode(mynode, true); // add the cloned dom into the xml document xmlref.appendchild(clonednode); once the stylesheet has been imported, xsltprocessor has to perform two methods for the actual transformation, namely xsltprocessor.transformtodocument() and xsltprocessor.transformtofragment().
Compiling a New C/C++ Module to WebAssembly - WebAssembly
you could then build your custom html completely from scratch, although this is an advanced approach; it is usually easier to use the provided html template.
WebAssembly Concepts - WebAssembly
a module is stateless and thus, like a blob, can be explicitly shared between windows and workers (via postmessage()).
Compiling an Existing C Module to WebAssembly - WebAssembly
to compile this program, you need to tell the compiler where it can find libwebp's header files using the -i flag and also pass it all the c files of libwebp that it needs.
WebAssembly
webassembly.module() a webassembly.module object contains stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.